Skip to content

Commit

Permalink
cmd: imp code
Browse files Browse the repository at this point in the history
  • Loading branch information
Mizzick committed Sep 5, 2024
1 parent b86c63e commit f8a4e2a
Show file tree
Hide file tree
Showing 5 changed files with 133 additions and 132 deletions.
114 changes: 57 additions & 57 deletions internal/cmd/args.go
Original file line number Diff line number Diff line change
Expand Up @@ -368,12 +368,12 @@ var commandLineOptions = []*commandLineOption{
},
}

// parseCmdLineOptions parses the command-line options. opts must not be nil.
func parseCmdLineOptions(opts *configuration) (err error) {
// parseCmdLineOptions parses the command-line options. conf must not be nil.
func parseCmdLineOptions(conf *configuration) (err error) {
cmdName, args := os.Args[0], os.Args[1:]

flags := flag.NewFlagSet(cmdName, flag.ContinueOnError)
for i, fieldPtr := range mapOptions(opts) {
for i, fieldPtr := range mapOptions(conf) {
addOption(flags, fieldPtr, commandLineOptions[i])
}

Expand Down Expand Up @@ -443,7 +443,7 @@ func addOption(flags *flag.FlagSet, fieldPtr any, o *commandLineOption) {
case *[]int:
defineFlagVar(flags, newIntSliceValue(*fieldPtr, fieldPtr), o)
case *[]string:
defineFlagVar(flags, newStringsValue(*fieldPtr, fieldPtr), o)
defineFlagVar(flags, newStringSliceValue(*fieldPtr, fieldPtr), o)
case encoding.TextUnmarshaler:
defineTextUnmarshalerFlag(flags, fieldPtr, o)
default:
Expand Down Expand Up @@ -493,19 +493,19 @@ func writeUsageLine(b *strings.Builder, o *commandLineOption) {

// processCmdLineOptions decides if dnsproxy should exit depending on the
// results of command-line option parsing.
func processCmdLineOptions(opts *configuration, parseErr error) (exitCode int, needExit bool) {
func processCmdLineOptions(conf *configuration, parseErr error) (exitCode int, needExit bool) {
if parseErr != nil {
// Assume that usage has already been printed.
return osutil.ExitCodeArgumentError, true
}

if opts.help {
if conf.help {
usage(os.Args[0], os.Stdout)

return osutil.ExitCodeSuccess, true
}

if opts.Version {
if conf.Version {
fmt.Printf("dnsproxy version %s\n", version.Version())

return osutil.ExitCodeSuccess, true
Expand All @@ -514,56 +514,56 @@ func processCmdLineOptions(opts *configuration, parseErr error) (exitCode int, n
return osutil.ExitCodeSuccess, false
}

// mapOptions returns options mapped with commandLineOptions.
func mapOptions(opts *configuration) map[int]any {
// mapOptions returns configuration mapped with commandLineOptions.
func mapOptions(conf *configuration) (m map[int]any) {
return map[int]any{
configPathIdx: &opts.ConfigPath,
logOutputIdx: &opts.LogOutput,
tlsCertPathIdx: &opts.TLSCertPath,
tlsKeyPathIdx: &opts.TLSKeyPath,
httpsServerNameIdx: &opts.HTTPSServerName,
httpsUserinfoIdx: &opts.HTTPSUserinfo,
dnsCryptConfigPathIdx: &opts.DNSCryptConfigPath,
ednsAddrIdx: &opts.EDNSAddr,
upstreamModeIdx: &opts.UpstreamMode,
listenAddrsIdx: &opts.ListenAddrs,
listenPortsIdx: &opts.ListenPorts,
httpsListenPortsIdx: &opts.HTTPSListenPorts,
tlsListenPortsIdx: &opts.TLSListenPorts,
quicListenPortsIdx: &opts.QUICListenPorts,
dnsCryptListenPortsIdx: &opts.DNSCryptListenPorts,
upstreamsIdx: &opts.Upstreams,
bootstrapDNSIdx: &opts.BootstrapDNS,
fallbacksIdx: &opts.Fallbacks,
privateRDNSUpstreamsIdx: &opts.PrivateRDNSUpstreams,
dns64PrefixIdx: &opts.DNS64Prefix,
privateSubnetsIdx: &opts.PrivateSubnets,
bogusNXDomainIdx: &opts.BogusNXDomain,
hostsFilesIdx: &opts.HostsFiles,
timeoutIdx: &opts.Timeout,
cacheMinTTLIdx: &opts.CacheMinTTL,
cacheMaxTTLIdx: &opts.CacheMaxTTL,
cacheSizeBytesIdx: &opts.CacheSizeBytes,
ratelimitIdx: &opts.Ratelimit,
ratelimitSubnetLenIPv4Idx: &opts.RatelimitSubnetLenIPv4,
ratelimitSubnetLenIPv6Idx: &opts.RatelimitSubnetLenIPv6,
udpBufferSizeIdx: &opts.UDPBufferSize,
maxGoRoutinesIdx: &opts.MaxGoRoutines,
tlsMinVersionIdx: &opts.TLSMinVersion,
tlsMaxVersionIdx: &opts.TLSMaxVersion,
helpIdx: &opts.help,
hostsFileEnabledIdx: &opts.HostsFileEnabled,
pprofIdx: &opts.Pprof,
versionIdx: &opts.Version,
verboseIdx: &opts.Verbose,
insecureIdx: &opts.Insecure,
ipv6DisabledIdx: &opts.IPv6Disabled,
http3Idx: &opts.HTTP3,
cacheOptimisticIdx: &opts.CacheOptimistic,
cacheIdx: &opts.Cache,
refuseAnyIdx: &opts.RefuseAny,
enableEDNSSubnetIdx: &opts.EnableEDNSSubnet,
dns64Idx: &opts.DNS64,
usePrivateRDNSIdx: &opts.UsePrivateRDNS,
configPathIdx: &conf.ConfigPath,
logOutputIdx: &conf.LogOutput,
tlsCertPathIdx: &conf.TLSCertPath,
tlsKeyPathIdx: &conf.TLSKeyPath,
httpsServerNameIdx: &conf.HTTPSServerName,
httpsUserinfoIdx: &conf.HTTPSUserinfo,
dnsCryptConfigPathIdx: &conf.DNSCryptConfigPath,
ednsAddrIdx: &conf.EDNSAddr,
upstreamModeIdx: &conf.UpstreamMode,
listenAddrsIdx: &conf.ListenAddrs,
listenPortsIdx: &conf.ListenPorts,
httpsListenPortsIdx: &conf.HTTPSListenPorts,
tlsListenPortsIdx: &conf.TLSListenPorts,
quicListenPortsIdx: &conf.QUICListenPorts,
dnsCryptListenPortsIdx: &conf.DNSCryptListenPorts,
upstreamsIdx: &conf.Upstreams,
bootstrapDNSIdx: &conf.BootstrapDNS,
fallbacksIdx: &conf.Fallbacks,
privateRDNSUpstreamsIdx: &conf.PrivateRDNSUpstreams,
dns64PrefixIdx: &conf.DNS64Prefix,
privateSubnetsIdx: &conf.PrivateSubnets,
bogusNXDomainIdx: &conf.BogusNXDomain,
hostsFilesIdx: &conf.HostsFiles,
timeoutIdx: &conf.Timeout,
cacheMinTTLIdx: &conf.CacheMinTTL,
cacheMaxTTLIdx: &conf.CacheMaxTTL,
cacheSizeBytesIdx: &conf.CacheSizeBytes,
ratelimitIdx: &conf.Ratelimit,
ratelimitSubnetLenIPv4Idx: &conf.RatelimitSubnetLenIPv4,
ratelimitSubnetLenIPv6Idx: &conf.RatelimitSubnetLenIPv6,
udpBufferSizeIdx: &conf.UDPBufferSize,
maxGoRoutinesIdx: &conf.MaxGoRoutines,
tlsMinVersionIdx: &conf.TLSMinVersion,
tlsMaxVersionIdx: &conf.TLSMaxVersion,
helpIdx: &conf.help,
hostsFileEnabledIdx: &conf.HostsFileEnabled,
pprofIdx: &conf.Pprof,
versionIdx: &conf.Version,
verboseIdx: &conf.Verbose,
insecureIdx: &conf.Insecure,
ipv6DisabledIdx: &conf.IPv6Disabled,
http3Idx: &conf.HTTP3,
cacheOptimisticIdx: &conf.CacheOptimistic,
cacheIdx: &conf.Cache,
refuseAnyIdx: &conf.RefuseAny,
enableEDNSSubnetIdx: &conf.EnableEDNSSubnet,
dns64Idx: &conf.DNS64,
usePrivateRDNSIdx: &conf.UsePrivateRDNS,
}
}
14 changes: 7 additions & 7 deletions internal/cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,20 @@ import (
// Main is the entrypoint of dnsproxy CLI. Main may accept arguments, such as
// embedded assets and command-line arguments.
func Main() {
opts, exitCode, err := parseConfig()
conf, exitCode, err := parseConfig()
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, fmt.Errorf("parsing options: %w", err))
}

if opts == nil {
if conf == nil {
os.Exit(exitCode)
}

logOutput := os.Stdout
if opts.LogOutput != "" {
if conf.LogOutput != "" {
// #nosec G302 -- Trust the file path that is given in the
// configuration.
logOutput, err = os.OpenFile(opts.LogOutput, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o644)
logOutput, err = os.OpenFile(conf.LogOutput, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o644)
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, fmt.Errorf("cannot create a log file: %s", err))

Expand All @@ -50,16 +50,16 @@ func Main() {
Format: slogutil.FormatDefault,
// TODO(d.kolyshev): Consider making configurable.
AddTimestamp: true,
Verbose: opts.Verbose,
Verbose: conf.Verbose,
})

ctx := context.Background()

if opts.Pprof {
if conf.Pprof {
runPprof(l)
}

err = runProxy(ctx, l, opts)
err = runProxy(ctx, l, conf)
if err != nil {
l.ErrorContext(ctx, "running dnsproxy", slogutil.KeyError, err)

Expand Down
18 changes: 9 additions & 9 deletions internal/cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,8 +191,8 @@ type configuration struct {

// parseConfig returns options parsed from the command args or config file. If
// no options have been parsed, it returns a suitable exit code and an error.
func parseConfig() (opts *configuration, exitCode int, err error) {
opts = &configuration{
func parseConfig() (conf *configuration, exitCode int, err error) {
conf = &configuration{
HTTPSServerName: "dnsproxy",
UpstreamMode: string(proxy.UpstreamModeLoadBalance),
CacheSizeBytes: 64 * 1024,
Expand All @@ -201,21 +201,21 @@ func parseConfig() (opts *configuration, exitCode int, err error) {
RatelimitSubnetLenIPv6: 56,
}

err = parseCmdLineOptions(opts)
exitCode, needExit := processCmdLineOptions(opts, err)
err = parseCmdLineOptions(conf)
exitCode, needExit := processCmdLineOptions(conf, err)
if needExit {
return nil, exitCode, err
}

confPath := opts.ConfigPath
confPath := conf.ConfigPath
if confPath == "" {
return opts, exitCode, nil
return conf, exitCode, nil
}

// TODO(d.kolyshev): Bootstrap and use slog.
fmt.Printf("dnsproxy config path: %s\n", confPath)

err = parseConfigFile(opts, confPath)
err = parseConfigFile(conf, confPath)
if err != nil {
return nil, osutil.ExitCodeFailure, fmt.Errorf(
"parsing config file %s: %w",
Expand All @@ -225,13 +225,13 @@ func parseConfig() (opts *configuration, exitCode int, err error) {
}

// Parse command-line args again as it has priority over YAML config.
err = parseCmdLineOptions(opts)
err = parseCmdLineOptions(conf)
if err != nil {
// Don't wrap the error, because it's informative enough as is.
return nil, osutil.ExitCodeFailure, err
}

return opts, exitCode, nil
return conf, exitCode, nil
}

// parseConfigFile fills options with the settings from file read by the given
Expand Down
25 changes: 13 additions & 12 deletions internal/cmd/flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ var _ flag.Value = (*float32Value)(nil)

// Set implements the [flag.Value] interface for *float32Value.
func (i *float32Value) Set(s string) (err error) {
v, err := strconv.ParseInt(s, 0, 32)
v, err := strconv.ParseFloat(s, 32)
*i = float32Value(v)

return err
Expand Down Expand Up @@ -117,31 +117,32 @@ func (i *intSliceValue) String() (out string) {
return out
}

// stringsValue represent a struct with a slice of strings that can be defined
// as a flag for [flag.FlagSet].
type stringsValue struct {
// stringSliceValue represent a struct with a slice of strings that can be
// defined as a flag for [flag.FlagSet].
type stringSliceValue struct {
// values is the pointer to a slice of string to store parsed values.
values *[]string

// wiped indicates if the default value has been overwritten.
wiped bool
}

// newStringsValue returns a pointer to stringsValue with the given value.
func newStringsValue(val []string, p *[]string) (out *stringsValue) {
// newStringSliceValue returns a pointer to stringSliceValue with the given
// value.
func newStringSliceValue(val []string, p *[]string) (out *stringSliceValue) {
*p = val

return &stringsValue{
return &stringSliceValue{
values: p,
wiped: false,
}
}

// type check
var _ flag.Value = (*stringsValue)(nil)
var _ flag.Value = (*stringSliceValue)(nil)

// Set implements the [flag.Value] interface for *stringsValue.
func (i *stringsValue) Set(s string) (err error) {
// Set implements the [flag.Value] interface for *stringSliceValue.
func (i *stringSliceValue) Set(s string) (err error) {
if !i.wiped {
i.wiped = true
*i.values = []string{}
Expand All @@ -152,7 +153,7 @@ func (i *stringsValue) Set(s string) (err error) {
return nil
}

// String implements the [flag.Value] interface for *stringsValue.
func (i *stringsValue) String() (out string) {
// String implements the [flag.Value] interface for *stringSliceValue.
func (i *stringSliceValue) String() (out string) {
return fmt.Sprintf("%s", *i.values)
}
Loading

0 comments on commit f8a4e2a

Please sign in to comment.