reverseproxy.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. // Copyright 2011 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // HTTP reverse proxy handler
  5. package vhost
  6. import (
  7. "context"
  8. "io"
  9. "log"
  10. "net"
  11. "net/http"
  12. "net/url"
  13. "strings"
  14. "sync"
  15. "time"
  16. )
  17. // onExitFlushLoop is a callback set by tests to detect the state of the
  18. // flushLoop() goroutine.
  19. var onExitFlushLoop func()
  20. // ReverseProxy is an HTTP Handler that takes an incoming request and
  21. // sends it to another server, proxying the response back to the
  22. // client.
  23. type ReverseProxy struct {
  24. // Director must be a function which modifies
  25. // the request into a new request to be sent
  26. // using Transport. Its response is then copied
  27. // back to the original client unmodified.
  28. // Director must not access the provided Request
  29. // after returning.
  30. Director func(*http.Request)
  31. // The transport used to perform proxy requests.
  32. // If nil, http.DefaultTransport is used.
  33. Transport http.RoundTripper
  34. // FlushInterval specifies the flush interval
  35. // to flush to the client while copying the
  36. // response body.
  37. // If zero, no periodic flushing is done.
  38. FlushInterval time.Duration
  39. // ErrorLog specifies an optional logger for errors
  40. // that occur when attempting to proxy the request.
  41. // If nil, logging goes to os.Stderr via the log package's
  42. // standard logger.
  43. ErrorLog *log.Logger
  44. // BufferPool optionally specifies a buffer pool to
  45. // get byte slices for use by io.CopyBuffer when
  46. // copying HTTP response bodies.
  47. BufferPool BufferPool
  48. // ModifyResponse is an optional function that
  49. // modifies the Response from the backend.
  50. // If it returns an error, the proxy returns a StatusBadGateway error.
  51. ModifyResponse func(*http.Response) error
  52. }
  53. // A BufferPool is an interface for getting and returning temporary
  54. // byte slices for use by io.CopyBuffer.
  55. type BufferPool interface {
  56. Get() []byte
  57. Put([]byte)
  58. }
  59. func singleJoiningSlash(a, b string) string {
  60. aslash := strings.HasSuffix(a, "/")
  61. bslash := strings.HasPrefix(b, "/")
  62. switch {
  63. case aslash && bslash:
  64. return a + b[1:]
  65. case !aslash && !bslash:
  66. return a + "/" + b
  67. }
  68. return a + b
  69. }
  70. // NewSingleHostReverseProxy returns a new ReverseProxy that routes
  71. // URLs to the scheme, host, and base path provided in target. If the
  72. // target's path is "/base" and the incoming request was for "/dir",
  73. // the target request will be for /base/dir.
  74. // NewSingleHostReverseProxy does not rewrite the Host header.
  75. // To rewrite Host headers, use ReverseProxy directly with a custom
  76. // Director policy.
  77. func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy {
  78. targetQuery := target.RawQuery
  79. director := func(req *http.Request) {
  80. req.URL.Scheme = target.Scheme
  81. req.URL.Host = target.Host
  82. req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
  83. if targetQuery == "" || req.URL.RawQuery == "" {
  84. req.URL.RawQuery = targetQuery + req.URL.RawQuery
  85. } else {
  86. req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
  87. }
  88. if _, ok := req.Header["User-Agent"]; !ok {
  89. // explicitly disable User-Agent so it's not set to default value
  90. req.Header.Set("User-Agent", "")
  91. }
  92. }
  93. return &ReverseProxy{Director: director}
  94. }
  95. func copyHeader(dst, src http.Header) {
  96. for k, vv := range src {
  97. for _, v := range vv {
  98. dst.Add(k, v)
  99. }
  100. }
  101. }
  102. func cloneHeader(h http.Header) http.Header {
  103. h2 := make(http.Header, len(h))
  104. for k, vv := range h {
  105. vv2 := make([]string, len(vv))
  106. copy(vv2, vv)
  107. h2[k] = vv2
  108. }
  109. return h2
  110. }
  111. // Hop-by-hop headers. These are removed when sent to the backend.
  112. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
  113. var hopHeaders = []string{
  114. "Connection",
  115. "Proxy-Connection", // non-standard but still sent by libcurl and rejected by e.g. google
  116. "Keep-Alive",
  117. "Proxy-Authenticate",
  118. "Proxy-Authorization",
  119. "Te", // canonicalized version of "TE"
  120. "Trailer", // not Trailers per URL above; http://www.rfc-editor.org/errata_search.php?eid=4522
  121. "Transfer-Encoding",
  122. "Upgrade",
  123. }
  124. func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
  125. transport := p.Transport
  126. if transport == nil {
  127. transport = http.DefaultTransport
  128. }
  129. ctx := req.Context()
  130. if cn, ok := rw.(http.CloseNotifier); ok {
  131. var cancel context.CancelFunc
  132. ctx, cancel = context.WithCancel(ctx)
  133. defer cancel()
  134. notifyChan := cn.CloseNotify()
  135. go func() {
  136. select {
  137. case <-notifyChan:
  138. cancel()
  139. case <-ctx.Done():
  140. }
  141. }()
  142. }
  143. outreq := req.WithContext(ctx) // includes shallow copies of maps, but okay
  144. if req.ContentLength == 0 {
  145. outreq.Body = nil // Issue 16036: nil Body for http.Transport retries
  146. }
  147. outreq.Header = cloneHeader(req.Header)
  148. // Modify for frp
  149. outreq = outreq.WithContext(context.WithValue(outreq.Context(), "url", req.URL.Path))
  150. outreq = outreq.WithContext(context.WithValue(outreq.Context(), "host", req.Host))
  151. p.Director(outreq)
  152. outreq.Close = false
  153. // Remove hop-by-hop headers listed in the "Connection" header.
  154. // See RFC 2616, section 14.10.
  155. if c := outreq.Header.Get("Connection"); c != "" {
  156. for _, f := range strings.Split(c, ",") {
  157. if f = strings.TrimSpace(f); f != "" {
  158. outreq.Header.Del(f)
  159. }
  160. }
  161. }
  162. // Remove hop-by-hop headers to the backend. Especially
  163. // important is "Connection" because we want a persistent
  164. // connection, regardless of what the client sent to us.
  165. for _, h := range hopHeaders {
  166. if outreq.Header.Get(h) != "" {
  167. outreq.Header.Del(h)
  168. }
  169. }
  170. if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
  171. // If we aren't the first proxy retain prior
  172. // X-Forwarded-For information as a comma+space
  173. // separated list and fold multiple headers into one.
  174. if prior, ok := outreq.Header["X-Forwarded-For"]; ok {
  175. clientIP = strings.Join(prior, ", ") + ", " + clientIP
  176. }
  177. outreq.Header.Set("X-Forwarded-For", clientIP)
  178. }
  179. res, err := transport.RoundTrip(outreq)
  180. if err != nil {
  181. p.logf("http: proxy error: %v", err)
  182. rw.WriteHeader(http.StatusNotFound)
  183. rw.Write([]byte(NotFound))
  184. return
  185. }
  186. // Remove hop-by-hop headers listed in the
  187. // "Connection" header of the response.
  188. if c := res.Header.Get("Connection"); c != "" {
  189. for _, f := range strings.Split(c, ",") {
  190. if f = strings.TrimSpace(f); f != "" {
  191. res.Header.Del(f)
  192. }
  193. }
  194. }
  195. for _, h := range hopHeaders {
  196. res.Header.Del(h)
  197. }
  198. if p.ModifyResponse != nil {
  199. if err := p.ModifyResponse(res); err != nil {
  200. p.logf("http: proxy error: %v", err)
  201. rw.WriteHeader(http.StatusBadGateway)
  202. return
  203. }
  204. }
  205. copyHeader(rw.Header(), res.Header)
  206. // The "Trailer" header isn't included in the Transport's response,
  207. // at least for *http.Transport. Build it up from Trailer.
  208. announcedTrailers := len(res.Trailer)
  209. if announcedTrailers > 0 {
  210. trailerKeys := make([]string, 0, len(res.Trailer))
  211. for k := range res.Trailer {
  212. trailerKeys = append(trailerKeys, k)
  213. }
  214. rw.Header().Add("Trailer", strings.Join(trailerKeys, ", "))
  215. }
  216. rw.WriteHeader(res.StatusCode)
  217. if len(res.Trailer) > 0 {
  218. // Force chunking if we saw a response trailer.
  219. // This prevents net/http from calculating the length for short
  220. // bodies and adding a Content-Length.
  221. if fl, ok := rw.(http.Flusher); ok {
  222. fl.Flush()
  223. }
  224. }
  225. p.copyResponse(rw, res.Body)
  226. res.Body.Close() // close now, instead of defer, to populate res.Trailer
  227. if len(res.Trailer) == announcedTrailers {
  228. copyHeader(rw.Header(), res.Trailer)
  229. return
  230. }
  231. for k, vv := range res.Trailer {
  232. k = http.TrailerPrefix + k
  233. for _, v := range vv {
  234. rw.Header().Add(k, v)
  235. }
  236. }
  237. }
  238. func (p *ReverseProxy) copyResponse(dst io.Writer, src io.Reader) {
  239. if p.FlushInterval != 0 {
  240. if wf, ok := dst.(writeFlusher); ok {
  241. mlw := &maxLatencyWriter{
  242. dst: wf,
  243. latency: p.FlushInterval,
  244. done: make(chan bool),
  245. }
  246. go mlw.flushLoop()
  247. defer mlw.stop()
  248. dst = mlw
  249. }
  250. }
  251. var buf []byte
  252. if p.BufferPool != nil {
  253. buf = p.BufferPool.Get()
  254. }
  255. p.copyBuffer(dst, src, buf)
  256. if p.BufferPool != nil {
  257. p.BufferPool.Put(buf)
  258. }
  259. }
  260. func (p *ReverseProxy) copyBuffer(dst io.Writer, src io.Reader, buf []byte) (int64, error) {
  261. if len(buf) == 0 {
  262. buf = make([]byte, 32*1024)
  263. }
  264. var written int64
  265. for {
  266. nr, rerr := src.Read(buf)
  267. if rerr != nil && rerr != io.EOF && rerr != context.Canceled {
  268. p.logf("httputil: ReverseProxy read error during body copy: %v", rerr)
  269. }
  270. if nr > 0 {
  271. nw, werr := dst.Write(buf[:nr])
  272. if nw > 0 {
  273. written += int64(nw)
  274. }
  275. if werr != nil {
  276. return written, werr
  277. }
  278. if nr != nw {
  279. return written, io.ErrShortWrite
  280. }
  281. }
  282. if rerr != nil {
  283. return written, rerr
  284. }
  285. }
  286. }
  287. func (p *ReverseProxy) logf(format string, args ...interface{}) {
  288. if p.ErrorLog != nil {
  289. p.ErrorLog.Printf(format, args...)
  290. } else {
  291. log.Printf(format, args...)
  292. }
  293. }
  294. type writeFlusher interface {
  295. io.Writer
  296. http.Flusher
  297. }
  298. type maxLatencyWriter struct {
  299. dst writeFlusher
  300. latency time.Duration
  301. mu sync.Mutex // protects Write + Flush
  302. done chan bool
  303. }
  304. func (m *maxLatencyWriter) Write(p []byte) (int, error) {
  305. m.mu.Lock()
  306. defer m.mu.Unlock()
  307. return m.dst.Write(p)
  308. }
  309. func (m *maxLatencyWriter) flushLoop() {
  310. t := time.NewTicker(m.latency)
  311. defer t.Stop()
  312. for {
  313. select {
  314. case <-m.done:
  315. if onExitFlushLoop != nil {
  316. onExitFlushLoop()
  317. }
  318. return
  319. case <-t.C:
  320. m.mu.Lock()
  321. m.dst.Flush()
  322. m.mu.Unlock()
  323. }
  324. }
  325. }
  326. func (m *maxLatencyWriter) stop() { m.done <- true }