reverse.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. package reverseproxy
  2. import (
  3. "errors"
  4. "io"
  5. "log"
  6. "net"
  7. "net/http"
  8. "net/url"
  9. "strings"
  10. "sync"
  11. "time"
  12. )
  13. var onExitFlushLoop func()
  14. const (
  15. defaultTimeout = time.Minute * 5
  16. )
  17. // ReverseProxy is an HTTP Handler that takes an incoming request and
  18. // sends it to another server, proxying the response back to the
  19. // client, support http, also support https tunnel using http.hijacker
  20. type ReverseProxy struct {
  21. // Set the timeout of the proxy server, default is 5 minutes
  22. Timeout time.Duration
  23. // Director must be a function which modifies
  24. // the request into a new request to be sent
  25. // using Transport. Its response is then copied
  26. // back to the original client unmodified.
  27. // Director must not access the provided Request
  28. // after returning.
  29. Director func(*http.Request)
  30. // The transport used to perform proxy requests.
  31. // default is http.DefaultTransport.
  32. Transport http.RoundTripper
  33. // FlushInterval specifies the flush interval
  34. // to flush to the client while copying the
  35. // response body. If zero, no periodic flushing is done.
  36. FlushInterval time.Duration
  37. // ErrorLog specifies an optional logger for errors
  38. // that occur when attempting to proxy the request.
  39. // If nil, logging goes to os.Stderr via the log package's
  40. // standard logger.
  41. ErrorLog *log.Logger
  42. // ModifyResponse is an optional function that
  43. // modifies the Response from the backend.
  44. // If it returns an error, the proxy returns a StatusBadGateway error.
  45. ModifyResponse func(*http.Response) error
  46. }
  47. type requestCanceler interface {
  48. CancelRequest(req *http.Request)
  49. }
  50. // NewReverseProxy returns a new ReverseProxy that routes
  51. // URLs to the scheme, host, and base path provided in target. If the
  52. // target's path is "/base" and the incoming request was for "/dir",
  53. // the target request will be for /base/dir. if the target's query is a=10
  54. // and the incoming request's query is b=100, the target's request's query
  55. // will be a=10&b=100.
  56. // NewReverseProxy does not rewrite the Host header.
  57. // To rewrite Host headers, use ReverseProxy directly with a custom
  58. // Director policy.
  59. func NewReverseProxy(target *url.URL) *ReverseProxy {
  60. targetQuery := target.RawQuery
  61. director := func(req *http.Request) {
  62. req.URL.Scheme = target.Scheme
  63. req.URL.Host = target.Host
  64. req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
  65. // If Host is empty, the Request.Write method uses
  66. // the value of URL.Host.
  67. // force use URL.Host
  68. req.Host = req.URL.Host
  69. if targetQuery == "" || req.URL.RawQuery == "" {
  70. req.URL.RawQuery = targetQuery + req.URL.RawQuery
  71. } else {
  72. req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
  73. }
  74. if _, ok := req.Header["User-Agent"]; !ok {
  75. req.Header.Set("User-Agent", "")
  76. }
  77. }
  78. return &ReverseProxy{Director: director}
  79. }
  80. func singleJoiningSlash(a, b string) string {
  81. aslash := strings.HasSuffix(a, "/")
  82. bslash := strings.HasPrefix(b, "/")
  83. switch {
  84. case aslash && bslash:
  85. return a + b[1:]
  86. case !aslash && !bslash:
  87. return a + "/" + b
  88. }
  89. return a + b
  90. }
  91. func copyHeader(dst, src http.Header) {
  92. for k, vv := range src {
  93. for _, v := range vv {
  94. dst.Add(k, v)
  95. }
  96. }
  97. }
  98. // Hop-by-hop headers. These are removed when sent to the backend.
  99. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
  100. var hopHeaders = []string{
  101. //"Connection",
  102. "Proxy-Connection", // non-standard but still sent by libcurl and rejected by e.g. google
  103. "Keep-Alive",
  104. "Proxy-Authenticate",
  105. "Proxy-Authorization",
  106. "Te", // canonicalized version of "TE"
  107. "Trailer", // not Trailers per URL above; http://www.rfc-editor.org/errata_search.php?eid=4522
  108. "Transfer-Encoding",
  109. //"Upgrade",
  110. }
  111. func (p *ReverseProxy) copyResponse(dst io.Writer, src io.Reader) {
  112. if p.FlushInterval != 0 {
  113. if wf, ok := dst.(writeFlusher); ok {
  114. mlw := &maxLatencyWriter{
  115. dst: wf,
  116. latency: p.FlushInterval,
  117. done: make(chan bool),
  118. }
  119. go mlw.flushLoop()
  120. defer mlw.stop()
  121. dst = mlw
  122. }
  123. }
  124. io.Copy(dst, src)
  125. }
  126. type writeFlusher interface {
  127. io.Writer
  128. http.Flusher
  129. }
  130. type maxLatencyWriter struct {
  131. dst writeFlusher
  132. latency time.Duration
  133. mu sync.Mutex
  134. done chan bool
  135. }
  136. func (m *maxLatencyWriter) Write(b []byte) (int, error) {
  137. m.mu.Lock()
  138. defer m.mu.Unlock()
  139. return m.dst.Write(b)
  140. }
  141. func (m *maxLatencyWriter) flushLoop() {
  142. t := time.NewTicker(m.latency)
  143. defer t.Stop()
  144. for {
  145. select {
  146. case <-m.done:
  147. if onExitFlushLoop != nil {
  148. onExitFlushLoop()
  149. }
  150. return
  151. case <-t.C:
  152. m.mu.Lock()
  153. m.dst.Flush()
  154. m.mu.Unlock()
  155. }
  156. }
  157. }
  158. func (m *maxLatencyWriter) stop() {
  159. m.done <- true
  160. }
  161. func (p *ReverseProxy) logf(format string, args ...interface{}) {
  162. if p.ErrorLog != nil {
  163. p.ErrorLog.Printf(format, args...)
  164. } else {
  165. log.Printf(format, args...)
  166. }
  167. }
  168. func removeHeaders(header http.Header) {
  169. // Remove hop-by-hop headers listed in the "Connection" header.
  170. if c := header.Get("Connection"); c != "" {
  171. for _, f := range strings.Split(c, ",") {
  172. if f = strings.TrimSpace(f); f != "" {
  173. header.Del(f)
  174. }
  175. }
  176. }
  177. // Remove hop-by-hop headers
  178. for _, h := range hopHeaders {
  179. if header.Get(h) != "" {
  180. header.Del(h)
  181. }
  182. }
  183. if header.Get("A-Upgrade") != "" {
  184. header.Set("Upgrade", header.Get("A-Upgrade"))
  185. header.Del("A-Upgrade")
  186. }
  187. }
  188. func addXForwardedForHeader(req *http.Request) {
  189. if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
  190. // If we aren't the first proxy retain prior
  191. // X-Forwarded-For information as a comma+space
  192. // separated list and fold multiple headers into one.
  193. if prior, ok := req.Header["X-Forwarded-For"]; ok {
  194. clientIP = strings.Join(prior, ", ") + ", " + clientIP
  195. }
  196. req.Header.Set("X-Forwarded-For", clientIP)
  197. }
  198. }
  199. func (p *ReverseProxy) ProxyHTTP(rw http.ResponseWriter, req *http.Request) error {
  200. transport := p.Transport
  201. if transport == nil {
  202. transport = http.DefaultTransport
  203. }
  204. outreq := new(http.Request)
  205. // Shallow copies of maps, like header
  206. *outreq = *req
  207. if cn, ok := rw.(http.CloseNotifier); ok {
  208. if requestCanceler, ok := transport.(requestCanceler); ok {
  209. // After the Handler has returned, there is no guarantee
  210. // that the channel receives a value, so to make sure
  211. reqDone := make(chan struct{})
  212. defer close(reqDone)
  213. clientGone := cn.CloseNotify()
  214. go func() {
  215. select {
  216. case <-clientGone:
  217. requestCanceler.CancelRequest(outreq)
  218. case <-reqDone:
  219. }
  220. }()
  221. }
  222. }
  223. p.Director(outreq)
  224. outreq.Close = false
  225. // We may modify the header (shallow copied above), so we only copy it.
  226. outreq.Header = make(http.Header)
  227. copyHeader(outreq.Header, req.Header)
  228. // Remove hop-by-hop headers listed in the "Connection" header, Remove hop-by-hop headers.
  229. removeHeaders(outreq.Header)
  230. // Add X-Forwarded-For Header.
  231. addXForwardedForHeader(outreq)
  232. res, err := transport.RoundTrip(outreq)
  233. if err != nil {
  234. p.logf("http: proxy error: %v", err)
  235. rw.WriteHeader(http.StatusBadGateway)
  236. return err
  237. }
  238. // Remove hop-by-hop headers listed in the "Connection" header of the response, Remove hop-by-hop headers.
  239. removeHeaders(res.Header)
  240. if p.ModifyResponse != nil {
  241. if err := p.ModifyResponse(res); err != nil {
  242. p.logf("http: proxy error: %v", err)
  243. rw.WriteHeader(http.StatusBadGateway)
  244. return err
  245. }
  246. }
  247. // Copy header from response to client.
  248. copyHeader(rw.Header(), res.Header)
  249. // The "Trailer" header isn't included in the Transport's response, Build it up from Trailer.
  250. if len(res.Trailer) > 0 {
  251. trailerKeys := make([]string, 0, len(res.Trailer))
  252. for k := range res.Trailer {
  253. trailerKeys = append(trailerKeys, k)
  254. }
  255. rw.Header().Add("Trailer", strings.Join(trailerKeys, ", "))
  256. }
  257. rw.WriteHeader(res.StatusCode)
  258. if len(res.Trailer) > 0 {
  259. // Force chunking if we saw a response trailer.
  260. // This prevents net/http from calculating the length for short
  261. // bodies and adding a Content-Length.
  262. if fl, ok := rw.(http.Flusher); ok {
  263. fl.Flush()
  264. }
  265. }
  266. p.copyResponse(rw, res.Body)
  267. // close now, instead of defer, to populate res.Trailer
  268. res.Body.Close()
  269. copyHeader(rw.Header(), res.Trailer)
  270. return nil
  271. }
  272. func (p *ReverseProxy) ProxyHTTPS(rw http.ResponseWriter, req *http.Request) error {
  273. hij, ok := rw.(http.Hijacker)
  274. if !ok {
  275. p.logf("http server does not support hijacker")
  276. return errors.New("http server does not support hijacker")
  277. }
  278. clientConn, _, err := hij.Hijack()
  279. if err != nil {
  280. p.logf("http: proxy error: %v", err)
  281. return err
  282. }
  283. proxyConn, err := net.Dial("tcp", req.URL.Host)
  284. if err != nil {
  285. p.logf("http: proxy error: %v", err)
  286. return err
  287. }
  288. // The returned net.Conn may have read or write deadlines
  289. // already set, depending on the configuration of the
  290. // Server, to set or clear those deadlines as needed
  291. // we set timeout to 5 minutes
  292. deadline := time.Now()
  293. if p.Timeout == 0 {
  294. deadline = deadline.Add(time.Minute * 5)
  295. } else {
  296. deadline = deadline.Add(p.Timeout)
  297. }
  298. err = clientConn.SetDeadline(deadline)
  299. if err != nil {
  300. p.logf("http: proxy error: %v", err)
  301. return err
  302. }
  303. err = proxyConn.SetDeadline(deadline)
  304. if err != nil {
  305. p.logf("http: proxy error: %v", err)
  306. return err
  307. }
  308. _, err = clientConn.Write([]byte("HTTP/1.0 200 OK\r\n\r\n"))
  309. if err != nil {
  310. p.logf("http: proxy error: %v", err)
  311. return err
  312. }
  313. go func() {
  314. io.Copy(clientConn, proxyConn)
  315. clientConn.Close()
  316. proxyConn.Close()
  317. }()
  318. io.Copy(proxyConn, clientConn)
  319. proxyConn.Close()
  320. clientConn.Close()
  321. return nil
  322. }
  323. func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) error {
  324. if req.Method == "CONNECT" {
  325. err := p.ProxyHTTPS(rw, req)
  326. return err
  327. } else {
  328. err := p.ProxyHTTP(rw, req)
  329. return err
  330. }
  331. }