| 21 | } |
| 22 | |
| 23 | func LoadHttpProxyScript(path string, sess *session.Session) (err error, s *HttpProxyScript) { |
| 24 | log.Debug("loading proxy script %s ...", path) |
| 25 | |
| 26 | plug, err := plugin.Load(path) |
| 27 | if err != nil { |
| 28 | return |
| 29 | } |
| 30 | |
| 31 | // define session pointer |
| 32 | if err = plug.Set("env", sess.Env.Data); err != nil { |
| 33 | log.Error("Error while defining environment: %+v", err) |
| 34 | return |
| 35 | } |
| 36 | |
| 37 | // define addSessionEvent function |
| 38 | err = plug.Set("addSessionEvent", func(call otto.FunctionCall) otto.Value { |
| 39 | if len(call.ArgumentList) < 2 { |
| 40 | log.Error("Failed to execute 'addSessionEvent' in HTTP proxy: 2 arguments required, but only %d given.", len(call.ArgumentList)) |
| 41 | return otto.FalseValue() |
| 42 | } |
| 43 | ottoTag := call.Argument(0) |
| 44 | if !ottoTag.IsString() { |
| 45 | log.Error("Failed to execute 'addSessionEvent' in HTTP proxy: first argument must be a string.") |
| 46 | return otto.FalseValue() |
| 47 | } |
| 48 | tag := strings.TrimSpace(ottoTag.String()) |
| 49 | if tag == "" { |
| 50 | log.Error("Failed to execute 'addSessionEvent' in HTTP proxy: tag cannot be empty.") |
| 51 | return otto.FalseValue() |
| 52 | } |
| 53 | data := call.Argument(1) |
| 54 | sess.Events.Add(tag, data) |
| 55 | return otto.TrueValue() |
| 56 | }) |
| 57 | if err != nil { |
| 58 | log.Error("Error while defining addSessionEvent function: %+v", err) |
| 59 | return |
| 60 | } |
| 61 | |
| 62 | // run onLoad if defined |
| 63 | if plug.HasFunc("onLoad") { |
| 64 | if _, err = plug.Call("onLoad"); err != nil { |
| 65 | log.Error("Error while executing onLoad callback: %s", "\nTraceback:\n "+err.(*otto.Error).String()) |
| 66 | return |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | s = &HttpProxyScript{ |
| 71 | Plugin: plug, |
| 72 | doOnRequest: plug.HasFunc("onRequest"), |
| 73 | doOnResponse: plug.HasFunc("onResponse"), |
| 74 | doOnCommand: plug.HasFunc("onCommand"), |
| 75 | } |
| 76 | return |
| 77 | } |
| 78 | |
| 79 | func (s *HttpProxyScript) OnRequest(original *http.Request) (jsreq *JSRequest, jsres *JSResponse) { |
| 80 | if s.doOnRequest { |