-
Notifications
You must be signed in to change notification settings - Fork 17
/
config.go
456 lines (404 loc) · 13.7 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
// Copyright (c) 2013-2015 The btcsuite developers
// Copyright (c) 2015-2023 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
"errors"
"fmt"
"io"
"net"
"os"
"os/user"
"path/filepath"
"regexp"
"runtime"
"strings"
"github.com/decred/dcrd/dcrjson/v4"
"github.com/decred/dcrd/dcrutil/v4"
wallettypes "decred.org/dcrwallet/v5/rpc/jsonrpc/types"
dcrdtypes "github.com/decred/dcrd/rpc/jsonrpc/types/v4"
flags "github.com/jessevdk/go-flags"
)
const (
// unusableFlags are the command usage flags which this utility are not
// able to use. In particular it doesn't support websockets and
// consequently notifications.
unusableFlags = dcrjson.UFWebsocketOnly | dcrjson.UFNotification
)
// Authorization types.
const (
authTypeBasic = "basic"
authTypeClientCert = "clientcert"
)
var (
dcrdHomeDir = dcrutil.AppDataDir("dcrd", false)
dcrctlHomeDir = dcrutil.AppDataDir("dcrctl", false)
dcrwalletHomeDir = dcrutil.AppDataDir("dcrwallet", false)
defaultConfigFile = filepath.Join(dcrctlHomeDir, "dcrctl.conf")
defaultClientCertFile = filepath.Join(dcrctlHomeDir, "client.pem")
defaultClientKeyFile = filepath.Join(dcrctlHomeDir, "client-key.pem")
defaultRPCServer = "localhost"
defaultWalletRPCServer = "localhost"
defaultRPCCertFile = filepath.Join(dcrdHomeDir, "rpc.cert")
defaultWalletCertFile = filepath.Join(dcrwalletHomeDir, "rpc.cert")
)
// listCommands categorizes and lists all of the usable commands along with
// their one-line usage.
func listCommands() {
var categories = []struct {
Header string
Method interface{}
Usages []string
}{{
Header: "Chain Server Commands:",
Method: dcrdtypes.Method(""),
}, {
Header: "Wallet Server Commands (--wallet):",
Method: wallettypes.Method(""),
}}
for i := range categories {
method := categories[i].Method
methods := dcrjson.RegisteredMethods(method)
for _, methodStr := range methods {
switch method.(type) {
case dcrdtypes.Method:
method = dcrdtypes.Method(methodStr)
case wallettypes.Method:
method = wallettypes.Method(methodStr)
}
flags, err := dcrjson.MethodUsageFlags(method)
if err != nil {
// This should never happen since the method was just
// returned from the package, but be safe.
continue
}
// Skip the commands that aren't usable from this utility.
if flags&unusableFlags != 0 {
continue
}
usage, err := dcrjson.MethodUsageText(method)
if err != nil {
// This should never happen since the method was just
// returned from the package, but be safe.
continue
}
categories[i].Usages = append(categories[i].Usages, usage)
}
}
// Display the command according to their categories.
for i := range categories {
fmt.Println(categories[i].Header)
for _, usage := range categories[i].Usages {
fmt.Println(usage)
}
fmt.Println()
}
}
// config defines the configuration options for dcrctl.
//
// See loadConfig for details on the configuration load process.
type config struct {
ShowVersion bool `short:"V" long:"version" description:"Display version information and exit"`
ListCommands bool `short:"l" long:"listcommands" description:"List all of the supported commands and exit"`
ConfigFile string `short:"C" long:"configfile" description:"Path to configuration file"`
RPCUser string `short:"u" long:"rpcuser" description:"RPC username"`
RPCPassword string `short:"P" long:"rpcpass" default-mask:"-" description:"RPC password"`
RPCServer string `short:"s" long:"rpcserver" description:"RPC server to connect to"`
WalletRPCServer string `short:"w" long:"walletrpcserver" description:"Wallet RPC server to connect to"`
RPCCert string `short:"c" long:"rpccert" description:"RPC server certificate chain for validation"`
PrintJSON bool `short:"j" long:"json" description:"Print json messages sent and received"`
NoTLS bool `long:"notls" description:"Disable TLS"`
Proxy string `long:"proxy" description:"Connect via SOCKS5 proxy (eg. 127.0.0.1:9050)"`
ProxyUser string `long:"proxyuser" description:"Username for proxy server"`
ProxyPass string `long:"proxypass" default-mask:"-" description:"Password for proxy server"`
TestNet bool `long:"testnet" description:"Connect to testnet"`
SimNet bool `long:"simnet" description:"Connect to the simulation test network"`
TLSSkipVerify bool `long:"skipverify" description:"Do not verify tls certificates (not recommended!)"`
Wallet bool `long:"wallet" description:"Connect to wallet"`
AuthType string `long:"authtype" description:"The authorization type in use by the target server" choice:"basic" choice:"clientcert" default:"basic"`
ClientCert string `long:"clientcert" description:"Path to TLS certificate for client authentication"`
ClientKey string `long:"clientkey" description:"Path to TLS client authentication key"`
}
// normalizeAddress returns addr with the passed default port appended if
// there is not already a port specified.
func normalizeAddress(addr string, useTestNet, useSimNet, useWallet bool) string {
_, _, err := net.SplitHostPort(addr)
if err != nil {
var defaultPort string
switch {
case useTestNet:
if useWallet {
defaultPort = "19110"
} else {
defaultPort = "19109"
}
case useSimNet:
if useWallet {
defaultPort = "19557"
} else {
defaultPort = "19556"
}
default:
if useWallet {
defaultPort = "9110"
} else {
defaultPort = "9109"
}
}
return net.JoinHostPort(addr, defaultPort)
}
return addr
}
// cleanAndExpandPath expands environment variables and leading ~ in the
// passed path, cleans the result, and returns it.
func cleanAndExpandPath(path string) string {
// Nothing to do when no path is given.
if path == "" {
return path
}
// NOTE: The os.ExpandEnv doesn't work with Windows cmd.exe-style
// %VARIABLE%, but the variables can still be expanded via POSIX-style
// $VARIABLE.
path = os.ExpandEnv(path)
if !strings.HasPrefix(path, "~") {
return filepath.Clean(path)
}
// Expand initial ~ to the current user's home directory, or ~otheruser
// to otheruser's home directory. On Windows, both forward and backward
// slashes can be used.
path = path[1:]
var pathSeparators string
if runtime.GOOS == "windows" {
pathSeparators = string(os.PathSeparator) + "/"
} else {
pathSeparators = string(os.PathSeparator)
}
userName := ""
if i := strings.IndexAny(path, pathSeparators); i != -1 {
userName = path[:i]
path = path[i:]
}
homeDir := ""
var u *user.User
var err error
if userName == "" {
u, err = user.Current()
} else {
u, err = user.Lookup(userName)
}
if err == nil {
homeDir = u.HomeDir
}
// Fallback to CWD if user lookup fails or user has no home directory.
if homeDir == "" {
homeDir = "."
}
return filepath.Join(homeDir, path)
}
// fileExists reports whether the named file or directory exists.
func fileExists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
// loadConfig initializes and parses the config using a config file and command
// line options.
//
// The configuration proceeds as follows:
// 1. Start with a default config with sane settings
// 2. Pre-parse the command line to check for an alternative config file
// 3. Load configuration file overwriting defaults with any specified options
// 4. Parse CLI options and overwrite/add any specified options
//
// The above results in functioning properly without any config settings
// while still allowing the user to override settings with config files and
// command line options. Command line options always take precedence.
func loadConfig() (*config, []string, error) {
// Default config.
cfg := config{
ConfigFile: defaultConfigFile,
RPCServer: defaultRPCServer,
RPCCert: defaultRPCCertFile,
WalletRPCServer: defaultWalletRPCServer,
}
// Pre-parse the command line options to see if an alternative config
// file, the version flag, or the list commands flag was specified. Any
// errors aside from the help message error can be ignored here since
// they will be caught by the final parse below.
preCfg := cfg
preParser := flags.NewParser(&preCfg, flags.HelpFlag)
_, err := preParser.Parse()
if err != nil {
var e *flags.Error
if errors.As(err, &e) {
if e.Type != flags.ErrHelp {
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, "")
fmt.Fprintln(os.Stderr, "The special parameter `-` "+
"indicates that a parameter should be read "+
"from the\nnext unread line from standard input.")
os.Exit(1)
} else if e.Type == flags.ErrHelp {
fmt.Fprintln(os.Stdout, err)
fmt.Fprintln(os.Stdout, "")
fmt.Fprintln(os.Stdout, "The special parameter `-` "+
"indicates that a parameter should be read "+
"from the\nnext unread line from standard input.")
os.Exit(0)
}
}
}
// Show the version and exit if the version flag was specified.
appName := filepath.Base(os.Args[0])
appName = strings.TrimSuffix(appName, filepath.Ext(appName))
usageMessage := fmt.Sprintf("Use %s -h to show options", appName)
if preCfg.ShowVersion {
fmt.Printf("%s version %s (Go version %s %s/%s)\n", appName,
Version, runtime.Version(), runtime.GOOS, runtime.GOARCH)
os.Exit(0)
}
// Show the available commands and exit if the associated flag was
// specified.
if preCfg.ListCommands {
listCommands()
os.Exit(0)
}
if !fileExists(preCfg.ConfigFile) {
err := createDefaultConfigFile(preCfg.ConfigFile)
if err != nil {
fmt.Fprintf(os.Stderr, "Error creating a default config file: %v\n", err)
}
}
// Load additional config from file.
parser := flags.NewParser(&cfg, flags.Default)
err = flags.NewIniParser(parser).ParseFile(preCfg.ConfigFile)
if err != nil {
var perr *os.PathError
if !errors.As(err, &perr) {
fmt.Fprintf(os.Stderr, "Error parsing config file: %v\n",
err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
}
// Parse command line options again to ensure they take precedence.
remainingArgs, err := parser.Parse()
if err != nil {
var e *flags.Error
if !errors.As(err, &e) || e.Type != flags.ErrHelp {
fmt.Fprintln(os.Stderr, usageMessage)
}
return nil, nil, err
}
// Multiple networks can't be selected simultaneously.
numNets := 0
if cfg.TestNet {
numNets++
}
if cfg.SimNet {
numNets++
}
if numNets > 1 {
str := "%s: the testnet and simnet params can't be used " +
"together -- choose one of the two"
err := fmt.Errorf(str, "loadConfig")
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
// The auth type that uses client certifications requires TLS.
if cfg.NoTLS && cfg.AuthType == authTypeClientCert {
str := "%s: the %q authorization type requires TLS"
err := fmt.Errorf(str, "loadConfig", authTypeClientCert)
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
// Override the RPC certificate if the --wallet flag was specified and
// the user did not specify one.
if cfg.Wallet && cfg.RPCCert == defaultRPCCertFile {
cfg.RPCCert = defaultWalletCertFile
}
// Set path for the client key/cert for the clientcert authorization type
// when they're specified.
if cfg.AuthType == authTypeClientCert {
if cfg.ClientCert == "" {
cfg.ClientCert = defaultClientCertFile
}
if cfg.ClientKey == "" {
cfg.ClientKey = defaultClientKeyFile
}
cfg.ClientCert = cleanAndExpandPath(cfg.ClientCert)
cfg.ClientKey = cleanAndExpandPath(cfg.ClientKey)
}
// When the --wallet flag is specified, use the walletrpcserver port
// if specified.
if cfg.Wallet && cfg.WalletRPCServer != defaultWalletRPCServer {
cfg.RPCServer = cfg.WalletRPCServer
}
// Handle environment variable expansion in the RPC certificate path.
cfg.RPCCert = cleanAndExpandPath(cfg.RPCCert)
// Add default port to RPC server based on --testnet and --wallet flags
// if needed.
cfg.RPCServer = normalizeAddress(cfg.RPCServer, cfg.TestNet,
cfg.SimNet, cfg.Wallet)
return &cfg, remainingArgs, nil
}
// createDefaultConfig creates a basic config file at the given destination path.
// For this it tries to read the dcrd config file at its default path, and extract
// the RPC user and password from it.
func createDefaultConfigFile(destinationPath string) error {
// Nothing to do when there is no existing dcrd conf file at the default
// path to extract the details from.
dcrdConfigPath := filepath.Join(dcrdHomeDir, "dcrd.conf")
if !fileExists(dcrdConfigPath) {
return nil
}
// Read dcrd.conf from its default path
dcrdConfigFile, err := os.Open(dcrdConfigPath)
if err != nil {
return err
}
defer dcrdConfigFile.Close()
content, err := io.ReadAll(dcrdConfigFile)
if err != nil {
return err
}
// Extract the rpcuser
rpcUserRegexp, err := regexp.Compile(`(?m)^\s*rpcuser=([^\s]+)`)
if err != nil {
return err
}
userSubmatches := rpcUserRegexp.FindSubmatch(content)
if userSubmatches == nil {
// No user found, nothing to do
return nil
}
// Extract the rpcpass
rpcPassRegexp, err := regexp.Compile(`(?m)^\s*rpcpass=([^\s]+)`)
if err != nil {
return err
}
passSubmatches := rpcPassRegexp.FindSubmatch(content)
if passSubmatches == nil {
// No password found, nothing to do
return nil
}
// Create the destination directory if it does not exists
err = os.MkdirAll(filepath.Dir(destinationPath), 0700)
if err != nil {
return err
}
// Create the destination file and write the rpcuser and rpcpass to it
dest, err := os.OpenFile(destinationPath,
os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer dest.Close()
dest.WriteString(fmt.Sprintf("rpcuser=%s\nrpcpass=%s",
string(userSubmatches[1]), string(passSubmatches[1])))
return nil
}