| 1 | package goproxy |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "io" |
| 6 | "log" |
| 7 | "net" |
| 8 | "net/http" |
| 9 | "os" |
| 10 | "regexp" |
| 11 | "sync/atomic" |
| 12 | ) |
| 13 | |
| 14 | // The basic proxy type. Implements http.Handler. |
| 15 | type ProxyHttpServer struct { |
| 16 | // session variable must be aligned in i386 |
| 17 | // see http://golang.org/src/pkg/sync/atomic/doc.go#L41 |
| 18 | sess int64 |
| 19 | // KeepDestinationHeaders indicates the proxy should retain any headers present in the http.Response before proxying |
| 20 | KeepDestinationHeaders bool |
| 21 | // setting Verbose to true will log information on each request sent to the proxy |
| 22 | Verbose bool |
| 23 | Logger Logger |
| 24 | NonproxyHandler http.Handler |
| 25 | reqHandlers []ReqHandler |
| 26 | respHandlers []RespHandler |
| 27 | httpsHandlers []HttpsHandler |
| 28 | Tr *http.Transport |
| 29 | // ConnectDial will be used to create TCP connections for CONNECT requests |
| 30 | // if nil Tr.Dial will be used |
| 31 | ConnectDial func(network string, addr string) (net.Conn, error) |
| 32 | ConnectDialWithReq func(req *http.Request, network string, addr string) (net.Conn, error) |
| 33 | CertStore CertStorage |
| 34 | KeepHeader bool |
| 35 | AllowHTTP2 bool |
| 36 | } |
| 37 | |
| 38 | var hasPort = regexp.MustCompile(`:\d+$`) |
| 39 | |
| 40 | func copyHeaders(dst, src http.Header, keepDestHeaders bool) { |
| 41 | if !keepDestHeaders { |
| 42 | for k := range dst { |
| 43 | dst.Del(k) |
| 44 | } |
| 45 | } |
| 46 | for k, vs := range src { |
| 47 | for _, v := range vs { |
| 48 | dst.Add(k, v) |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | func isEof(r *bufio.Reader) bool { |
| 54 | _, err := r.Peek(1) |
| 55 | if err == io.EOF { |
| 56 | return true |
| 57 | } |
| 58 | return false |
| 59 | } |
| 60 | |
| 61 | func (proxy *ProxyHttpServer) filterRequest(r *http.Request, ctx *ProxyCtx) (req *http.Request, resp *http.Response) { |
| 62 | req = r |
| 63 | for _, h := range proxy.reqHandlers { |
| 64 | req, resp = h.Handle(r, ctx) |
| 65 | // non-nil resp means the handler decided to skip sending the request |
| 66 | // and return canned response instead. |
| 67 | if resp != nil { |
| 68 | break |
| 69 | } |
| 70 | } |
| 71 | return |
| 72 | } |
| 73 | func (proxy *ProxyHttpServer) filterResponse(respOrig *http.Response, ctx *ProxyCtx) (resp *http.Response) { |
| 74 | resp = respOrig |
| 75 | for _, h := range proxy.respHandlers { |
| 76 | ctx.Resp = resp |
| 77 | resp = h.Handle(resp, ctx) |
| 78 | } |
| 79 | return |
| 80 | } |
| 81 | |
| 82 | func removeProxyHeaders(ctx *ProxyCtx, r *http.Request) { |
| 83 | r.RequestURI = "" // this must be reset when serving a request with the client |
| 84 | ctx.Logf("Sending request %v %v", r.Method, r.URL.String()) |
| 85 | // If no Accept-Encoding header exists, Transport will add the headers it can accept |
| 86 | // and would wrap the response body with the relevant reader. |
| 87 | r.Header.Del("Accept-Encoding") |
| 88 | // curl can add that, see |
| 89 | // https://jdebp.eu./FGA/web-proxy-connection-header.html |
| 90 | r.Header.Del("Proxy-Connection") |
| 91 | r.Header.Del("Proxy-Authenticate") |
| 92 | r.Header.Del("Proxy-Authorization") |
| 93 | // Connection, Authenticate and Authorization are single hop Header: |
| 94 | // http://www.w3.org/Protocols/rfc2616/rfc2616.txt |
| 95 | // 14.10 Connection |
| 96 | // The Connection general-header field allows the sender to specify |
| 97 | // options that are desired for that particular connection and MUST NOT |
| 98 | // be communicated by proxies over further connections. |
| 99 | |
| 100 | // When server reads http request it sets req.Close to true if |
| 101 | // "Connection" header contains "close". |
| 102 | // https://github.com/golang/go/blob/master/src/net/http/request.go#L1080 |
| 103 | // Later, transfer.go adds "Connection: close" back when req.Close is true |
| 104 | // https://github.com/golang/go/blob/master/src/net/http/transfer.go#L275 |
| 105 | // That's why tests that checks "Connection: close" removal fail |
| 106 | if r.Header.Get("Connection") == "close" { |
| 107 | r.Close = false |
| 108 | } |
| 109 | r.Header.Del("Connection") |
| 110 | } |
| 111 | |
| 112 | type flushWriter struct { |
| 113 | w io.Writer |
| 114 | } |
| 115 | |
| 116 | func (fw flushWriter) Write(p []byte) (int, error) { |
| 117 | n, err := fw.w.Write(p) |
| 118 | if f, ok := fw.w.(http.Flusher); ok { |
| 119 | // only flush if the Writer implements the Flusher interface. |
| 120 | f.Flush() |
| 121 | } |
| 122 | |
| 123 | return n, err |
| 124 | } |
| 125 | |
| 126 | // Standard net/http function. Shouldn't be used directly, http.Serve will use it. |
| 127 | func (proxy *ProxyHttpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 128 | //r.Header["X-Forwarded-For"] = w.RemoteAddr() |
| 129 | if r.Method == "CONNECT" { |
| 130 | proxy.handleHttps(w, r) |
| 131 | } else { |
| 132 | ctx := &ProxyCtx{Req: r, Session: atomic.AddInt64(&proxy.sess, 1), Proxy: proxy} |
| 133 | |
| 134 | var err error |
| 135 | ctx.Logf("Got request %v %v %v %v", r.URL.Path, r.Host, r.Method, r.URL.String()) |
| 136 | if !r.URL.IsAbs() { |
| 137 | proxy.NonproxyHandler.ServeHTTP(w, r) |
| 138 | return |
| 139 | } |
| 140 | r, resp := proxy.filterRequest(r, ctx) |
| 141 | |
| 142 | if resp == nil { |
| 143 | if isWebSocketRequest(r) { |
| 144 | ctx.Logf("Request looks like websocket upgrade.") |
| 145 | proxy.serveWebsocket(ctx, w, r) |
| 146 | } |
| 147 | |
| 148 | if !proxy.KeepHeader { |
| 149 | removeProxyHeaders(ctx, r) |
| 150 | } |
| 151 | resp, err = ctx.RoundTrip(r) |
| 152 | if err != nil { |
| 153 | ctx.Error = err |
| 154 | resp = proxy.filterResponse(nil, ctx) |
| 155 | |
| 156 | } |
| 157 | if resp != nil { |
| 158 | ctx.Logf("Received response %v", resp.Status) |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | var origBody io.ReadCloser |
| 163 | |
| 164 | if resp != nil { |
| 165 | origBody = resp.Body |
| 166 | defer origBody.Close() |
| 167 | } |
| 168 | |
| 169 | resp = proxy.filterResponse(resp, ctx) |
| 170 | |
| 171 | if resp == nil { |
| 172 | var errorString string |
| 173 | if ctx.Error != nil { |
| 174 | errorString = "error read response " + r.URL.Host + " : " + ctx.Error.Error() |
| 175 | ctx.Logf(errorString) |
| 176 | http.Error(w, ctx.Error.Error(), 500) |
| 177 | } else { |
| 178 | errorString = "error read response " + r.URL.Host |
| 179 | ctx.Logf(errorString) |
| 180 | http.Error(w, errorString, 500) |
| 181 | } |
| 182 | return |
| 183 | } |
| 184 | ctx.Logf("Copying response to client %v [%d]", resp.Status, resp.StatusCode) |
| 185 | // http.ResponseWriter will take care of filling the correct response length |
| 186 | // Setting it now, might impose wrong value, contradicting the actual new |
| 187 | // body the user returned. |
| 188 | // We keep the original body to remove the header only if things changed. |
| 189 | // This will prevent problems with HEAD requests where there's no body, yet, |
| 190 | // the Content-Length header should be set. |
| 191 | if origBody != resp.Body { |
| 192 | resp.Header.Del("Content-Length") |
| 193 | } |
| 194 | copyHeaders(w.Header(), resp.Header, proxy.KeepDestinationHeaders) |
| 195 | w.WriteHeader(resp.StatusCode) |
| 196 | var copyWriter io.Writer = w |
| 197 | if w.Header().Get("content-type") == "text/event-stream" { |
| 198 | // server-side events, flush the buffered data to the client. |
| 199 | copyWriter = &flushWriter{w: w} |
| 200 | } |
| 201 | |
| 202 | nr, err := io.Copy(copyWriter, resp.Body) |
| 203 | if err := resp.Body.Close(); err != nil { |
| 204 | ctx.Warnf("Can't close response body %v", err) |
| 205 | } |
| 206 | ctx.Logf("Copied %v bytes to client error=%v", nr, err) |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | // NewProxyHttpServer creates and returns a proxy server, logging to stderr by default |
| 211 | func NewProxyHttpServer() *ProxyHttpServer { |
| 212 | proxy := ProxyHttpServer{ |
| 213 | Logger: log.New(os.Stderr, "", log.LstdFlags), |
| 214 | reqHandlers: []ReqHandler{}, |
| 215 | respHandlers: []RespHandler{}, |
| 216 | httpsHandlers: []HttpsHandler{}, |
| 217 | NonproxyHandler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 218 | http.Error(w, "This is a proxy server. Does not respond to non-proxy requests.", 500) |
| 219 | }), |
| 220 | Tr: &http.Transport{TLSClientConfig: tlsClientSkipVerify, Proxy: http.ProxyFromEnvironment}, |
| 221 | } |
| 222 | |
| 223 | proxy.ConnectDial = dialerFromEnv(&proxy) |
| 224 | |
| 225 | return &proxy |
| 226 | } |