dpcore.go 12 KB

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