forked from mehrdadrad/mylg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
437 lines (383 loc) · 8.44 KB
/
config.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
package cli
import (
"bytes"
"encoding/json"
"fmt"
"os"
"os/user"
"reflect"
"strconv"
"strings"
)
var defaultConfig = `{
"ping" : {
"timeout" : "2s",
"interval": "1s",
"count": 4
},
"hping" : {
"timeout" : "2s",
"method" : "HEAD",
"data" : "mylg",
"count" : 5
},
"web" : {
"port" : 8080,
"address" : "127.0.0.1"
},
"scan" : {
"port" : "1-500"
},
"trace" : {
"wait" : "2s",
"theme" : "dark"
},
"snmp" : {
"community" : "public",
"timeout" : "1s",
"version" : "2c",
"retries" : 1,
"port" : 161,
"securitylevel" : "noauthnopriv",
"authpass" : "nopass",
"authproto" : "sha",
"Privacypass" : "nopass",
"Privacyproto" : "aes"
}
}`
// Config represents configuration
type Config struct {
Ping Ping `json:"ping"`
Hping HPing `json:"hping"`
Web Web `json:"web"`
Scan Scan `json:"scan"`
Trace Trace `json:"trace"`
Snmp SNMP `json:"snmp"`
}
// Ping represents ping command options
type Ping struct {
Timeout string `json:"timeout"`
Interval string `json:"interval"`
Count int `json:"count"`
}
// HPing represents ping command options
type HPing struct {
Timeout string `json:"timeout"`
Method string `json:"method"`
Data string `json:"data"`
Count int `json:"count"`
}
// Web represents web command options
type Web struct {
Port int `json:"port"`
Address string `json:"address"`
}
// Scan represents scan command options
type Scan struct {
Port string `json:"port"`
}
// Trace represents trace command options
type Trace struct {
Wait string `json:"wait"`
Theme string `json:"theme"`
}
// SNMP represents nms command options
type SNMP struct {
Community string `json:"community"`
Timeout string `json:"timeout"`
Version string `json:"version"`
Retries int `json:"retries"`
Port int `json:"port"`
Securitylevel string `json:"securitylevel"`
Authpass string `json:"authpass"`
Authproto string `json:"authproto"`
Privacypass string `json:"privacypass"`
Privacyproto string `json:"privacyproto"`
}
// WriteConfig write config to disk
func WriteConfig(cfg Config) error {
f, err := cfgFile()
if err != nil {
return err
}
h, err := os.Create(f)
if err != nil {
return err
}
b, err := json.Marshal(cfg)
if err != nil {
return err
}
_, err = h.Write(bytes.ToLower(b))
if err != nil {
return err
}
h.Close()
return nil
}
// GetOptions returns option(s)/value(s) for specific command
func GetOptions(s interface{}, key string) ([]string, []interface{}) {
var (
opts []string
vals []interface{}
)
v := reflect.ValueOf(s)
t := v.Type()
for i := 0; i < v.NumField(); i++ {
if t.Field(i).Name == key {
f := v.Field(i)
ft := f.Type()
for j := 0; j < f.NumField(); j++ {
vals = append(vals, f.Field(j))
opts = append(opts, ft.Field(j).Name)
}
break
}
}
return opts, vals
}
// GetCMDNames returns command line names
func GetCMDNames(s interface{}) []string {
var fields []string
v := reflect.ValueOf(s)
t := v.Type()
for i := 0; i < t.NumField(); i++ {
fields = append(fields, t.Field(i).Name)
}
return fields
}
// UpgradeConfig adds / removes new command(s)/option(s)
func UpgradeConfig(cfg *Config) error {
var (
conf map[string]interface{}
cConf Config
)
b := make([]byte, 2048)
f, err := cfgFile()
if err != nil {
return err
}
h, err := os.Open(f)
if err != nil {
return err
}
n, _ := h.Read(b)
b = b[:n]
// load saved/old config to conf
json.Unmarshal(b, &conf)
// load default config to cConf
json.Unmarshal([]byte(defaultConfig), &cConf)
for _, cmd := range GetCMDNames(cConf) {
opts, vals := GetOptions(cConf, cmd)
for i, opt := range opts {
if v, ok := conf[strings.ToLower(cmd)].(interface{}); ok {
if _, ok = v.(map[string]interface{})[strings.ToLower(opt)]; !ok {
args := fmt.Sprintf("%s %s %v", cmd, opt, vals[i])
SetConfig(args, cfg)
}
} else {
// there is new command
args := fmt.Sprintf("%s %s %v", cmd, opt, vals[i])
SetConfig(args, cfg)
}
}
}
return nil
}
// LoadConfig loads configuration
func LoadConfig() Config {
var cfg Config
cfg = ReadConfig()
UpgradeConfig(&cfg)
return cfg
}
// InitConfig creates new config file
func InitConfig(f string) ([]byte, error) {
h, err := os.Create(f)
if err != nil {
return []byte(""), err
}
h.Chmod(os.FileMode(int(0600)))
h.WriteString(defaultConfig)
h.Close()
return []byte(defaultConfig), nil
}
// ReadConfig reads configuration from existing
// or default configuration
func ReadConfig() Config {
var (
b = make([]byte, 2048)
conf Config
err error
)
f, err := cfgFile()
if err != nil {
}
h, err := os.Open(f)
if err != nil {
switch {
case os.IsNotExist(err):
if b, err = InitConfig(f); err != nil {
println(err.Error())
}
case os.IsPermission(err):
println("cannot read configuration file due to insufficient permissions")
b = []byte(defaultConfig)
default:
println(err.Error())
b = []byte(defaultConfig)
}
} else {
n, _ := h.Read(b)
b = b[:n]
}
err = json.Unmarshal(b, &conf)
if err != nil {
println(err.Error())
b = []byte(defaultConfig)
json.Unmarshal(b, &conf)
}
return conf
}
// ReadDefaultConfig returns default configuration
func ReadDefaultConfig() (Config, error) {
var (
b = make([]byte, 2048)
conf Config
)
b = []byte(defaultConfig)
err := json.Unmarshal(b, &conf)
return conf, err
}
// cfgFile returns config file
func cfgFile() (string, error) {
user, err := user.Current()
if err != nil {
return "", err
}
return user.HomeDir + "/.mylg.config", nil
}
//
func optionType(v reflect.Value, opt string) string {
opt = strings.Title(opt)
for i := 0; i < v.NumField(); i++ {
if v.Type().Field(i).Name == opt {
return v.Type().Field(i).Type.Name()
}
}
return "nan"
}
// SetConfig handles update option's value
func SetConfig(args string, s *Config) error {
var (
v reflect.Value
integer int64
float float64
err error
)
args = strings.ToLower(args)
f := strings.Fields(args)
if len(f) < 3 {
helpSet()
return fmt.Errorf("syntax error")
}
cmd, opt, val := f[0], f[1], f[2]
opt = strings.Title(opt)
v = reflect.ValueOf(s)
v = reflect.Indirect(v)
v = v.FieldByName(strings.Title(cmd))
if !v.IsValid() {
return fmt.Errorf("invalid command")
}
switch optionType(v, opt) {
case "string":
// string
err = SetValue(v.Addr(), opt, fmt.Sprintf("%v", val))
case "int":
// integer
if integer, err = strconv.ParseInt(val, 10, 64); err == nil {
err = SetValue(v.Addr(), strings.Title(opt), integer)
} else {
err = fmt.Errorf("the value should be integer")
}
case "float":
// float
if float, err = strconv.ParseFloat(val, 64); err == nil {
err = SetValue(v.Addr(), opt, float)
} else {
err = fmt.Errorf("the value should be float")
}
default:
err = fmt.Errorf("invalid option")
}
if err != nil {
return err
}
// save config
err = WriteConfig(*s)
return err
}
// SetValue set optioni's value
func SetValue(v reflect.Value, rec string, val interface{}) error {
if v.Kind() != reflect.Ptr {
return fmt.Errorf("not a pointer value")
}
v = reflect.Indirect(v)
switch v.Kind() {
case reflect.Int:
if value, ok := val.(int64); ok {
v.SetInt(value)
} else {
return fmt.Errorf("the value should be integer")
}
case reflect.Float64:
if value, ok := val.(float64); ok {
v.SetFloat(value)
} else {
return fmt.Errorf("the value should be float")
}
case reflect.String:
if value, ok := val.(string); ok {
v.SetString(value)
} else {
return fmt.Errorf("the value shouldn't be number")
}
case reflect.Struct:
for i := 0; i < v.NumField(); i++ {
if v.Type().Field(i).Name == rec {
err := SetValue(v.Field(i).Addr(), rec, val)
if err != nil {
return err
}
}
}
}
return nil
}
// ShowConfig prints the configuration
func ShowConfig(s *Config) {
var v reflect.Value
v = reflect.ValueOf(s)
v = reflect.Indirect(v)
for i := 0; i < v.NumField(); i++ {
cmd := v.Type().Field(i).Name
cmd = strings.ToLower(cmd)
vv := v.Field(i).Addr()
vv = reflect.Indirect(vv)
for j := 0; j < vv.NumField(); j++ {
subCmd := vv.Type().Field(j).Name
subCmd = strings.ToLower(subCmd)
value := vv.Field(j)
fmt.Printf("set %-8s %-15s %v\n", cmd, subCmd, value)
}
}
}
// helpSet shows set command
func helpSet() {
println(`
usage:
set command option value
example:
set ping timeout 2s
`)
}