-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathsshproxyctl.go
1023 lines (891 loc) · 24.7 KB
/
sshproxyctl.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
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015-2025 CEA/DAM/DIF
// Author: Arnaud Guignard <[email protected]>
// Contributor: Cyril Servant <[email protected]>
//
// This software is governed by the CeCILL-B license under French law and
// abiding by the rules of distribution of free software. You can use,
// modify and/ or redistribute the software under the terms of the CeCILL-B
// license as circulated by CEA, CNRS and INRIA at the following URL
// "http://www.cecill.info".
package main
import (
"encoding/csv"
"encoding/json"
"flag"
"fmt"
"log"
"math"
"net"
"os"
"os/user"
"sort"
"strconv"
"strings"
"time"
"github.com/cea-hpc/sshproxy/pkg/nodesets"
"github.com/cea-hpc/sshproxy/pkg/utils"
"github.com/olekukonko/tablewriter"
)
var (
// SshproxyVersion is set by Makefile
SshproxyVersion = "0.0.0+noproperlybuilt"
defaultConfig = "/etc/sshproxy/sshproxy.yaml"
)
func mustInitEtcdClient(configFile string) *utils.Client {
config, err := utils.LoadConfig(configFile, "", "", time.Now(), nil, "")
if err != nil {
log.Fatalf("reading configuration file %s: %v", configFile, err)
}
cli, err := utils.NewEtcdClient(config, nil)
if err != nil {
log.Fatalf("configuring etcd client: %v", err)
}
return cli
}
func getErrorBanner(configFile string) string {
config, err := utils.LoadConfig(configFile, "", "", time.Now(), nil, "")
if err != nil {
log.Fatalf("reading configuration file %s: %v", configFile, err)
}
return config.ErrorBanner
}
func displayCSV(rows [][]string) {
w := csv.NewWriter(os.Stdout)
w.WriteAll(rows)
if err := w.Error(); err != nil {
log.Fatalln("error writing csv:", err)
}
}
func displayJSON(objs interface{}) {
w := json.NewEncoder(os.Stdout)
if err := w.Encode(&objs); err != nil {
log.Fatalln("error writing JSON:", err)
}
}
func displayTable(headers []string, rows [][]string) {
table := tablewriter.NewWriter(os.Stdout)
colours := make([]tablewriter.Colors, len(headers))
for i := 0; i < len(headers); i++ {
colours[i] = tablewriter.Colors{tablewriter.Bold}
}
table.SetHeader(headers)
table.SetBorder(false)
table.SetAutoFormatHeaders(false)
//table.SetAutoWrapText(false)
table.SetHeaderColor(colours...)
table.AppendBulk(rows)
table.Render()
}
type aggConnection struct {
User string
Service string
Dest string
N int
Last time.Time
BwIn int
BwOut int
}
type aggregatedConnections []*aggConnection
func (ac aggregatedConnections) toRows(passthrough bool) [][]string {
rows := make([][]string, len(ac))
for i, c := range ac {
rows[i] = []string{
c.User,
c.Service,
c.Dest,
strconv.Itoa(c.N),
c.Last.Format("2006-01-02 15:04:05"),
byteToHuman(c.BwIn, passthrough),
byteToHuman(c.BwOut, passthrough),
}
}
return rows
}
type flatConnections []*utils.FlatConnection
func (fc flatConnections) getAllConnections(passthrough bool) [][]string {
rows := make([][]string, len(fc))
for i, c := range fc {
rows[i] = []string{
c.User,
c.Service,
c.From,
c.Dest,
c.Ts.Format("2006-01-02 15:04:05"),
byteToHuman(c.BwIn, passthrough),
byteToHuman(c.BwOut, passthrough),
}
}
return rows
}
func (fc flatConnections) getAggregatedConnections() aggregatedConnections {
type conn struct {
User string
Service string
Dest string
}
type connInfo struct {
N int
Ts time.Time
BwIn int
BwOut int
}
conns := make(map[conn]*connInfo)
for _, c := range fc {
key := conn{User: c.User, Service: c.Service, Dest: c.Dest}
if val, present := conns[key]; present {
val.N++
val.Ts = c.Ts
val.BwIn += c.BwIn
val.BwOut += c.BwOut
} else {
conns[key] = &connInfo{
N: 1,
Ts: c.Ts,
BwIn: c.BwIn,
BwOut: c.BwOut,
}
}
}
var connections aggregatedConnections
for k, v := range conns {
connections = append(connections, &aggConnection{
k.User,
k.Service,
k.Dest,
v.N,
v.Ts,
v.BwIn,
v.BwOut,
})
}
sort.Slice(connections, func(i, j int) bool {
switch {
case connections[i].User != connections[j].User:
return connections[i].User < connections[j].User
case connections[i].Service != connections[j].Service:
return connections[i].Service < connections[j].Service
case connections[i].Dest != connections[j].Dest:
return connections[i].Dest < connections[j].Dest
}
return false
})
return connections
}
func (fc flatConnections) displayCSV(allFlag bool) {
var rows [][]string
if allFlag {
rows = fc.getAllConnections(true)
} else {
rows = fc.getAggregatedConnections().toRows(true)
}
displayCSV(rows)
}
func (fc flatConnections) displayJSON(allFlag bool) {
var objs interface{}
if allFlag {
objs = fc
} else {
objs = fc.getAggregatedConnections()
}
displayJSON(objs)
}
func (fc flatConnections) displayTable(allFlag bool) {
var rows [][]string
if allFlag {
rows = fc.getAllConnections(false)
} else {
rows = fc.getAggregatedConnections().toRows(false)
}
var headers []string
if allFlag {
headers = []string{"User", "Service", "From", "Destination", "Start time", "Bw in", "Bw out"}
} else {
headers = []string{"User", "Service", "Destination", "# of conns", "Last connection", "Bw in", "Bw out"}
}
displayTable(headers, rows)
}
func showConnections(configFile string, csvFlag bool, jsonFlag bool, allFlag bool) {
cli := mustInitEtcdClient(configFile)
defer cli.Close()
var connections flatConnections
connections, err := cli.GetAllConnections()
if err != nil {
log.Fatalf("ERROR: getting connections from etcd: %v", err)
}
if csvFlag {
connections.displayCSV(allFlag)
} else if jsonFlag {
connections.displayJSON(allFlag)
} else {
connections.displayTable(allFlag)
}
}
type flatUserLight struct {
User string
Groups string
N int
BwIn int
BwOut int
}
type flatUsers []*utils.FlatUser
func (fu flatUsers) getAllUsers(allFlag bool, passthrough bool) [][]string {
rows := make([][]string, len(fu))
for i, v := range fu {
if allFlag {
rows[i] = []string{
v.User,
v.Service,
v.Groups,
fmt.Sprintf("%d", v.N),
byteToHuman(v.BwIn, passthrough),
byteToHuman(v.BwOut, passthrough),
v.Dest,
secondsToHuman(v.TTL, passthrough),
}
} else {
rows[i] = []string{
v.User,
v.Groups,
fmt.Sprintf("%d", v.N),
byteToHuman(v.BwIn, passthrough),
byteToHuman(v.BwOut, passthrough),
}
}
}
sort.Slice(rows, func(i, j int) bool {
if allFlag && rows[i][0] == rows[j][0] {
return rows[i][1] < rows[j][1]
} else {
return rows[i][0] < rows[j][0]
}
})
return rows
}
func (fu flatUsers) displayJSON(allFlag bool) {
if allFlag {
displayJSON(fu)
} else {
users := make([]*flatUserLight, len(fu))
for i, v := range fu {
users[i] = &flatUserLight{
v.User,
v.Groups,
v.N,
v.BwIn,
v.BwOut,
}
}
displayJSON(users)
}
}
func (fu flatUsers) displayCSV(allFlag bool) {
rows := fu.getAllUsers(allFlag, true)
displayCSV(rows)
}
func (fu flatUsers) displayTable(allFlag bool) {
rows := fu.getAllUsers(allFlag, false)
var headers []string
if allFlag {
headers = []string{"User", "Service", "Groups", "# of conns", "Bw in", "Bw out", "Persist to", "Persist TTL"}
} else {
headers = []string{"User", "Groups", "# of conns", "Bw in", "Bw out"}
}
displayTable(headers, rows)
}
func showUsers(configFile string, csvFlag bool, jsonFlag bool, allFlag bool) {
cli := mustInitEtcdClient(configFile)
defer cli.Close()
var users flatUsers
users, err := cli.GetAllUsers(allFlag)
if err != nil {
log.Fatalf("ERROR: getting users from etcd: %v", err)
}
if jsonFlag {
users.displayJSON(allFlag)
} else if csvFlag {
users.displayCSV(allFlag)
} else {
users.displayTable(allFlag)
}
}
type flatGroupLight struct {
Group string
Users string
N int
BwIn int
BwOut int
}
type flatGroups []*utils.FlatGroup
func (fg flatGroups) getAllGroups(allFlag bool, passthrough bool) [][]string {
rows := make([][]string, len(fg))
for i, v := range fg {
if allFlag {
rows[i] = []string{
v.Group,
v.Service,
v.Users,
fmt.Sprintf("%d", v.N),
byteToHuman(v.BwIn, passthrough),
byteToHuman(v.BwOut, passthrough),
}
} else {
rows[i] = []string{
v.Group,
v.Users,
fmt.Sprintf("%d", v.N),
byteToHuman(v.BwIn, passthrough),
byteToHuman(v.BwOut, passthrough),
}
}
}
sort.Slice(rows, func(i, j int) bool {
return rows[i][0] < rows[j][0]
})
return rows
}
func (fg flatGroups) displayJSON(allFlag bool) {
if allFlag {
displayJSON(fg)
} else {
groups := make([]*flatGroupLight, len(fg))
for i, v := range fg {
groups[i] = &flatGroupLight{
v.Group,
v.Users,
v.N,
v.BwIn,
v.BwOut,
}
}
displayJSON(groups)
}
}
func (fg flatGroups) displayCSV(allFlag bool) {
rows := fg.getAllGroups(allFlag, true)
displayCSV(rows)
}
func (fg flatGroups) displayTable(allFlag bool) {
rows := fg.getAllGroups(allFlag, false)
var headers []string
if allFlag {
headers = []string{"Group", "Service", "Users", "# of conns", "Bw in", "Bw out"}
} else {
headers = []string{"Group", "Users", "# of conns", "Bw in", "Bw out"}
}
displayTable(headers, rows)
}
func showGroups(configFile string, csvFlag bool, jsonFlag bool, allFlag bool) {
cli := mustInitEtcdClient(configFile)
defer cli.Close()
var groups flatGroups
groups, err := cli.GetAllGroups(allFlag)
if err != nil {
log.Fatalf("ERROR: getting groups from etcd: %v", err)
}
if jsonFlag {
groups.displayJSON(allFlag)
} else if csvFlag {
groups.displayCSV(allFlag)
} else {
groups.displayTable(allFlag)
}
}
func showHosts(configFile string, csvFlag bool, jsonFlag bool) {
cli := mustInitEtcdClient(configFile)
defer cli.Close()
hosts, err := cli.GetAllHosts()
if err != nil {
log.Fatalf("ERROR: getting hosts from etcd: %v", err)
}
if jsonFlag {
displayJSON(hosts)
return
}
rows := make([][]string, len(hosts))
for i, h := range hosts {
rows[i] = []string{
h.Hostname,
h.State.String(),
h.Ts.Format("2006-01-02 15:04:05"),
fmt.Sprintf("%d", h.N),
byteToHuman(h.BwIn, csvFlag),
byteToHuman(h.BwOut, csvFlag),
fmt.Sprintf("%d", h.HistoryN),
}
}
if csvFlag {
displayCSV(rows)
} else {
displayTable([]string{"Host", "State", "Last check", "# of conns", "Bw in", "Bw out", "# persist"}, rows)
}
}
func enableHost(host, port, configFile string) error {
cli := mustInitEtcdClient(configFile)
defer cli.Close()
key := fmt.Sprintf("%s:%s", host, port)
return cli.SetHost(key, utils.Up, time.Now())
}
func forgetHost(host, port, configFile string) error {
cli := mustInitEtcdClient(configFile)
defer cli.Close()
key := fmt.Sprintf("%s:%s", host, port)
return cli.DelHost(key)
}
func disableHost(host, port, configFile string) error {
cli := mustInitEtcdClient(configFile)
defer cli.Close()
key := fmt.Sprintf("%s:%s", host, port)
return cli.SetHost(key, utils.Disabled, time.Now())
}
func setErrorBanner(errorBanner string, expire time.Time, configFile string) error {
cli := mustInitEtcdClient(configFile)
defer cli.Close()
if errorBanner == "" {
return cli.DelErrorBanner()
}
return cli.SetErrorBanner(errorBanner, expire)
}
func delErrorBanner(configFile string) error {
cli := mustInitEtcdClient(configFile)
defer cli.Close()
return cli.DelErrorBanner()
}
func showErrorBanner(configFile string) {
cli := mustInitEtcdClient(configFile)
defer cli.Close()
errorBanner, expire, err := cli.GetErrorBanner()
if err != nil {
log.Fatalf("ERROR: getting error banner from etcd: %v", err)
}
fmt.Fprintf(flag.CommandLine.Output(), "Default error banner:\n%s\n", getErrorBanner(configFile))
if errorBanner != "" {
if expire == "" {
expire = "never"
}
fmt.Fprintf(flag.CommandLine.Output(), "Current error banner (expiration date: %s):\n%s\n", expire, errorBanner)
}
}
func showConfig(configFile, userString, groupsString, sourceString string) {
groupsMap := make(map[string]bool)
userComment := ""
// get system groups of given user, if it exists
userObject, err := user.Lookup(userString)
if err != nil {
userComment = " (unknown on this system)"
} else {
groupsMap, _ = utils.GetGroupUser(userObject)
}
// add given groups to system groups
for _, group := range strings.Split(groupsString, ",") {
if group != "" {
groupsMap[group] = true
}
}
// get config for given user / groups
config, err := utils.LoadConfig(configFile, userString, "", time.Now(), groupsMap, sourceString)
if err != nil {
log.Fatalf("reading configuration file %s: %v", configFile, err)
}
fmt.Fprintf(os.Stdout, "user = %s%s\n", userString, userComment)
for _, configLine := range utils.PrintConfig(config, groupsMap) {
fmt.Fprintln(os.Stdout, configLine)
}
}
func showVersion() {
fmt.Fprintf(flag.CommandLine.Output(), "%s version %s\n", os.Args[0], SshproxyVersion)
}
func usage() {
fmt.Fprintf(flag.CommandLine.Output(), `Usage: %s [OPTIONS] COMMAND
The commands are:
help display help on a command
version show version number and exit
show show states present in etcd
enable enable a host in etcd
forget forget a host/error_banner in etcd
disable disable a host in etcd
error_banner set the error banner in etcd
The common options are:
`, os.Args[0])
flag.PrintDefaults()
os.Exit(2)
}
func newHelpParser() *flag.FlagSet {
fs := flag.NewFlagSet("help", flag.ExitOnError)
fs.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), `Usage: %s help COMMAND
Show help of a command.
`, os.Args[0])
os.Exit(2)
}
return fs
}
func newVersionParser() *flag.FlagSet {
fs := flag.NewFlagSet("version", flag.ExitOnError)
fs.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), `Usage: %s version
Show version and exit.
`, os.Args[0])
os.Exit(2)
}
return fs
}
func newShowParser(csvFlag *bool, jsonFlag *bool, allFlag *bool, userString *string, groupsString *string, sourceString *string) *flag.FlagSet {
fs := flag.NewFlagSet("show", flag.ExitOnError)
fs.BoolVar(csvFlag, "csv", false, "show results in CSV format")
fs.BoolVar(jsonFlag, "json", false, "show results in JSON format")
fs.BoolVar(allFlag, "all", false, "show all connections / users / groups")
fs.StringVar(userString, "user", "", "show the config for this specific user and this user's groups (if any)")
fs.StringVar(groupsString, "groups", "", "show the config for these specific groups (comma separated)")
fs.StringVar(sourceString, "source", "", "show the config for this specific source (host[:port])")
fs.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), `Usage: %s show COMMAND [OPTIONS]
The commands are:
connections [-all] [-csv|-json] show connections stored in etcd
hosts [-csv|-json] show hosts stored in etcd
users [-all] [-csv|-json] show users stored in etcd
groups [-all] [-csv|-json] show groups stored in etcd
error_banner show error banners stored in etcd and in configuration
config [-user USER] [-groups GROUPS] [-source SOURCE] show the calculated configuration
The options are:
`, os.Args[0])
fs.PrintDefaults()
os.Exit(2)
}
return fs
}
func newEnableParser(allFlag *bool, hostString *string, portString *string) *flag.FlagSet {
fs := flag.NewFlagSet("enable", flag.ExitOnError)
fs.BoolVar(allFlag, "all", false, "enable all hosts present in config")
fs.StringVar(hostString, "host", "", "hostname to enable (can be a nodeset)")
fs.StringVar(portString, "port", "", "port to enable (can be a nodeset)")
fs.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), `Usage: %s enable -all|-host HOST [-port PORT]
Enable a previously disabled host in etcd.
`, os.Args[0])
fs.PrintDefaults()
os.Exit(2)
}
return fs
}
func newForgetParser(allFlag *bool, hostString *string, portString *string) *flag.FlagSet {
fs := flag.NewFlagSet("forget", flag.ExitOnError)
fs.BoolVar(allFlag, "all", false, "forget all hosts present in config")
fs.StringVar(hostString, "host", "", "hostname to forget (can be a nodeset)")
fs.StringVar(portString, "port", "", "port to forget (can be a nodeset)")
fs.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), `Usage: %s forget COMMAND [OPTIONS]
The commands are:
host -all|-host HOST [-port PORT] forget a host in etcd
error_banner forget the error_banner in etcd
The options are:
`, os.Args[0])
fs.PrintDefaults()
os.Exit(2)
}
return fs
}
func newDisableParser(allFlag *bool, hostString *string, portString *string) *flag.FlagSet {
fs := flag.NewFlagSet("disable", flag.ExitOnError)
fs.BoolVar(allFlag, "all", false, "disable all hosts present in config")
fs.StringVar(hostString, "host", "", "hostname to disable (can be a nodeset)")
fs.StringVar(portString, "port", "", "port to disable (can be a nodeset)")
fs.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), `Usage: %s disable -all|-host HOST [-port PORT]
Disable a host in etcd.
`, os.Args[0])
fs.PrintDefaults()
os.Exit(2)
}
return fs
}
func newErrorBannerParser(expireFlag *string) *flag.FlagSet {
fs := flag.NewFlagSet("error_banner", flag.ExitOnError)
fs.StringVar(expireFlag, "expire", "", "set the expiration date of this error banner. Format: YYYY-MM-DD[ HH:MM[:SS]]")
fs.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), `Usage: %s error_banner [-expire DATE] MESSAGE
Set the error banner in etcd.
The options are:
`, os.Args[0])
fs.PrintDefaults()
os.Exit(2)
}
return fs
}
func getHostPortFromCommandLine(allFlag bool, hostsNodeset string, portsNodeset string, configFile string) ([]string, error) {
_, nodesetDlclose, nodesetExpand := nodesets.InitExpander()
defer nodesetDlclose()
configDests, err := utils.LoadAllDestsFromConfig(configFile)
if err != nil {
return []string{}, fmt.Errorf("%s", err)
}
if allFlag && portsNodeset == "" {
return configDests, nil
}
var hosts []string
var ports []string
for _, configDest := range configDests {
host, port, err := utils.SplitHostPort(configDest)
if err != nil {
return []string{}, fmt.Errorf("%s", err)
}
hosts = append(hosts, host)
ports = append(ports, port)
}
if !allFlag {
hosts, err = nodesetExpand(hostsNodeset)
if err != nil {
return []string{}, fmt.Errorf("%s", err)
}
}
if portsNodeset != "" {
ports, err = nodesetExpand(portsNodeset)
if err != nil {
return []string{}, fmt.Errorf("%s", err)
}
}
var hostPorts []string
for _, port := range ports {
if iport, err := strconv.Atoi(port); err != nil {
return []string{}, fmt.Errorf("port \"%s\" must be an integer", port)
} else if iport < 0 || iport > 65535 {
return []string{}, fmt.Errorf("port \"%s\" must be in the 0-65535 range", port)
}
for _, host := range hosts {
if _, _, err := net.SplitHostPort(host + ":" + port); err != nil {
return []string{}, fmt.Errorf("%s", err)
}
hostPorts = append(hostPorts, host+":"+port)
}
}
return hostPorts, nil
}
func getErrorBannerFromCommandLine(args []string) (string, error) {
if len(args) == 1 {
return args[0], nil
}
return "", fmt.Errorf("wrong number of arguments")
}
func byteToHuman(b int, passthrough bool) string {
if passthrough {
return fmt.Sprintf("%d", b)
}
const unit = 1024
if b < unit {
return fmt.Sprintf("%d kB/s", b)
}
div, exp := unit, 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB/s", float32(b)/float32(div), "MGT"[exp])
}
func secondsToHuman(s int64, passthrough bool) string {
seconds := float64(s)
if seconds == 0 {
return ""
} else if passthrough {
return fmt.Sprintf("%.f", seconds)
} else if seconds < 60 {
return fmt.Sprintf("%.fs", seconds)
}
m := math.Floor(seconds / 60)
seconds -= m * 60
if m < 60 {
return fmt.Sprintf("%.fm %.fs", m, seconds)
}
h := math.Floor(m / 60)
m -= h * 60
if h < 24 {
return fmt.Sprintf("%.fh %.fm %.fs", h, m, seconds)
}
d := math.Floor(h / 24)
h -= d * 24
return fmt.Sprintf("%.fd %.fh %.fm %.fs", d, h, m, seconds)
}
func matchExpire(expire string) (time.Time, error) {
layouts := []string{"2006-01-02", "2006-01-02 15:04", "2006-01-02 15:04:05"}
loc, _ := time.LoadLocation("Local")
var err error
var t time.Time
for _, layout := range layouts {
t, err = time.ParseInLocation(layout, expire, loc)
if err == nil {
return t, nil
}
}
if expire != "" {
return t, err
}
return t, nil
}
func main() {
flag.Usage = usage
configFile := flag.String("c", defaultConfig, "path to configuration file")
flag.Parse()
if flag.NArg() == 0 {
fmt.Fprintf(os.Stderr, "ERROR: missing command\n\n")
usage()
}
var csvFlag bool
var jsonFlag bool
var allFlag bool
var expire string
var userString string
var groupsString string
var sourceString string
var hostString string
var portString string
parsers := map[string]*flag.FlagSet{
"help": newHelpParser(),
"version": newVersionParser(),
"show": newShowParser(&csvFlag, &jsonFlag, &allFlag, &userString, &groupsString, &sourceString),
"enable": newEnableParser(&allFlag, &hostString, &portString),
"forget": newForgetParser(&allFlag, &hostString, &portString),
"disable": newDisableParser(&allFlag, &hostString, &portString),
"error_banner": newErrorBannerParser(&expire),
}
cmd := flag.Arg(0)
args := flag.Args()[1:]
switch cmd {
case "help":
p := parsers[cmd]
p.Parse(args)
if p.NArg() == 0 {
usage()
}
subcmd := p.Arg(0)
if p2, present := parsers[subcmd]; present {
p2.Usage()
} else {
fmt.Fprintf(os.Stderr, "unknown command: %s\n\n", subcmd)
usage()
}
case "version":
p := parsers[cmd]
p.Parse(args)
showVersion()
case "show":
p := parsers[cmd]
p.Parse(args)
if p.NArg() == 0 {
fmt.Fprintf(os.Stderr, "ERROR: missing 'hosts', 'connections', 'users', 'groups', 'error_banner' or 'config'\n\n")
p.Usage()
}
subcmd := p.Arg(0)
// parse flags after subcommand
args = p.Args()[1:]
p.Parse(args)
switch subcmd {
case "hosts":
showHosts(*configFile, csvFlag, jsonFlag)
case "connections":
showConnections(*configFile, csvFlag, jsonFlag, allFlag)
case "users":
showUsers(*configFile, csvFlag, jsonFlag, allFlag)
case "groups":
showGroups(*configFile, csvFlag, jsonFlag, allFlag)
case "error_banner":
showErrorBanner(*configFile)
case "config":
showConfig(*configFile, userString, groupsString, sourceString)
default:
fmt.Fprintf(os.Stderr, "ERROR: unknown subcommand: %s\n\n", subcmd)
p.Usage()
}
case "enable":
p := parsers[cmd]
p.Parse(args)
if !allFlag && hostString == "" {
fmt.Fprintf(os.Stderr, "ERROR: missing '-all' or '-host'\n\n")
p.Usage()
}
hostPorts, err := getHostPortFromCommandLine(allFlag, hostString, portString, *configFile)
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: %s\n\n", err)
p.Usage()
}
for _, hostPort := range hostPorts {
host, port, err := utils.SplitHostPort(hostPort)
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: %s\n\n", err)
p.Usage()
}
enableHost(host, port, *configFile)
}
case "forget":
p := parsers[cmd]
p.Parse(args)
if p.NArg() == 0 {
fmt.Fprintf(os.Stderr, "ERROR: missing 'host' or 'error_banner'\n\n")
p.Usage()
}
subcmd := p.Arg(0)
// parse flags after subcommand
args = p.Args()[1:]
p.Parse(args)
switch subcmd {
case "host":
if !allFlag && hostString == "" {
fmt.Fprintf(os.Stderr, "ERROR: missing '-all' or '-host'\n\n")
p.Usage()
}
hostPorts, err := getHostPortFromCommandLine(allFlag, hostString, portString, *configFile)
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: %s\n\n", err)
p.Usage()
}
for _, hostPort := range hostPorts {
host, port, err := utils.SplitHostPort(hostPort)
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: %s\n\n", err)
p.Usage()
}
forgetHost(host, port, *configFile)
}
case "error_banner":
delErrorBanner(*configFile)
}
case "disable":
p := parsers[cmd]
p.Parse(args)
if !allFlag && hostString == "" {
fmt.Fprintf(os.Stderr, "ERROR: missing '-all' or '-host'\n\n")
p.Usage()
}
hostPorts, err := getHostPortFromCommandLine(allFlag, hostString, portString, *configFile)
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: %s\n\n", err)
p.Usage()
}
for _, hostPort := range hostPorts {
host, port, err := utils.SplitHostPort(hostPort)
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: %s\n\n", err)
p.Usage()
}
disableHost(host, port, *configFile)
}