-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathcli.go
More file actions
556 lines (518 loc) · 14.2 KB
/
Copy pathcli.go
File metadata and controls
556 lines (518 loc) · 14.2 KB
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
package cli
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"os"
"path"
"runtime"
"strconv"
"strings"
"github.com/GrigoryKrasnochub/updaterini"
"github.com/ipfs/go-log/v2"
"github.com/libp2p/go-libp2p/p2p/host/eventbus"
"github.com/urfave/cli/v2"
"github.com/anywherelan/awl/api/apiclient"
"github.com/anywherelan/awl/config"
"github.com/anywherelan/awl/update"
)
const (
WithEnvCommandName = "with-env"
CliCommandName = "cli"
)
var defaultApiAddr = "127.0.0.1:" + strconv.Itoa(config.DefaultHTTPPort)
var binaryName = path.Base(os.Args[0])
type Application struct {
logger *log.ZapEventLogger
api *apiclient.Client
cliapp *cli.App
updateType update.ApplicationType
}
func New(updateType update.ApplicationType) *Application {
app := new(Application)
app.logger = log.Logger("awl/cli")
app.updateType = updateType
app.init()
return app
}
func (a *Application) Run() {
if len(os.Args) == 1 {
return
}
switch arg := os.Args[1]; arg {
case WithEnvCommandName:
// is handled in linux_root_hacks.go
return
case CliCommandName:
err := a.cliapp.Run(os.Args[1:])
if err != nil {
a.logger.Fatalf("Error occurred: %v", err)
}
os.Exit(0)
case "-h", "--help":
a.printGlobalHelp()
os.Exit(0)
case "-v", "--version":
a.printVersion()
os.Exit(0)
default:
fmt.Printf("Unknown command '%s'. Use '%s -h' for help, or run '%s' to start the server\n", arg, binaryName, binaryName)
os.Exit(-1)
}
}
func (a *Application) printGlobalHelp() {
fmt.Printf(`Usage: %s <command>
Run without a command to start the server.
Flags:
-h, --help Show context-sensitive help.
-v, --version Show version.
Commands:
cli Command line interface for Anywherelan
Run "%s <command> --help" for more information on a command.
`, binaryName, binaryName)
}
func (a *Application) printVersion() {
fmt.Printf("Anywherelan version %s (%s %s-%s)\n", config.Version, runtime.Version(), runtime.GOOS, runtime.GOARCH)
}
func (a *Application) init() {
a.cliapp = &cli.App{
Name: "awl",
HelpName: binaryName + " " + CliCommandName,
Description: "Anywherelan (awl for brevity) is a mesh VPN project, similar to tinc, direct wireguard or tailscale. " +
"Awl makes it easy to connect to any of your devices (at the IP protocol level) wherever they are." +
"\nSee more at the project page https://github.com/anywherelan/awl",
Version: config.Version,
Usage: "p2p mesh vpn",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "api_addr",
Usage: fmt.Sprintf("awl api address, example: %s", defaultApiAddr),
Required: false,
},
},
Commands: []*cli.Command{
{
Name: "me",
Usage: "Group of commands to work with your status and settings",
Subcommands: []*cli.Command{
{
Name: "status",
Usage: "Print your server status, network stats",
Before: a.initApiConnection,
Action: func(c *cli.Context) error {
return printStatus(a.api)
},
},
{
Name: "id",
Usage: "Print your peer id",
Before: a.initApiConnection,
Action: func(c *cli.Context) error {
return printPeerId(a.api)
},
},
{
Name: "rename",
Usage: "Rename your peer",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "name",
Usage: "peer name",
Required: true,
},
},
Before: a.initApiConnection,
Action: func(c *cli.Context) error {
return renameMe(a.api, c.String("name"))
},
},
{
Name: "list_proxies",
Usage: "Prints list of available SOCKS5 proxies",
Before: a.initApiConnection,
Action: func(c *cli.Context) error {
return listProxies(a.api)
},
},
{
Name: "set_proxy",
Usage: "Sets SOCKS5 proxy for your peer, empty pid/name means disable proxy",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "pid",
Usage: "peer id",
Required: false,
},
&cli.StringFlag{
Name: "name",
Usage: "peer name",
Required: false,
},
},
Before: func(c *cli.Context) error {
return a.initApiAndPeerId(c, false)
},
Action: func(c *cli.Context) error {
return setProxy(a.api, c.String("pid"))
},
},
},
},
{
Name: "peers",
Usage: "Group of commands to work with peers. Use to check friend requests and work with known peers",
Subcommands: []*cli.Command{
{
Name: "status",
Usage: "Print peers status",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "format",
Aliases: []string{"f"},
Required: false,
Value: "npslucev",
Usage: "control table columns list and order.Each char add column, write column chars together without gap. Use these chars to add specific columns:\n " +
"n - peers number\n p - peers name, domain and ip address\n i - peers id\n s - peers status\n l - peers last seen datetime\n v - peers awl version" +
"\n u - network usage by peer (in/out)\n c - list of peers connections (IP address + protocol)\n e - exit node status\n ",
},
},
Before: a.initApiConnection,
Action: func(c *cli.Context) error {
return printPeersStatus(a.api, c.String("format"))
},
},
{
Name: "requests",
Usage: "Print all incoming friend requests",
Before: a.initApiConnection,
Action: func(c *cli.Context) error {
return printFriendRequests(a.api)
},
},
{
Name: "add",
Usage: "Invite peer or accept existing invitation from this peer",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "pid",
Usage: "peer id",
Required: true,
},
&cli.StringFlag{
Name: "name",
Usage: "peer name",
Required: true,
},
&cli.StringFlag{
Name: "ip",
Usage: "override peer IP address",
Required: false,
},
},
Before: a.initApiConnection,
Action: func(c *cli.Context) error {
return addPeer(a.api, c.String("pid"), c.String("name"), c.String("ip"))
},
},
{
Name: "remove",
Usage: "Remove peer from the friends list",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "pid",
Usage: "peer id",
Required: false,
},
&cli.StringFlag{
Name: "name",
Usage: "peer name",
Required: false,
},
},
Before: a.initApiAndPeerIdRequired,
Action: func(c *cli.Context) error {
return removePeer(a.api, c.String("pid"))
},
},
{
Name: "rename",
Usage: "Change known peer name",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "pid",
Usage: "peer id",
Required: false,
},
&cli.StringFlag{
Name: "name",
Usage: "peer name",
Required: false,
},
&cli.StringFlag{
Name: "new_name",
Usage: "peer new name",
Required: true,
},
},
Before: a.initApiAndPeerIdRequired,
Action: func(c *cli.Context) error {
return changePeerAlias(a.api, c.String("pid"), c.String("new_name"))
},
},
{
Name: "update_domain",
Usage: "Change known peer domain name",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "pid",
Usage: "peer id",
Required: false,
},
&cli.StringFlag{
Name: "name",
Usage: "peer name",
Required: false,
},
&cli.StringFlag{
Name: "domain",
Usage: "peer domain name",
Required: true,
},
},
Before: a.initApiAndPeerIdRequired,
Action: func(c *cli.Context) error {
return changePeerDomain(a.api, c.String("pid"), c.String("domain"))
},
},
{
Name: "update_ip",
Usage: "Change known peer IP address",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "pid",
Usage: "peer id",
Required: false,
},
&cli.StringFlag{
Name: "name",
Usage: "peer name",
Required: false,
},
&cli.StringFlag{
Name: "ip",
Usage: "peer IP address",
Required: true,
},
},
Before: a.initApiAndPeerIdRequired,
Action: func(c *cli.Context) error {
return changePeerIP(a.api, c.String("pid"), c.String("ip"))
},
},
{
Name: "allow_exit_node",
Usage: "Allow known peer to use this device as exit node (as socks5 proxy)",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "pid",
Usage: "peer id",
Required: false,
},
&cli.StringFlag{
Name: "name",
Usage: "peer name",
Required: false,
},
&cli.BoolFlag{
Name: "allow",
Usage: "allow",
Required: false,
},
},
Before: a.initApiAndPeerIdRequired,
Action: func(c *cli.Context) error {
return setAllowUsingAsExitNode(a.api, c.String("pid"), c.Bool("allow"))
},
},
},
},
{
Name: "logs",
Aliases: []string{"log"},
Usage: "Prints application logs (default print 10 logs from the end of logs)",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "head",
Usage: "print logs from the beginning of logs",
Required: false,
},
&cli.IntFlag{
Name: "n",
Usage: "define number of rows of logs to output. Use 0 to print all",
Required: false,
Value: 10,
},
},
Before: a.initApiConnection,
Action: func(c *cli.Context) error {
logs, err := a.api.ApplicationLog(c.Int("n"), c.Bool("head"))
if err != nil {
return err
}
fmt.Println(logs)
return nil
},
},
{
Name: "p2p_info",
Usage: "Prints p2p debug info",
Before: a.initApiConnection,
Action: func(*cli.Context) error {
debugInfo, err := a.api.P2pDebugInfo()
if err != nil {
return err
}
bytes, err := json.MarshalIndent(debugInfo, "", " ")
if err != nil {
return err
}
fmt.Println(string(bytes))
return nil
},
},
{
Name: "update",
Usage: "Updates awl to the latest version",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "quiet",
Aliases: []string{"q"},
Usage: "update without confirmation message",
Required: false,
},
&cli.BoolFlag{
Name: "run",
Aliases: []string{"r"},
Usage: "run after a successful update",
Required: false,
},
},
Action: func(c *cli.Context) error {
_, _ = fmt.Fprintf(a.cliapp.Writer, "current version: %s\n", config.Version)
conf, err := config.LoadConfig(eventbus.NewBus())
if err != nil {
return fmt.Errorf("update: read config: %v", err)
}
updService, err := update.NewUpdateService(conf, a.logger, a.updateType)
if err != nil {
return fmt.Errorf("update: create update service: %v", err)
}
status, err := updService.CheckForUpdates()
if err != nil {
return fmt.Errorf("update: check for updates: %v", err)
}
if !status {
a.logger.Infof("app is already up-to-date")
return nil
}
if !c.Bool("quiet") {
status, err = a.yesNoPrompt(fmt.Sprintf("update to version %s: %s, %s", updService.NewVersion.VersionTag(),
updService.NewVersion.VersionName(), updService.NewVersion.VersionDescription()), true)
if !status || err != nil {
a.logger.Info("update stopped")
return err
}
}
a.logger.Infof("trying to update to version %s: %s", updService.NewVersion.VersionTag(),
updService.NewVersion.VersionName())
updResult, err := updService.DoUpdate()
if err != nil {
return fmt.Errorf("update: updating process: %v", err)
}
a.logger.Infof("updated successfully %s -> %s", conf.Version, updService.NewVersion.VersionTag())
if c.Bool("run") {
return updResult.DeletePreviousVersionFiles(updaterini.DeleteModRerunExec)
}
return updResult.DeletePreviousVersionFiles(updaterini.DeleteModKillProcess)
},
},
},
}
}
func (a *Application) initApiConnection(c *cli.Context) error {
apiAddr := c.String("api_addr")
if apiAddr != "" {
return a.initApiFromAddr(apiAddr)
}
conf, errConfig := config.LoadConfig(eventbus.NewBus())
if errConfig == nil {
return a.initApiFromAddr(conf.HttpListenAddress)
}
errDefault := a.initApiFromAddr(defaultApiAddr)
if errDefault == nil {
return nil
}
a.logger.Errorf("could not load config file, error: %v", errConfig)
a.logger.Errorf("could not connect to default api_addr (%s), error: %v", defaultApiAddr, errDefault)
return errors.New("no connection to api server")
}
func (a *Application) initApiFromAddr(addr string) error {
api := apiclient.New(addr)
_, err := api.PeerInfo()
if err != nil {
return fmt.Errorf("could not access api on address %s: %v", addr, err)
}
a.api = api
return nil
}
func (a *Application) initApiAndPeerIdRequired(c *cli.Context) error {
return a.initApiAndPeerId(c, true)
}
func (a *Application) initApiAndPeerId(c *cli.Context, isRequired bool) error {
err := a.initApiConnection(c)
if err != nil {
return err
}
pid := c.String("pid")
if pid != "" {
return nil
}
alias := c.String("name")
if alias == "" && isRequired {
return fmt.Errorf("peerID or name should be defined")
} else if alias == "" && !isRequired {
return nil
}
pid, err = getPeerIdByAlias(a.api, alias)
if err != nil {
return err
}
return c.Set("pid", pid)
}
func (a *Application) yesNoPrompt(message string, def bool) (bool, error) {
choices := "Yes/no, default yes"
if !def {
choices = "yes/No, default no"
}
r := bufio.NewReader(a.cliapp.Reader)
var s string
for {
_, err := fmt.Fprintf(a.cliapp.Writer, "%s (%s) ", message, choices)
if err != nil {
return false, err
}
s, _ = r.ReadString('\n')
s = strings.TrimSpace(s)
if s == "" {
return def, nil
}
s = strings.ToLower(s)
if s == "y" || s == "yes" {
return true, nil
}
if s == "n" || s == "no" {
return false, nil
}
}
}