dpcore.go 10 KB

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