dpcore.go 10 KB

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