caplet.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package caplets
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. "strings"
  6. "github.com/evilsocket/islazy/fs"
  7. )
  8. type Script struct {
  9. Path string `json:"path"`
  10. Size int64 `json:"size"`
  11. Code []string `json:"code"`
  12. }
  13. func newScript(path string, size int64) Script {
  14. return Script{
  15. Path: path,
  16. Size: size,
  17. Code: make([]string, 0),
  18. }
  19. }
  20. type Caplet struct {
  21. Script
  22. Name string `json:"name"`
  23. Scripts []Script `json:"scripts"`
  24. }
  25. func NewCaplet(name string, path string, size int64) Caplet {
  26. return Caplet{
  27. Script: newScript(path, size),
  28. Name: name,
  29. Scripts: make([]Script, 0),
  30. }
  31. }
  32. func (cap *Caplet) Eval(argv []string, lineCb func(line string) error) error {
  33. if argv == nil {
  34. argv = []string{}
  35. }
  36. // the caplet might include other files (include directive, proxy modules, etc),
  37. // temporarily change the working directory
  38. return fs.Chdir(filepath.Dir(cap.Path), func() error {
  39. for _, line := range cap.Code {
  40. // skip empty lines and comments
  41. if line == "" || line[0] == '#' {
  42. continue
  43. }
  44. // replace $0 with argv[0], $1 with argv[1] and so on
  45. for i, arg := range argv {
  46. what := fmt.Sprintf("$%d", i)
  47. line = strings.Replace(line, what, arg, -1)
  48. }
  49. if err := lineCb(line); err != nil {
  50. return err
  51. }
  52. }
  53. return nil
  54. })
  55. }