reverse.go 9.6 KB

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