| 1 | package session |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "strings" |
| 6 | |
| 7 | "github.com/evilsocket/islazy/str" |
| 8 | ) |
| 9 | |
| 10 | func ParseCommands(line string) []string { |
| 11 | args := []string{} |
| 12 | buf := "" |
| 13 | |
| 14 | singleQuoted := false |
| 15 | doubleQuoted := false |
| 16 | finish := false |
| 17 | |
| 18 | line = strings.Replace(line, `""`, `"<empty>"`, -1) |
| 19 | line = strings.Replace(line, `''`, `"<empty>"`, -1) |
| 20 | for _, c := range line { |
| 21 | switch c { |
| 22 | case ';': |
| 23 | if !singleQuoted && !doubleQuoted { |
| 24 | finish = true |
| 25 | } else { |
| 26 | buf += string(c) |
| 27 | } |
| 28 | |
| 29 | case '"': |
| 30 | if doubleQuoted { |
| 31 | // finish of quote |
| 32 | doubleQuoted = false |
| 33 | } else if singleQuoted { |
| 34 | // quote initiated with ', so we ignore it |
| 35 | buf += string(c) |
| 36 | } else { |
| 37 | // quote init here |
| 38 | doubleQuoted = true |
| 39 | } |
| 40 | |
| 41 | case '\'': |
| 42 | if singleQuoted { |
| 43 | singleQuoted = false |
| 44 | } else if doubleQuoted { |
| 45 | buf += string(c) |
| 46 | } else { |
| 47 | singleQuoted = true |
| 48 | } |
| 49 | |
| 50 | default: |
| 51 | buf += string(c) |
| 52 | } |
| 53 | |
| 54 | if finish { |
| 55 | buf = strings.Replace(buf, `<empty>`, `""`, -1) |
| 56 | args = append(args, buf) |
| 57 | finish = false |
| 58 | buf = "" |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | if len(buf) > 0 { |
| 63 | buf = strings.Replace(buf, `<empty>`, `""`, -1) |
| 64 | args = append(args, buf) |
| 65 | } |
| 66 | |
| 67 | cmds := make([]string, 0) |
| 68 | for _, cmd := range args { |
| 69 | cmd = str.Trim(cmd) |
| 70 | if cmd != "" || (len(cmd) > 0 && cmd[0] != '#') { |
| 71 | cmds = append(cmds, cmd) |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | return cmds |
| 76 | } |
| 77 | |
| 78 | func (s *Session) parseEnvTokens(str string) (string, error) { |
| 79 | for _, m := range reEnvVarCapture.FindAllString(str, -1) { |
| 80 | varName := strings.Trim(strings.Replace(m, "env.", "", -1), "{}") |
| 81 | if found, value := s.Env.Get(varName); found { |
| 82 | str = strings.Replace(str, m, value, -1) |
| 83 | } else { |
| 84 | return "", fmt.Errorf("variable '%s' is not defined", varName) |
| 85 | } |
| 86 | } |
| 87 | return str, nil |
| 88 | } |