dpcore.go 11 KB

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