forked from mehrdadrad/mylg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.go
419 lines (382 loc) · 9.8 KB
/
cli.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
// Package cli provides all methods to control command line functions
package cli
import (
"encoding/json"
"fmt"
"github.com/chzyer/readline"
"github.com/mehrdadrad/mylg/banner"
"io"
"io/ioutil"
"net/http"
"regexp"
"strconv"
"strings"
)
const usage = `Usage:
The myLG tool, developed to troubleshoot networking situations.
The vi/emacs mode, almost all basic features are supported. Press tab to see which options are available.
connect <provider name> connects to external looking glass, press tab to see the menu
node <city/country name> connects to specific node at current looking glass, press tab to see the available nodes
local back to local
lg change mode to external looking glass
ns change mode to name server looking up
ping ping ip address or domain name
trace trace ip address or domain name (real-time w/ -r option)
dig nameserver look up
nms quick NMS - monitor device/server ports real-time
whois resolve AS number/IP/CIDR to holder (provided by ripe ncc)
hping ping through HTTP/HTTPS w/ GET/POST/HEAD methods
scan scan tcp ports (you can provide range >scan host minport maxport)
dump prints out a description of the contents of packets on a network interface
disc discover all the devices on a LAN
peering peering information (provided by peeringdb.com)
web web dashboard - opens dashboard at your default browser
Please visit http://mylg.io/doc for more information
`
// Readline structure
type Readline struct {
instance *readline.Instance
completer *readline.PrefixCompleter
prompt string
next chan struct{}
}
var (
cmds = []string{
"ping",
"trace",
"bgp",
"hping",
"connect",
"node",
"local",
"lg",
"ns",
"dig",
"nms",
"whois",
"scan",
"dump",
"disc",
"peering",
"speedtest",
"help",
"web",
"set",
"exit",
"show",
}
)
// Init set readline imain items
func Init(version string) *Readline {
var (
r Readline
err error
completer = readline.NewPrefixCompleter(pcItems()...)
)
r.completer = completer
r.instance, err = readline.NewEx(&readline.Config{
Prompt: "local> ",
HistoryFile: "/tmp/.mylg.history",
InterruptPrompt: "^C",
EOFPrompt: "exit",
AutoComplete: completer,
})
if err != nil {
panic(err)
}
banner.Println(version) // print banner
go checkUpdate(version) // check update version
return &r
}
// RemoveItemCompleter removes subitem(s) from a specific main item
func (r *Readline) RemoveItemCompleter(pcItem string) {
child := []readline.PrefixCompleterInterface{}
for _, p := range r.completer.Children {
if strings.TrimSpace(string(p.GetName())) != pcItem {
child = append(child, p)
}
}
r.completer.Children = child
}
// AddCompleter updates subitem(s) from a specific main item
func (r *Readline) AddCompleter(pcItem string, pcSubItems []string) {
var pc readline.PrefixCompleter
c := []readline.PrefixCompleterInterface{}
for _, item := range pcSubItems {
c = append(c, readline.PcItem(item))
}
pc.Name = []rune(pcItem + " ")
pc.Children = c
r.completer.Children = append(r.completer.Children, &pc)
}
// UpdateCompleter updates subitem(s) from a specific main item
func (r *Readline) UpdateCompleter(pcItem string, pcSubItems []string) {
child := []readline.PrefixCompleterInterface{}
var pc readline.PrefixCompleter
for _, p := range r.completer.Children {
if strings.TrimSpace(string(p.GetName())) == pcItem {
c := []readline.PrefixCompleterInterface{}
for _, item := range pcSubItems {
c = append(c, readline.PcItem(item))
}
pc.Name = []rune(pcItem + " ")
pc.Children = c
child = append(child, &pc)
} else {
child = append(child, p)
}
}
if len(pc.Name) < 1 {
// todo adding new
}
r.completer.Children = child
}
// SetPrompt set readline prompt and store it
func (r *Readline) SetPrompt(p string) {
p = strings.ToLower(p)
r.prompt = p
r.instance.SetPrompt(p + "> ")
}
// UpdatePromptN appends readline prompt
func (r *Readline) UpdatePromptN(p string, n int) {
var parts []string
p = strings.ToLower(p)
parts = strings.SplitAfterN(r.prompt, "/", n)
if n <= len(parts) && n > -1 {
parts[n-1] = p
r.prompt = strings.Join(parts, "")
} else {
r.prompt += "/" + p
}
r.instance.SetPrompt(r.prompt + "> ")
}
// GetPrompt returns the current prompt string
func (r *Readline) GetPrompt() string {
return r.prompt
}
// Refresh prompt
func (r *Readline) Refresh() {
r.instance.Refresh()
}
// SetVim set mode to vim
func (r *Readline) SetVim() {
if !r.instance.IsVimMode() {
r.instance.SetVimMode(true)
println("mode changed to vim")
} else {
println("mode already is vim")
}
}
// SetEmacs set mode to emacs
func (r *Readline) SetEmacs() {
if r.instance.IsVimMode() {
r.instance.SetVimMode(false)
println("mode changed to emacs")
} else {
println("mode already is emacs")
}
}
// Next trigers to read next line
func (r *Readline) Next() {
r.next <- struct{}{}
}
// Run the main loop
func (r *Readline) Run(cmd chan<- string, next chan struct{}) {
r.next = next
defer close(cmd)
LOOP:
for {
line, err := r.instance.Readline()
if err != nil { // io.EOF, readline.ErrInterrupt
switch err {
case io.EOF:
break LOOP
case readline.ErrInterrupt:
default:
println(err.Error())
break LOOP
}
}
cmd <- line
if _, ok := <-next; !ok {
break
}
}
}
// Close the readline instance
func (r *Readline) Close(next chan struct{}) {
r.instance.Close()
}
// Help print out the main help
func (r *Readline) Help() {
fmt.Println(usage)
}
// CMDRgx returns commands regex for validation
func CMDRgx() *regexp.Regexp {
expr := fmt.Sprintf(`(%s)\s{0,1}(.*)`, strings.Join(cmds, "|"))
re, _ := regexp.Compile(expr)
return re
}
func pcItems() []readline.PrefixCompleterInterface {
var (
i []readline.PrefixCompleterInterface
subItems = map[string][]readline.PrefixCompleterInterface{
"set": {
readline.PcItem("snmp",
readline.PcItem("community"),
readline.PcItem("version"),
readline.PcItem("timeout"),
),
readline.PcItem("ping",
readline.PcItem("interval"),
readline.PcItem("count"),
readline.PcItem("timeout"),
),
readline.PcItem("hping",
readline.PcItem("method"),
readline.PcItem("count"),
readline.PcItem("timeout"),
readline.PcItem("data"),
),
readline.PcItem("web",
readline.PcItem("port"),
readline.PcItem("address"),
),
readline.PcItem("scan",
readline.PcItem("port"),
),
readline.PcItem("trace",
readline.PcItem("wait"),
readline.PcItem("theme"),
),
},
}
)
for _, c := range cmds {
if _, ok := subItems[c]; !ok {
i = append(i, readline.PcItem(c))
} else {
i = append(i, readline.PcItem(c, subItems[c]...))
}
}
return i
}
// checkUpdate checks if any new version is available
func checkUpdate(version string) {
type mylg struct {
Version string
Update struct {
Enabled bool
}
}
var appCtl mylg
if version == "test" {
return
}
resp, err := http.Get("http://mylg.io/appctl/mylg")
if err != nil {
println("error: check update has been failed ")
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
println("error: update check failed (2)" + err.Error())
return
}
err = json.Unmarshal(body, &appCtl)
if err != nil {
return
}
if appCtl.Update.Enabled && version != appCtl.Version {
fmt.Printf("New version is available (v%s) at http://mylg.io/download\n", appCtl.Version)
}
}
//Flag parses the command arguments syntax:
// -flag=x
// -flag x
// help
func Flag(args string) (string, map[string]interface{}) {
var (
r = make(map[string]interface{}, 10)
err error
target string
)
// in case we have args without target
args = " " + args
// range
re := regexp.MustCompile(`(?i)\s-([a-z|0-9]+)[=|\s]{0,1}(\d+\-\d+)`)
f := re.FindAllStringSubmatch(args, -1)
for _, kv := range f {
r[kv[1]] = kv[2]
args = strings.Replace(args, kv[0], "", 1)
}
// none-boolean flags
for _, rgx := range []string{
`(?i)\s{1}-([a-z]+)[=|\s](-[0-9]+)`, // negative number
`(?i)\s{1}-([a-z|0-9]+)[=|\s]([0-9|a-z|'"{}:\.\/_@!#$%^&*)(\+]+)`} {
re = regexp.MustCompile(rgx)
f = re.FindAllStringSubmatch(args, -1)
for _, kv := range f {
if len(kv) > 1 {
// trim extra characters (' and ") from value
kv[2] = strings.Trim(kv[2], "'")
kv[2] = strings.Trim(kv[2], `"`)
r[kv[1]], err = strconv.Atoi(kv[2])
if err != nil {
r[kv[1]] = kv[2]
}
args = strings.Replace(args, kv[0], "", 1)
}
}
}
// boolean flags
re = regexp.MustCompile(`(?i)\s-([a-z|0-9]+)`)
f = re.FindAllStringSubmatch(args, -1)
for _, kv := range f {
if len(kv) == 2 {
r[kv[1]] = ""
args = strings.Replace(args, kv[0], "", 1)
}
}
// target
re = regexp.MustCompile(`(?i)^[^-][\S|\w\s]*`)
t := re.FindStringSubmatch(args)
if len(t) > 0 {
target = strings.TrimSpace(t[0])
}
// help
if m, _ := regexp.MatchString(`(?i)help$`, args); m {
r["help"] = true
}
return target, r
}
// SetFlag returns command option(s)
func SetFlag(flag map[string]interface{}, option string, v interface{}) interface{} {
if sValue, ok := flag[option]; ok {
switch v.(type) {
case int:
if v, ok := sValue.(int); ok {
return v
}
case string:
switch sValue.(type) {
case string:
if v, ok := sValue.(string); ok {
return v
}
case int:
str := strconv.FormatInt(int64(sValue.(int)), 10)
return str
case float64:
str := strconv.FormatFloat(sValue.(float64), 'f', -1, 64)
return str
}
case bool:
return !v.(bool)
default:
return sValue.(string)
}
}
return v
}