Skip to content

Commit 6c158e9

Browse files
committed
Use flag instead of flags
1 parent f9e4422 commit 6c158e9

File tree

9 files changed

+74
-70
lines changed

9 files changed

+74
-70
lines changed

chain.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ func makeChain(inChain []string) (outChain []string, err error) {
9999
log.Warn("No candidate remailers match selection criteria")
100100
}
101101

102-
if len(candidates) == 0 && flags.Remailer {
102+
if len(candidates) == 0 && flag.Remailer {
103103
log.Warn("Relaxing latency and uptime criteria to build chain")
104104
if len(outChain) == 0 {
105105
// Construct a list of suitable exit remailers

client.go

+23-23
Original file line numberDiff line numberDiff line change
@@ -31,19 +31,19 @@ func readMessage(filename string) []byte {
3131
fmt.Fprintf(os.Stderr, "%s: Malformed mail message\n", filename)
3232
os.Exit(1)
3333
}
34-
if flags.To != "" {
35-
msg.Header["To"] = []string{flags.To}
36-
if !strings.Contains(flags.To, "@") {
34+
if flag.To != "" {
35+
msg.Header["To"] = []string{flag.To}
36+
if !strings.Contains(flag.To, "@") {
3737
fmt.Fprintf(
3838
os.Stderr,
3939
"%s: Recipient doesn't appear to be an "+
4040
"email address\n",
41-
flags.To,
41+
flag.To,
4242
)
4343
}
4444
}
45-
if flags.Subject != "" {
46-
msg.Header["Subject"] = []string{flags.Subject}
45+
if flag.Subject != "" {
46+
msg.Header["Subject"] = []string{flag.Subject}
4747
}
4848
return assemble(*msg)
4949
}
@@ -59,20 +59,20 @@ func mixprep() {
5959
var plain []byte
6060
// final is consistent across multiple copies so we define it early
6161
final := newSlotFinal()
62-
if len(flags.Args) == 0 {
62+
if len(flag.Args) == 0 {
6363
//fmt.Println("Enter message, complete with headers. Ctrl-D to finish")
6464
plain, err = ioutil.ReadAll(os.Stdin)
6565
if err != nil {
6666
fmt.Fprintln(os.Stderr, err)
6767
os.Exit(1)
6868
}
69-
} else if len(flags.Args) == 1 {
69+
} else if len(flag.Args) == 1 {
7070
// A single arg should be the filename
71-
plain = readMessage(flags.Args[0])
72-
} else if len(flags.Args) >= 2 {
71+
plain = readMessage(flag.Args[0])
72+
} else if len(flag.Args) >= 2 {
7373
// Two args should be recipient and filename
74-
flags.To = flags.Args[0]
75-
plain = readMessage(flags.Args[1])
74+
flag.To = flag.Args[0]
75+
plain = readMessage(flag.Args[1])
7676
}
7777
// plainLen is the length of the plain byte message and can exceed
7878
// the total body size of the payload.
@@ -107,10 +107,10 @@ func mixprep() {
107107
// Read the chain from flag or config
108108
var inChain []string
109109
var inChainFunc []string
110-
if flags.Chain == "" {
110+
if flag.Chain == "" {
111111
inChain = strings.Split(cfg.Stats.Chain, ",")
112112
} else {
113-
inChain = strings.Split(flags.Chain, ",")
113+
inChain = strings.Split(flag.Chain, ",")
114114
}
115115
if len(inChain) == 0 {
116116
err = errors.New("empty input chain")
@@ -136,15 +136,15 @@ func mixprep() {
136136
}
137137
gotExit = false
138138
// If no copies flag is specified, use the config file NUMCOPIES
139-
if flags.Copies == 0 {
140-
flags.Copies = cfg.Stats.Numcopies
139+
if flag.Copies == 0 {
140+
flag.Copies = cfg.Stats.Numcopies
141141
}
142-
if flags.Copies > maxCopies {
142+
if flag.Copies > maxCopies {
143143
// Limit copies to a maximum of 10
144-
flags.Copies = maxCopies
144+
flag.Copies = maxCopies
145145
}
146146
// Copies loop begins here
147-
for n := 0; n < flags.Copies; n++ {
147+
for n := 0; n < flag.Copies; n++ {
148148
if gotExit {
149149
// Set the last node in the chain to the
150150
// previously select exitnode
@@ -169,7 +169,7 @@ func mixprep() {
169169
// Retain the entry hop. We need to mail the message to it.
170170
sendTo := chain[0]
171171
// Report the chain if we're running as a client.
172-
if flags.Client {
172+
if flag.Client {
173173
log.Infof("Chain: %s\n", strings.Join(chain, ","))
174174
}
175175
yamnMsg := encodeMsg(
@@ -182,7 +182,7 @@ func mixprep() {
182182
} // End of fragments loop
183183

184184
// Decide if we want to inject a dummy
185-
if !flags.NoDummy && Pubring.HaveStats() && crandom.Dice() < 80 {
185+
if !flag.NoDummy && Pubring.HaveStats() && crandom.Dice() < 80 {
186186
dummy()
187187
}
188188
}
@@ -333,10 +333,10 @@ func dummy() {
333333
plainMsg := []byte("I hope Len approves")
334334
// Make a single hop chain with a random node
335335
var inChain []string
336-
if flags.Chain == "" {
336+
if flag.Chain == "" {
337337
inChain = []string{"*", "*"}
338338
} else {
339-
inChain = strings.Split(flags.Chain, ",")
339+
inChain = strings.Split(flag.Chain, ",")
340340
}
341341
final := newSlotFinal()
342342
// Override the default delivery method (255 = Dummy)

config/config.go

+23-10
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package config
22

33
import (
44
"flag"
5+
"fmt"
56
"io/ioutil"
67
"os"
78
"path"
@@ -107,6 +108,22 @@ type Flags struct {
107108
MemInfo bool
108109
}
109110

111+
// GetCfg parses the command line flags and config file if they haven't been previously parsed.
112+
// This should be an init function but tests fail if flags are parsed in init.
113+
// See: https://github.com/golang/go/issues/46869
114+
func GetCfg() (*Flags, *Config) {
115+
var err error
116+
f := ParseFlags()
117+
// Some config defaults are derived from flags so ParseConfig is a flags method
118+
c, err := f.ParseConfig()
119+
if err != nil {
120+
// No logging is defined at this point so log the error to stderr
121+
fmt.Fprintf(os.Stderr, "Unable to parse config file: %v", err)
122+
os.Exit(1)
123+
}
124+
return f, c
125+
}
126+
110127
// WriteConfig will write the current config to a given filename
111128
func (c *Config) WriteConfig(filename string) error {
112129
data, err := yaml.Marshal(c)
@@ -139,15 +156,11 @@ func ParseFlags() *Flags {
139156
flag.BoolVar(&f.Send, "send", false, "Force pool send")
140157
flag.BoolVar(&f.Send, "S", false, "Force pool send")
141158
// Perform remailer actions
142-
flag.BoolVar(&f.Remailer, "remailer", false,
143-
"Perform routine remailer actions")
144-
flag.BoolVar(&f.Remailer, "M", false,
145-
"Perform routine remailer actions")
159+
flag.BoolVar(&f.Remailer, "remailer", false, "Perform routine remailer actions")
160+
flag.BoolVar(&f.Remailer, "M", false, "Perform routine remailer actions")
146161
// Start remailer as a daemon
147-
flag.BoolVar(&f.Daemon, "daemon", false,
148-
"Start remailer as a daemon. (Requires -M")
149-
flag.BoolVar(&f.Daemon, "D", false,
150-
"Start remailer as a daemon. (Requires -M")
162+
flag.BoolVar(&f.Daemon, "daemon", false, "Start remailer as a daemon. (Requires -M)")
163+
flag.BoolVar(&f.Daemon, "D", false, "Start remailer as a daemon. (Requires -M)")
151164
// Remailer chain
152165
flag.StringVar(&f.Chain, "chain", "", "Remailer chain")
153166
flag.StringVar(&f.Chain, "l", "", "Remailer chain")
@@ -158,8 +171,8 @@ func ParseFlags() *Flags {
158171
flag.StringVar(&f.Subject, "subject", "", "Subject header")
159172
flag.StringVar(&f.Subject, "s", "", "Subject header")
160173
// Number of copies
161-
flag.IntVar(&f.Copies, "copies", 0, "Number of copies")
162-
flag.IntVar(&f.Copies, "c", 0, "Number of copies")
174+
flag.IntVar(&f.Copies, "copies", 2, "Number of copies")
175+
flag.IntVar(&f.Copies, "c", 2, "Number of copies")
163176
// Config file
164177
flag.StringVar(&f.Config, "config", "", "Config file")
165178
// Read STDIN

config/config_test.go

-2
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,6 @@ import (
99
func TestFlags(t *testing.T) {
1010
expectedClient := false
1111
expectedCopies := 0
12-
13-
// This needs to be set prior to doing ParseFlags()
1412
f := ParseFlags()
1513
if f.Client != expectedClient {
1614
t.Errorf("Expected Client to contain \"%v\" but got \"%v\".", expectedClient, f.Client)

go.mod

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,4 @@ require (
1313
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b
1414
)
1515

16-
replace github.com/Masterminds/log-go v0.4.0 => github.com/crooks/log-go v0.4.1
16+
replace github.com/Masterminds/log-go v0.4.0 => github.com/crooks/log-go v0.4.1

go.sum

-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
2-
github.com/Masterminds/log-go v0.4.0 h1:RkiJ3U65qjGtHRfV2T74DurURYDDz0sBs7U383hC3Qs=
3-
github.com/Masterminds/log-go v0.4.0/go.mod h1:xPgU2yZAUbQCkvzB2I8OaqV5OFqOmq907g++YvJDL5Y=
42
github.com/crooks/log-go v0.4.1 h1:YVUpOxLAwCW0DWcxE6g4xEeMhODljWyNmGG09a/aGlw=
53
github.com/crooks/log-go v0.4.1/go.mod h1:xPgU2yZAUbQCkvzB2I8OaqV5OFqOmq907g++YvJDL5Y=
64
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=

pool.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ func serverPoolOutboundSend() {
4747
// on clients, where all messages should be sent instantly after creation.
4848
func poolOutboundSend() {
4949
var err error
50-
if cfg.Remailer.Daemon || flags.Daemon {
50+
if cfg.Remailer.Daemon || flag.Daemon {
5151
// This should never happen. If the server is started as a
5252
// daemon, the serverPoolOutboundSend process is initiated and
5353
// runs in an endless loop. This function would conflict with
@@ -62,7 +62,7 @@ func poolOutboundSend() {
6262
log.Warnf("Reading pool failed: %s", err)
6363
return
6464
}
65-
if flags.Remailer {
65+
if flag.Remailer {
6666
// During normal operation, the pool shouldn't be flushed.
6767
log.Warn("Flushing outbound remailer pool")
6868
}

server.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ func loopServer() (err error) {
8383
oneDay := time.Duration(dayLength) * time.Second
8484

8585
// Determine if this is a single run or the start of a Daemon
86-
runAsDaemon := cfg.Remailer.Daemon || flags.Daemon
86+
runAsDaemon := cfg.Remailer.Daemon || flag.Daemon
8787

8888
// Actually start the server loop
8989
if runAsDaemon {
@@ -252,15 +252,15 @@ func nagOperator() {
252252
)
253253
}
254254
// Complain about high pool rates.
255-
if cfg.Pool.Rate > 90 && !flags.Send {
255+
if cfg.Pool.Rate > 90 && !flag.Send {
256256
log.Warnf(
257257
"Your pool rate of %d is excessively high. Unless "+
258258
"testing, a lower setting is recommended.",
259259
cfg.Pool.Rate,
260260
)
261261
}
262262
// Complain about running a remailer with flag_send
263-
if flags.Send && flags.Remailer {
263+
if flag.Send && flag.Remailer {
264264
log.Warnf(
265265
"Your remailer will flush the outbound pool every "+
266266
"%d seconds. Unless you're testing, this is "+
@@ -418,7 +418,7 @@ func decodeV2(d *decMessage, slotDataBytes []byte) (err error) {
418418
writeMessageToPool(inter.getNextHop(), d.getPayload())
419419
stats.outYamn++
420420
// Decide if we want to inject a dummy
421-
if !flags.NoDummy && crandom.Dice() < 55 {
421+
if !flag.NoDummy && crandom.Dice() < 55 {
422422
dummy()
423423
stats.outDummy++
424424
}

yamn.go

+20-25
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package main
33
import (
44
"fmt"
55
"io/ioutil"
6+
stdlog "log"
67
"os"
78

89
"github.com/Masterminds/log-go"
@@ -24,17 +25,9 @@ const (
2425

2526
var (
2627
// flags - Command line flags
27-
flags *config.Flags
28+
flag *config.Flags
2829
// cfg - Config parameters
2930
cfg *config.Config
30-
// Trace loglevel
31-
Trace *log.Logger
32-
// Info loglevel
33-
Info *log.Logger
34-
// Warn loglevel
35-
Warn *log.Logger
36-
// Error loglevel
37-
Error *log.Logger
3831
// Pubring - Public Keyring
3932
Pubring *keymgr.Pubring
4033
// IDDb - Message ID log (replay protection)
@@ -45,20 +38,13 @@ var (
4538

4639
func main() {
4740
var err error
48-
flags = config.ParseFlags()
49-
if flags.Version {
41+
flag, cfg = config.GetCfg()
42+
if flag.Version {
5043
fmt.Println(version)
5144
os.Exit(0)
5245
}
53-
// Some config defaults are derived from flags so ParseConfig is a flags method
54-
cfg, err = flags.ParseConfig()
55-
if err != nil {
56-
// No logging is defined at this point so log the error to stderr
57-
fmt.Fprintf(os.Stderr, "Unable to parse config file: %v", err)
58-
os.Exit(1)
59-
}
6046
// If the debug flag is set, print the config and exit
61-
if flags.Debug {
47+
if flag.Debug {
6248
y, err := cfg.Debug()
6349
if err != nil {
6450
fmt.Printf("Debugging Error: %s\n", err)
@@ -74,6 +60,15 @@ func main() {
7460
fmt.Fprintf(os.Stderr, "%s: Unknown loglevel", cfg.General.Loglevel)
7561
os.Exit(1)
7662
}
63+
// If we're logging to a file, open the file and redirect output to it
64+
if cfg.General.LogToFile {
65+
logfile, err := os.OpenFile(cfg.Files.Logfile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
66+
if err != nil {
67+
fmt.Fprintf(os.Stderr, "%s: Error opening logfile: %v", cfg.Files.Logfile, err)
68+
os.Exit(1)
69+
}
70+
stdlog.SetOutput(logfile)
71+
}
7772
log.Current = log.StdLogger{Level: loglevel}
7873

7974
// Inform the user which (if any) config file was used.
@@ -84,9 +79,9 @@ func main() {
8479
}
8580

8681
// Setup complete, time to do some work
87-
if flags.Client {
82+
if flag.Client {
8883
mixprep()
89-
} else if flags.Stdin {
84+
} else if flag.Stdin {
9085
dir := maildir.Dir(cfg.Files.Maildir)
9186
newmsg, err := dir.NewDelivery()
9287
if err != nil {
@@ -100,20 +95,20 @@ func main() {
10095
}
10196
newmsg.Write(stdin)
10297
newmsg.Close()
103-
} else if flags.Remailer {
98+
} else if flag.Remailer {
10499
err = loopServer()
105100
if err != nil {
106101
panic(err)
107102
}
108-
} else if flags.Dummy {
103+
} else if flag.Dummy {
109104
injectDummy()
110-
} else if flags.Refresh {
105+
} else if flag.Refresh {
111106
fmt.Printf("Keyring refresh: from=%s, to=%s\n", cfg.Urls.Pubring, cfg.Files.Pubring)
112107
httpGet(cfg.Urls.Pubring, cfg.Files.Pubring)
113108
fmt.Printf("Stats refresh: from=%s, to=%s\n", cfg.Urls.Mlist2, cfg.Files.Mlist2)
114109
httpGet(cfg.Urls.Mlist2, cfg.Files.Mlist2)
115110
}
116-
if flags.Send {
111+
if flag.Send {
117112
// Flush the outbound pool
118113
poolOutboundSend()
119114
}

0 commit comments

Comments
 (0)