dpcore.go 12 KB

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