dpcore.go 11 KB

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