capture/main.go

232 lines
6.5 KiB
Go
Raw Normal View History

2017-11-08 00:10:54 +01:00
package main
import (
"bytes"
"compress/gzip"
2018-07-21 19:50:53 +02:00
"encoding/json"
2017-11-18 13:23:36 +01:00
"fmt"
2018-11-25 18:10:10 +01:00
"html/template"
2017-11-08 00:10:54 +01:00
"io"
"io/ioutil"
"net/http"
2018-11-22 22:45:20 +01:00
"net/http/httptest"
2017-11-08 00:10:54 +01:00
"net/http/httputil"
2018-08-04 01:53:54 +02:00
"net/url"
2018-11-24 11:03:16 +01:00
"plugin"
2018-07-21 19:50:53 +02:00
"strings"
2017-11-08 00:10:54 +01:00
2018-11-24 18:51:33 +01:00
"github.com/ofabricio/curl"
2017-11-21 22:36:40 +01:00
)
2017-11-08 00:10:54 +01:00
func main() {
2018-09-16 16:21:36 +02:00
config := ReadConfig()
2018-11-11 17:54:35 +01:00
startCapture(config)
}
2017-11-08 00:10:54 +01:00
2018-11-11 17:54:35 +01:00
func startCapture(config Config) {
2018-11-22 22:45:20 +01:00
2018-11-25 18:10:10 +01:00
list := NewCaptureList(config.MaxCaptures)
2018-11-22 22:45:20 +01:00
2018-11-25 22:24:59 +01:00
handler := NewPlugin(NewRecorder(list, NewProxyHandler(config.TargetURL)))
http.Handle("/", handler)
2018-11-25 18:10:10 +01:00
http.Handle(config.DashboardPath, NewDashboardHtmlHandler(config))
http.Handle(config.DashboardConnPath, NewDashboardConnHandler(list))
http.Handle(config.DashboardClearPath, NewDashboardClearHandler(list))
2018-11-25 22:24:59 +01:00
http.Handle(config.DashboardRetryPath, NewDashboardRetryHandler(list, handler))
2018-11-25 18:10:10 +01:00
http.Handle(config.DashboardItemInfoPath, NewDashboardItemInfoHandler(list))
2018-09-16 16:18:39 +02:00
2018-11-16 22:39:53 +01:00
captureHost := fmt.Sprintf("http://localhost:%s", config.ProxyPort)
2017-11-18 13:23:36 +01:00
2018-11-16 22:39:53 +01:00
fmt.Printf("\nListening on %s", captureHost)
fmt.Printf("\n %s/%s\n\n", captureHost, config.Dashboard)
2017-11-18 13:23:36 +01:00
2018-09-16 16:21:36 +02:00
fmt.Println(http.ListenAndServe(":"+config.ProxyPort, nil))
2017-11-08 00:10:54 +01:00
}
2018-11-25 18:10:10 +01:00
func NewDashboardConnHandler(list *CaptureList) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
if _, ok := rw.(http.Flusher); !ok {
fmt.Printf("streaming not supported at %s\n", req.URL)
http.Error(rw, "streaming not supported", http.StatusInternalServerError)
return
}
rw.Header().Set("Content-Type", "text/event-stream")
rw.Header().Set("Cache-Control", "no-cache")
fmt.Fprintf(rw, "event: connected\ndata: %s\n\n", "clear")
rw.(http.Flusher).Flush()
for {
jsn, _ := json.Marshal(list.ItemsAsMetadata())
fmt.Fprintf(rw, "event: captures\ndata: %s\n\n", jsn)
rw.(http.Flusher).Flush()
select {
case <-list.Updated:
case <-req.Context().Done():
return
}
}
2017-11-21 22:36:40 +01:00
})
}
2018-11-25 18:10:10 +01:00
func NewDashboardClearHandler(list *CaptureList) http.Handler {
2018-11-16 22:39:53 +01:00
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
2018-11-25 18:10:10 +01:00
list.RemoveAll()
2018-11-16 22:39:53 +01:00
rw.WriteHeader(http.StatusOK)
2018-09-07 16:45:02 +02:00
})
}
2018-11-25 18:10:10 +01:00
func NewDashboardHtmlHandler(config Config) http.Handler {
2018-11-16 22:39:53 +01:00
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Add("Content-Type", "text/html")
2018-11-25 18:10:10 +01:00
t, err := template.New("dashboard template").Delims("<<", ">>").Parse(dashboardHTML)
if err != nil {
msg := fmt.Sprintf("could not parse dashboard html template: %v", err)
fmt.Println(msg)
http.Error(rw, msg, http.StatusInternalServerError)
return
}
t.Execute(rw, config)
2018-08-04 01:53:54 +02:00
})
}
2018-11-25 22:24:59 +01:00
func NewDashboardRetryHandler(list *CaptureList, next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
id := req.URL.Path[strings.LastIndex(req.URL.Path, "/")+1:]
capture := list.Find(id)
if capture == nil {
http.Error(rw, "Item Not Found", http.StatusNotFound)
return
}
var reqBody []byte
capture.Req.Body, reqBody = drain(capture.Req.Body)
r, _ := http.NewRequest(capture.Req.Method, capture.Req.URL.String(), capture.Req.Body)
r.Header = capture.Req.Header
next.ServeHTTP(rw, r)
capture.Req.Body = ioutil.NopCloser(bytes.NewReader(reqBody))
})
}
2018-11-25 18:10:10 +01:00
func NewDashboardItemInfoHandler(list *CaptureList) http.Handler {
2018-11-16 22:39:53 +01:00
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
2018-11-22 22:45:20 +01:00
id := req.URL.Path[strings.LastIndex(req.URL.Path, "/")+1:]
2018-11-25 18:10:10 +01:00
capture := list.Find(id)
2018-11-22 22:45:20 +01:00
if capture == nil {
http.Error(rw, "Item Not Found", http.StatusNotFound)
return
2018-09-16 16:18:39 +02:00
}
2018-11-22 22:45:20 +01:00
rw.Header().Add("Content-Type", "application/json")
2018-11-24 15:24:16 +01:00
json.NewEncoder(rw).Encode(dump(capture))
2018-08-02 00:36:23 +02:00
})
}
2018-11-24 11:03:16 +01:00
func NewPlugin(next http.Handler) http.Handler {
p, err := plugin.Open("plugin.so")
if err != nil {
if strings.HasPrefix(err.Error(), "plugin.Open") {
fmt.Printf("error: could not open plugin file 'plugin.so': %v\n", err)
}
return next
}
f, err := p.Lookup("Handler")
if err != nil {
fmt.Printf("error: could not find plugin Handler function %v\n", err)
return next
}
pluginFn, ok := f.(func(http.Handler) http.Handler)
if !ok {
fmt.Println("error: plugin Handler function should be 'func(http.Handler) http.Handler'")
return next
}
return pluginFn(next)
}
2018-11-25 18:10:10 +01:00
func NewRecorder(list *CaptureList, next http.Handler) http.Handler {
2018-11-11 17:54:35 +01:00
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
2018-11-24 15:24:16 +01:00
// save req body for later
var reqBody []byte
req.Body, reqBody = drain(req.Body)
2017-11-08 00:10:54 +01:00
2018-11-22 22:45:20 +01:00
rec := httptest.NewRecorder()
next.ServeHTTP(rec, req)
2018-11-24 15:24:16 +01:00
// respond
2018-11-22 22:45:20 +01:00
for k, v := range rec.HeaderMap {
rw.Header()[k] = v
}
rw.WriteHeader(rec.Code)
rw.Write(rec.Body.Bytes())
2018-11-24 15:24:16 +01:00
// record req and res
req.Body = ioutil.NopCloser(bytes.NewReader(reqBody))
2018-11-22 22:45:20 +01:00
res := rec.Result()
2018-11-25 18:10:10 +01:00
list.Insert(Capture{Req: req, Res: res})
2018-11-22 22:45:20 +01:00
})
}
2018-11-22 22:52:02 +01:00
func NewProxyHandler(URL string) http.Handler {
2018-11-22 22:45:20 +01:00
url, _ := url.Parse(URL)
proxy := httputil.NewSingleHostReverseProxy(url)
proxy.ErrorHandler = func(rw http.ResponseWriter, req *http.Request, err error) {
fmt.Printf("uh oh | %v | %s %s\n", err, req.Method, req.URL)
}
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
req.Host = url.Host
req.URL.Host = url.Host
req.URL.Scheme = url.Scheme
2018-11-11 17:54:35 +01:00
proxy.ServeHTTP(rw, req)
})
2018-08-04 01:53:54 +02:00
}
2018-11-24 15:24:16 +01:00
func dump(c *Capture) CaptureDump {
reqDump, err := dumpRequest(c.Req)
if err != nil {
fmt.Printf("could not dump request: %v\n", err)
}
resDump, err := dumpResponse(c.Res)
if err != nil {
fmt.Printf("could not dump response: %v\n", err)
}
2018-11-24 18:51:33 +01:00
strcurl, err := curl.New(c.Req)
if err != nil {
fmt.Printf("could not convert request to curl: %v\n", err)
}
return CaptureDump{Request: string(reqDump), Response: string(resDump), Curl: strcurl}
2018-11-24 15:24:16 +01:00
}
2018-08-04 01:53:54 +02:00
func dumpRequest(req *http.Request) ([]byte, error) {
2018-11-11 17:54:35 +01:00
if req.Header.Get("Content-Encoding") == "gzip" {
2018-11-22 22:45:20 +01:00
var reqBody []byte
req.Body, reqBody = drain(req.Body)
reader, _ := gzip.NewReader(bytes.NewReader(reqBody))
2018-11-11 17:54:35 +01:00
req.Body = ioutil.NopCloser(reader)
reqDump, err := httputil.DumpRequest(req, true)
2018-11-22 22:45:20 +01:00
req.Body = ioutil.NopCloser(bytes.NewReader(reqBody))
2018-11-11 17:54:35 +01:00
return reqDump, err
}
2018-07-21 19:50:53 +02:00
return httputil.DumpRequest(req, true)
}
2018-08-04 01:53:54 +02:00
func dumpResponse(res *http.Response) ([]byte, error) {
if res.Header.Get("Content-Encoding") == "gzip" {
2018-11-22 22:45:20 +01:00
var resBody []byte
res.Body, resBody = drain(res.Body)
reader, _ := gzip.NewReader(bytes.NewReader(resBody))
2018-11-11 17:54:35 +01:00
res.Body = ioutil.NopCloser(reader)
resDump, err := httputil.DumpResponse(res, true)
2018-11-22 22:45:20 +01:00
res.Body = ioutil.NopCloser(bytes.NewReader(resBody))
2018-11-11 17:54:35 +01:00
return resDump, err
}
2018-11-11 17:54:35 +01:00
return httputil.DumpResponse(res, true)
}
2018-09-07 16:45:02 +02:00
2018-11-22 22:45:20 +01:00
func drain(b io.ReadCloser) (io.ReadCloser, []byte) {
all, _ := ioutil.ReadAll(b)
b.Close()
return ioutil.NopCloser(bytes.NewReader(all)), all
}