dpcore.go 11 KB

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