script.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package session
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "path/filepath"
  6. "regexp"
  7. "strings"
  8. "github.com/bettercap/bettercap/caplets"
  9. _ "github.com/bettercap/bettercap/js"
  10. "github.com/evilsocket/islazy/fs"
  11. "github.com/evilsocket/islazy/plugin"
  12. "github.com/evilsocket/islazy/str"
  13. )
  14. // require("telegram.js")
  15. var requireParser = regexp.MustCompile(`(?msi)^\s*require\s*\(\s*["']([^"']+)["']\s*\);?\s*$`)
  16. type Script struct {
  17. *plugin.Plugin
  18. }
  19. // yo! we're doing c-like preprocessing on a javascript file from go :D
  20. func preprocess(basePath string, code string, level int) (string, error) {
  21. if level >= 255 {
  22. return "", fmt.Errorf("too many nested includes")
  23. }
  24. matches := requireParser.FindAllStringSubmatch(code, -1)
  25. for _, match := range matches {
  26. expr := match[0]
  27. fileName := str.Trim(match[1])
  28. if fileName[0] != '/' {
  29. searchPaths := []string{
  30. filepath.Join(basePath, fileName),
  31. filepath.Join(caplets.InstallBase, fileName),
  32. }
  33. if !strings.Contains(fileName, ".js") {
  34. searchPaths = append(searchPaths, []string{
  35. filepath.Join(basePath, fileName) + ".js",
  36. filepath.Join(caplets.InstallBase, fileName) + ".js",
  37. }...)
  38. }
  39. found := false
  40. for _, fName := range searchPaths {
  41. if fs.Exists(fName) {
  42. fileName = fName
  43. found = true
  44. break
  45. }
  46. }
  47. if !found {
  48. return "", fmt.Errorf("file %s not found in any of %#v", fileName, searchPaths)
  49. }
  50. }
  51. raw, err := ioutil.ReadFile(fileName)
  52. if err != nil {
  53. return "", fmt.Errorf("%s: %v", fileName, err)
  54. }
  55. if includedBody, err := preprocess(filepath.Dir(fileName), string(raw), level+1); err != nil {
  56. return "", fmt.Errorf("%s: %v", fileName, err)
  57. } else {
  58. code = strings.ReplaceAll(code, expr, includedBody)
  59. }
  60. }
  61. return code, nil
  62. }
  63. func LoadScript(fileName string) (*Script, error) {
  64. raw, err := ioutil.ReadFile(fileName)
  65. if err != nil {
  66. return nil, err
  67. }
  68. basePath := filepath.Dir(fileName)
  69. if code, err := preprocess(basePath, string(raw), 0); err != nil {
  70. return nil, err
  71. } else if p, err := plugin.Parse(code); err != nil {
  72. return nil, err
  73. } else {
  74. p.Path = fileName
  75. p.Name = strings.Replace(basePath, ".js", "", -1)
  76. return &Script{
  77. Plugin: p,
  78. }, nil
  79. }
  80. }