forked from bettercap/bettercap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodule_handler.go
89 lines (74 loc) · 1.83 KB
/
module_handler.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
package session
import (
"encoding/json"
"fmt"
"regexp"
"strconv"
"sync"
"github.com/evilsocket/islazy/str"
"github.com/evilsocket/islazy/tui"
"github.com/bettercap/readline"
)
const IPv4Validator = `^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$`
type ModuleHandler struct {
sync.Mutex
Name string
Description string
Parser *regexp.Regexp
Completer *readline.PrefixCompleter
exec func(args []string) error
}
func NewModuleHandler(name string, expr string, desc string, exec func(args []string) error) ModuleHandler {
h := ModuleHandler{
Name: name,
Description: desc,
Parser: nil,
exec: exec,
}
if expr != "" {
h.Parser = regexp.MustCompile(expr)
}
return h
}
func (h *ModuleHandler) Complete(name string, cb func(prefix string) []string) {
h.Completer = readline.PcItem(name, readline.PcItemDynamic(func(prefix string) []string {
prefix = str.Trim(prefix[len(name):])
return cb(prefix)
}))
}
func (h *ModuleHandler) Help(padding int) string {
return fmt.Sprintf(" "+tui.Bold("%"+strconv.Itoa(padding)+"s")+" : %s\n", h.Name, h.Description)
}
func (h *ModuleHandler) Parse(line string) (bool, []string) {
if h.Parser == nil {
if line == h.Name {
return true, nil
}
return false, nil
}
result := h.Parser.FindStringSubmatch(line)
if len(result) == h.Parser.NumSubexp()+1 {
return true, result[1:]
}
return false, nil
}
func (h *ModuleHandler) Exec(args []string) error {
h.Lock()
defer h.Unlock()
return h.exec(args)
}
type JSONModuleHandler struct {
Name string `json:"name"`
Description string `json:"description"`
Parser string `json:"parser"`
}
func (h ModuleHandler) MarshalJSON() ([]byte, error) {
j := JSONModuleHandler{
Name: h.Name,
Description: h.Description,
}
if h.Parser != nil {
j.Parser = h.Parser.String()
}
return json.Marshal(j)
}