dpcore.go 12 KB

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