dpcore.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. package dpcore
  2. import (
  3. "errors"
  4. "io"
  5. "log"
  6. "net"
  7. "net/http"
  8. "net/url"
  9. "path/filepath"
  10. "strings"
  11. "sync"
  12. "time"
  13. )
  14. var onExitFlushLoop func()
  15. const (
  16. defaultTimeout = time.Minute * 5
  17. )
  18. // ReverseProxy is an HTTP Handler that takes an incoming request and
  19. // sends it to another server, proxying the response back to the
  20. // client, support http, also support https tunnel using http.hijacker
  21. type ReverseProxy struct {
  22. // Set the timeout of the proxy server, default is 5 minutes
  23. Timeout time.Duration
  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. // default is http.DefaultTransport.
  33. Transport http.RoundTripper
  34. // FlushInterval specifies the flush interval
  35. // to flush to the client while copying the
  36. // response body. If zero, no periodic flushing is done.
  37. FlushInterval time.Duration
  38. // ErrorLog specifies an optional logger for errors
  39. // that occur when attempting to proxy the request.
  40. // If nil, logging goes to os.Stderr via the log package's
  41. // standard logger.
  42. ErrorLog *log.Logger
  43. // ModifyResponse is an optional function that
  44. // modifies the Response from the backend.
  45. // If it returns an error, the proxy returns a StatusBadGateway error.
  46. ModifyResponse func(*http.Response) error
  47. //Prepender is an optional prepend text for URL rewrite
  48. //
  49. Prepender string
  50. Verbal bool
  51. }
  52. type requestCanceler interface {
  53. CancelRequest(req *http.Request)
  54. }
  55. func NewDynamicProxyCore(target *url.URL, prepender string) *ReverseProxy {
  56. targetQuery := target.RawQuery
  57. director := func(req *http.Request) {
  58. req.URL.Scheme = target.Scheme
  59. req.URL.Host = target.Host
  60. req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
  61. // If Host is empty, the Request.Write method uses
  62. // the value of URL.Host.
  63. // force use URL.Host
  64. req.Host = req.URL.Host
  65. if targetQuery == "" || req.URL.RawQuery == "" {
  66. req.URL.RawQuery = targetQuery + req.URL.RawQuery
  67. } else {
  68. req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
  69. }
  70. if _, ok := req.Header["User-Agent"]; !ok {
  71. req.Header.Set("User-Agent", "")
  72. }
  73. }
  74. return &ReverseProxy{
  75. Director: director,
  76. Prepender: prepender,
  77. Verbal: false,
  78. }
  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. if p.Verbal {
  235. p.logf("http: proxy error: %v", err)
  236. }
  237. //rw.WriteHeader(http.StatusBadGateway)
  238. return err
  239. }
  240. // Remove hop-by-hop headers listed in the "Connection" header of the response, Remove hop-by-hop headers.
  241. removeHeaders(res.Header)
  242. if p.ModifyResponse != nil {
  243. if err := p.ModifyResponse(res); err != nil {
  244. if p.Verbal {
  245. p.logf("http: proxy error: %v", err)
  246. }
  247. //rw.WriteHeader(http.StatusBadGateway)
  248. return err
  249. }
  250. }
  251. //Custom header rewriter functions
  252. if res.Header.Get("Location") != "" {
  253. //Custom redirection to this rproxy relative path
  254. res.Header.Set("Location", filepath.ToSlash(filepath.Join(p.Prepender, res.Header.Get("Location"))))
  255. }
  256. // Copy header from response to client.
  257. copyHeader(rw.Header(), res.Header)
  258. // The "Trailer" header isn't included in the Transport's response, Build it up from Trailer.
  259. if len(res.Trailer) > 0 {
  260. trailerKeys := make([]string, 0, len(res.Trailer))
  261. for k := range res.Trailer {
  262. trailerKeys = append(trailerKeys, k)
  263. }
  264. rw.Header().Add("Trailer", strings.Join(trailerKeys, ", "))
  265. }
  266. rw.WriteHeader(res.StatusCode)
  267. if len(res.Trailer) > 0 {
  268. // Force chunking if we saw a response trailer.
  269. // This prevents net/http from calculating the length for short
  270. // bodies and adding a Content-Length.
  271. if fl, ok := rw.(http.Flusher); ok {
  272. fl.Flush()
  273. }
  274. }
  275. p.copyResponse(rw, res.Body)
  276. // close now, instead of defer, to populate res.Trailer
  277. res.Body.Close()
  278. copyHeader(rw.Header(), res.Trailer)
  279. return nil
  280. }
  281. func (p *ReverseProxy) ProxyHTTPS(rw http.ResponseWriter, req *http.Request) error {
  282. hij, ok := rw.(http.Hijacker)
  283. if !ok {
  284. p.logf("http server does not support hijacker")
  285. return errors.New("http server does not support hijacker")
  286. }
  287. clientConn, _, err := hij.Hijack()
  288. if err != nil {
  289. if p.Verbal {
  290. p.logf("http: proxy error: %v", err)
  291. }
  292. return err
  293. }
  294. proxyConn, err := net.Dial("tcp", req.URL.Host)
  295. if err != nil {
  296. if p.Verbal {
  297. p.logf("http: proxy error: %v", err)
  298. }
  299. return err
  300. }
  301. // The returned net.Conn may have read or write deadlines
  302. // already set, depending on the configuration of the
  303. // Server, to set or clear those deadlines as needed
  304. // we set timeout to 5 minutes
  305. deadline := time.Now()
  306. if p.Timeout == 0 {
  307. deadline = deadline.Add(time.Minute * 5)
  308. } else {
  309. deadline = deadline.Add(p.Timeout)
  310. }
  311. err = clientConn.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 = proxyConn.SetDeadline(deadline)
  319. if err != nil {
  320. if p.Verbal {
  321. p.logf("http: proxy error: %v", err)
  322. }
  323. return err
  324. }
  325. _, err = clientConn.Write([]byte("HTTP/1.0 200 OK\r\n\r\n"))
  326. if err != nil {
  327. if p.Verbal {
  328. p.logf("http: proxy error: %v", err)
  329. }
  330. return err
  331. }
  332. go func() {
  333. io.Copy(clientConn, proxyConn)
  334. clientConn.Close()
  335. proxyConn.Close()
  336. }()
  337. io.Copy(proxyConn, clientConn)
  338. proxyConn.Close()
  339. clientConn.Close()
  340. return nil
  341. }
  342. func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) error {
  343. if req.Method == "CONNECT" {
  344. err := p.ProxyHTTPS(rw, req)
  345. return err
  346. } else {
  347. err := p.ProxyHTTP(rw, req)
  348. return err
  349. }
  350. }