module_handler.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package session
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "regexp"
  6. "strconv"
  7. "sync"
  8. "github.com/evilsocket/islazy/str"
  9. "github.com/evilsocket/islazy/tui"
  10. "github.com/bettercap/readline"
  11. )
  12. const (
  13. IPv4Validator = `^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$`
  14. IPv6Validator = `^[:a-fA-F0-9]{6,}$`
  15. IPValidator = `^[\.:a-fA-F0-9]{6,}$`
  16. )
  17. type ModuleHandler struct {
  18. *sync.Mutex
  19. Name string
  20. Description string
  21. Parser *regexp.Regexp
  22. Completer *readline.PrefixCompleter
  23. exec func(args []string) error
  24. }
  25. func NewModuleHandler(name string, expr string, desc string, exec func(args []string) error) ModuleHandler {
  26. h := ModuleHandler{
  27. Mutex: &sync.Mutex{},
  28. Name: name,
  29. Description: desc,
  30. Parser: nil,
  31. exec: exec,
  32. }
  33. if expr != "" {
  34. h.Parser = regexp.MustCompile(expr)
  35. }
  36. return h
  37. }
  38. func (h *ModuleHandler) Complete(name string, cb func(prefix string) []string) {
  39. h.Completer = readline.PcItem(name, readline.PcItemDynamic(func(prefix string) []string {
  40. prefix = str.Trim(prefix[len(name):])
  41. return cb(prefix)
  42. }))
  43. }
  44. func (h *ModuleHandler) Help(padding int) string {
  45. return fmt.Sprintf(" "+tui.Bold("%"+strconv.Itoa(padding)+"s")+" : %s\n", h.Name, h.Description)
  46. }
  47. func (h *ModuleHandler) Parse(line string) (bool, []string) {
  48. if h.Parser == nil {
  49. if line == h.Name {
  50. return true, nil
  51. }
  52. return false, nil
  53. }
  54. result := h.Parser.FindStringSubmatch(line)
  55. if len(result) == h.Parser.NumSubexp()+1 {
  56. return true, result[1:]
  57. }
  58. return false, nil
  59. }
  60. func (h *ModuleHandler) Exec(args []string) error {
  61. h.Lock()
  62. defer h.Unlock()
  63. return h.exec(args)
  64. }
  65. type JSONModuleHandler struct {
  66. Name string `json:"name"`
  67. Description string `json:"description"`
  68. Parser string `json:"parser"`
  69. }
  70. func (h ModuleHandler) MarshalJSON() ([]byte, error) {
  71. j := JSONModuleHandler{
  72. Name: h.Name,
  73. Description: h.Description,
  74. }
  75. if h.Parser != nil {
  76. j.Parser = h.Parser.String()
  77. }
  78. return json.Marshal(j)
  79. }