dpcore.go 11 KB

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