forked from ooni/probe-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
420 lines (371 loc) · 10.9 KB
/
main.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
// Command miniooni is a simple binary for research and QA purposes
// with a CLI interface similar to MK and OONI Probe v2.x.
package main
import (
"context"
"fmt"
"os"
"path"
"runtime/debug"
"strings"
"time"
"github.com/apex/log"
"github.com/ooni/probe-cli/v3/internal/engine"
"github.com/ooni/probe-cli/v3/internal/humanize"
"github.com/ooni/probe-cli/v3/internal/legacy/assetsdir"
"github.com/ooni/probe-cli/v3/internal/logx"
"github.com/ooni/probe-cli/v3/internal/model"
"github.com/ooni/probe-cli/v3/internal/registry"
"github.com/ooni/probe-cli/v3/internal/runtimex"
"github.com/ooni/probe-cli/v3/internal/version"
"github.com/spf13/cobra"
)
// Options contains the options you can set from the CLI.
type Options struct {
Annotations []string
AuthFile string
Emoji bool
ExtraOptions []string
HomeDir string
Inputs []string
InputFilePaths []string
MaxRuntime int64
NoJSON bool
NoCollector bool
ProbeServicesURL string
Proxy string
Random bool
RepeatEvery int64
ReportFile string
SnowflakeRendezvous string
SoftwareName string
SoftwareVersion string
TorArgs []string
TorBinary string
Tunnel string
Verbose bool
Yes bool
}
// main is the main function of miniooni.
func main() {
var globalOptions Options
rootCmd := &cobra.Command{
Use: "miniooni",
Short: "miniooni is OONI's research client",
Args: cobra.NoArgs,
Version: version.Version,
}
rootCmd.SetVersionTemplate("{{ .Version }}\n")
flags := rootCmd.PersistentFlags()
flags.StringSliceVarP(
&globalOptions.Annotations,
"annotation",
"A",
[]string{},
"add KEY=VALUE annotation to the report (can be repeated multiple times)",
)
flags.BoolVar(
&globalOptions.Emoji,
"emoji",
false,
"whether to use emojis when logging",
)
flags.StringVar(
&globalOptions.HomeDir,
"home",
"",
"force specific home directory",
)
flags.BoolVarP(
&globalOptions.NoJSON,
"no-json",
"N",
false,
"disable writing to disk",
)
flags.BoolVarP(
&globalOptions.NoCollector,
"no-collector",
"n",
false,
"do not submit measurements to the OONI collector",
)
flags.StringVar(
&globalOptions.ProbeServicesURL,
"probe-services",
"",
"URL of the OONI backend instance you want to use",
)
flags.StringVar(
&globalOptions.Proxy,
"proxy",
"",
"set proxy URL to communicate with the OONI backend (mutually exclusive with --tunnel)",
)
flags.Int64Var(
&globalOptions.RepeatEvery,
"repeat-every",
0,
"wait the given number of seconds and then repeat the same measurement",
)
flags.StringVarP(
&globalOptions.ReportFile,
"reportfile",
"o",
"",
"set the output report file path (default: \"report.jsonl\")",
)
flags.StringVar(
&globalOptions.SnowflakeRendezvous,
"snowflake-rendezvous",
"domain_fronting",
"rendezvous method for --tunnel=torsf (one of: \"domain_fronting\" and \"amp\")",
)
flags.StringVar(
&globalOptions.SoftwareName,
"software-name",
"miniooni",
"Set the name of the application",
)
flags.StringVar(
&globalOptions.SoftwareVersion,
"software-version",
version.Version,
"Set the version of the application",
)
flags.StringSliceVar(
&globalOptions.TorArgs,
"tor-args",
[]string{},
"extra arguments for the tor binary (may be specified multiple times)",
)
flags.StringVar(
&globalOptions.TorBinary,
"tor-binary",
"",
"execute a specific tor binary",
)
flags.StringVar(
&globalOptions.Tunnel,
"tunnel",
"",
"tunnel to use to communicate with the OONI backend (one of: psiphon, tor, torsf)",
)
flags.BoolVarP(
&globalOptions.Verbose,
"verbose",
"v",
false,
"increase verbosity level",
)
flags.BoolVarP(
&globalOptions.Yes,
"yes",
"y",
false,
"assume yes as the answer to all questions",
)
rootCmd.MarkFlagsMutuallyExclusive("proxy", "tunnel")
registerAllExperiments(rootCmd, &globalOptions)
registerOONIRun(rootCmd, &globalOptions)
registerJavaScript(rootCmd, &globalOptions)
if err := rootCmd.Execute(); err != nil {
os.Exit(1)
}
}
// TODO(bassosimone): the current implementation is basically a cobra application
// where we hammered the previous miniooni code to make it work. We should
// obviously strive for more correctness. For example, it's a bit disgusting
// that MainWithConfiguration is invoked for both oonirun and random experiments.
// registerOONIRun registers the oonirun subcommand
func registerOONIRun(rootCmd *cobra.Command, globalOptions *Options) {
subCmd := &cobra.Command{
Use: "oonirun",
Short: "Runs a given OONI Run v2 link",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
MainWithConfiguration(cmd.Use, globalOptions)
},
}
rootCmd.AddCommand(subCmd)
flags := subCmd.Flags()
flags.StringSliceVarP(
&globalOptions.Inputs,
"input",
"i",
[]string{},
"URL of the OONI Run v2 descriptor to run (may be specified multiple times)",
)
flags.StringSliceVarP(
&globalOptions.InputFilePaths,
"input-file",
"f",
[]string{},
"Path to the OONI Run v2 descriptor to run (may be specified multiple times)",
)
flags.StringVarP(
&globalOptions.AuthFile,
"bearer-token-file",
"",
"",
"Path to a file containing a bearer token for fetching a remote OONI Run v2 descriptor",
)
}
// registerAllExperiments registers a subcommand for each experiment
func registerAllExperiments(rootCmd *cobra.Command, globalOptions *Options) {
for name, ff := range registry.AllExperiments {
subCmd := &cobra.Command{
Use: name,
Short: fmt.Sprintf("Runs the %s experiment", name),
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
MainWithConfiguration(cmd.Use, globalOptions)
},
}
rootCmd.AddCommand(subCmd)
flags := subCmd.Flags()
factory := ff()
switch factory.InputPolicy() {
case model.InputOrQueryBackend,
model.InputStrictlyRequired,
model.InputOptional,
model.InputOrStaticDefault:
flags.StringSliceVarP(
&globalOptions.InputFilePaths,
"input-file",
"f",
[]string{},
"path to file to supply test dependent input (may be specified multiple times)",
)
flags.StringSliceVarP(
&globalOptions.Inputs,
"input",
"i",
[]string{},
"add test-dependent input (may be specified multiple times)",
)
flags.Int64Var(
&globalOptions.MaxRuntime,
"max-runtime",
0,
"maximum runtime in seconds for the experiment (zero means infinite)",
)
flags.BoolVar(
&globalOptions.Random,
"random",
false,
"randomize the inputs list",
)
default:
// nothing
}
if doc := documentationForOptions(factory); doc != "" {
flags.StringSliceVarP(
&globalOptions.ExtraOptions,
"option",
"O",
[]string{},
doc,
)
}
}
}
// MainWithConfiguration is the miniooni main with a specific configuration
// represented by the experiment name and the current options.
//
// This function will panic in case of a fatal error. It is up to you that
// integrate this function to either handle the panic of ignore it.
func MainWithConfiguration(experimentName string, currentOptions *Options) {
runtimex.PanicOnError(engine.CheckEmbeddedPsiphonConfig(), "Invalid embedded psiphon config")
if currentOptions.Tunnel != "" {
currentOptions.Proxy = fmt.Sprintf("%s:///", currentOptions.Tunnel)
}
logHandler := logx.NewHandlerWithDefaultSettings()
logHandler.Emoji = currentOptions.Emoji
logger := &log.Logger{Level: log.InfoLevel, Handler: logHandler}
if currentOptions.Verbose {
logger.Level = log.DebugLevel
}
if currentOptions.ReportFile == "" {
currentOptions.ReportFile = "report.jsonl"
}
log.Log = logger
for {
mainSingleIteration(logger, experimentName, currentOptions)
if currentOptions.RepeatEvery <= 0 {
break
}
log.Infof("waiting %ds before repeating the measurement", currentOptions.RepeatEvery)
log.Info("use Ctrl-C to interrupt miniooni")
time.Sleep(time.Duration(currentOptions.RepeatEvery) * time.Second)
}
}
// mainSingleIteration runs a single iteration. There may be multiple iterations
// when the user specifies the --repeat-every command line flag.
func mainSingleIteration(logger model.Logger, experimentName string, currentOptions *Options) {
// We allow the inner code to fail but we stop propagating the panic here
// such that --repeat-every works as intended anyway
if currentOptions.RepeatEvery > 0 {
defer func() {
if r := recover(); r != nil {
log.Warnf("recovered from panic: %+v\n%s\n", r, debug.Stack())
}
}()
}
extraOptions := mustMakeMapStringAny(currentOptions.ExtraOptions)
annotations := mustMakeMapStringString(currentOptions.Annotations)
ctx := context.Background()
//Mon Jan 2 15:04:05 -0700 MST 2006
log.Infof("Current time: %s", time.Now().UTC().Format("2006-01-02 15:04:05 MST"))
homeDir := gethomedir(currentOptions.HomeDir)
runtimex.Assert(homeDir != "", "home directory is empty")
miniooniDir := path.Join(homeDir, ".miniooni")
err := os.MkdirAll(miniooniDir, 0700)
runtimex.PanicOnError(err, "cannot create $HOME/.miniooni directory")
// We cleanup the assets files used by versions of ooniprobe
// older than v3.9.0, where we started embedding the assets
// into the binary and use that directly. This cleanup doesn't
// remove the whole directory but only known files inside it
// and then the directory itself, if empty. We explicitly discard
// the return value as it does not matter to us here.
assetsDir := path.Join(miniooniDir, "assets")
_, _ = assetsdir.Cleanup(assetsDir)
log.Debugf("miniooni state directory: %s", miniooniDir)
log.Info("miniooni home directory: $HOME/.miniooni")
acquireUserConsent(miniooniDir, currentOptions)
sess := newSessionOrPanic(ctx, currentOptions, miniooniDir, logger)
defer func() {
_ = sess.Close()
log.Infof("whole session: recv %s, sent %s",
humanize.SI(sess.KibiBytesReceived()*1024, "byte"),
humanize.SI(sess.KibiBytesSent()*1024, "byte"),
)
}()
lookupBackendsOrPanic(ctx, sess)
lookupLocationOrPanic(ctx, sess)
// We handle the oonirun experiment name specially. The user must specify
// `miniooni -i {OONIRunURL} oonirun` to run a OONI Run URL (v1 or v2).
if experimentName == "oonirun" {
ooniRunMain(ctx, sess, currentOptions, annotations)
return
}
// Otherwise just run OONI experiments as we normally do.
runx(ctx, sess, experimentName, annotations, extraOptions, currentOptions)
}
func documentationForOptions(factory *registry.Factory) string {
var sb strings.Builder
options, err := factory.Options()
if err != nil || len(options) < 1 {
return ""
}
fmt.Fprint(&sb, "Pass KEY=VALUE options to the experiment. Available options:\n")
for name, info := range options {
if info.Doc == "" {
continue
}
fmt.Fprintf(&sb, "\n")
fmt.Fprintf(&sb, " -O, --option %s=<%s>\n", name, info.Type)
fmt.Fprintf(&sb, " %s\n", info.Doc)
}
return sb.String()
}