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