dpcore.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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, ignoreTLSVerification bool) *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. optimalConcurrentConnection := 32
  78. thisTransporter.(*http.Transport).MaxIdleConns = optimalConcurrentConnection + 3
  79. thisTransporter.(*http.Transport).MaxIdleConnsPerHost = optimalConcurrentConnection
  80. thisTransporter.(*http.Transport).IdleConnTimeout = 60 * time.Second
  81. thisTransporter.(*http.Transport).MaxConnsPerHost = optimalConcurrentConnection + 3
  82. thisTransporter.(*http.Transport).DisableCompression = true
  83. if ignoreTLSVerification {
  84. //Ignore TLS certificate validation error
  85. thisTransporter.(*http.Transport).TLSClientConfig.InsecureSkipVerify = true
  86. }
  87. return &ReverseProxy{
  88. Director: director,
  89. Prepender: prepender,
  90. Verbal: false,
  91. Transport: thisTransporter,
  92. }
  93. }
  94. func singleJoiningSlash(a, b string) string {
  95. aslash := strings.HasSuffix(a, "/")
  96. bslash := strings.HasPrefix(b, "/")
  97. switch {
  98. case aslash && bslash:
  99. return a + b[1:]
  100. case !aslash && !bslash:
  101. return a + "/" + b
  102. }
  103. return a + b
  104. }
  105. func joinURLPath(a, b *url.URL) (path, rawpath string) {
  106. if a.RawPath == "" && b.RawPath == "" {
  107. return singleJoiningSlash(a.Path, b.Path), ""
  108. }
  109. // Same as singleJoiningSlash, but uses EscapedPath to determine
  110. // whether a slash should be added
  111. apath := a.EscapedPath()
  112. bpath := b.EscapedPath()
  113. aslash := strings.HasSuffix(apath, "/")
  114. bslash := strings.HasPrefix(bpath, "/")
  115. switch {
  116. case aslash && bslash:
  117. return a.Path + b.Path[1:], apath + bpath[1:]
  118. case !aslash && !bslash:
  119. return a.Path + "/" + b.Path, apath + "/" + bpath
  120. }
  121. return a.Path + b.Path, apath + bpath
  122. }
  123. func copyHeader(dst, src http.Header) {
  124. for k, vv := range src {
  125. for _, v := range vv {
  126. dst.Add(k, v)
  127. }
  128. }
  129. }
  130. // Hop-by-hop headers. These are removed when sent to the backend.
  131. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
  132. var hopHeaders = []string{
  133. //"Connection",
  134. "Proxy-Connection", // non-standard but still sent by libcurl and rejected by e.g. google
  135. "Keep-Alive",
  136. "Proxy-Authenticate",
  137. "Proxy-Authorization",
  138. "Te", // canonicalized version of "TE"
  139. "Trailer", // not Trailers per URL above; http://www.rfc-editor.org/errata_search.php?eid=4522
  140. "Transfer-Encoding",
  141. //"Upgrade",
  142. }
  143. func (p *ReverseProxy) copyResponse(dst io.Writer, src io.Reader) {
  144. if p.FlushInterval != 0 {
  145. if wf, ok := dst.(writeFlusher); ok {
  146. mlw := &maxLatencyWriter{
  147. dst: wf,
  148. latency: p.FlushInterval,
  149. done: make(chan bool),
  150. }
  151. go mlw.flushLoop()
  152. defer mlw.stop()
  153. dst = mlw
  154. }
  155. }
  156. io.Copy(dst, src)
  157. }
  158. type writeFlusher interface {
  159. io.Writer
  160. http.Flusher
  161. }
  162. type maxLatencyWriter struct {
  163. dst writeFlusher
  164. latency time.Duration
  165. mu sync.Mutex
  166. done chan bool
  167. }
  168. func (m *maxLatencyWriter) Write(b []byte) (int, error) {
  169. m.mu.Lock()
  170. defer m.mu.Unlock()
  171. return m.dst.Write(b)
  172. }
  173. func (m *maxLatencyWriter) flushLoop() {
  174. t := time.NewTicker(m.latency)
  175. defer t.Stop()
  176. for {
  177. select {
  178. case <-m.done:
  179. if onExitFlushLoop != nil {
  180. onExitFlushLoop()
  181. }
  182. return
  183. case <-t.C:
  184. m.mu.Lock()
  185. m.dst.Flush()
  186. m.mu.Unlock()
  187. }
  188. }
  189. }
  190. func (m *maxLatencyWriter) stop() {
  191. m.done <- true
  192. }
  193. func (p *ReverseProxy) logf(format string, args ...interface{}) {
  194. if p.ErrorLog != nil {
  195. p.ErrorLog.Printf(format, args...)
  196. } else {
  197. log.Printf(format, args...)
  198. }
  199. }
  200. func removeHeaders(header http.Header) {
  201. // Remove hop-by-hop headers listed in the "Connection" header.
  202. if c := header.Get("Connection"); c != "" {
  203. for _, f := range strings.Split(c, ",") {
  204. if f = strings.TrimSpace(f); f != "" {
  205. header.Del(f)
  206. }
  207. }
  208. }
  209. // Remove hop-by-hop headers
  210. for _, h := range hopHeaders {
  211. if header.Get(h) != "" {
  212. header.Del(h)
  213. }
  214. }
  215. if header.Get("A-Upgrade") != "" {
  216. header.Set("Upgrade", header.Get("A-Upgrade"))
  217. header.Del("A-Upgrade")
  218. }
  219. }
  220. func addXForwardedForHeader(req *http.Request) {
  221. if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
  222. // If we aren't the first proxy retain prior
  223. // X-Forwarded-For information as a comma+space
  224. // separated list and fold multiple headers into one.
  225. if prior, ok := req.Header["X-Forwarded-For"]; ok {
  226. clientIP = strings.Join(prior, ", ") + ", " + clientIP
  227. }
  228. req.Header.Set("X-Forwarded-For", clientIP)
  229. if req.TLS != nil {
  230. req.Header.Set("X-Forwarded-Proto", "https")
  231. } else {
  232. req.Header.Set("X-Forwarded-Proto", "http")
  233. }
  234. }
  235. }
  236. func (p *ReverseProxy) ProxyHTTP(rw http.ResponseWriter, req *http.Request, rrr *ResponseRewriteRuleSet) error {
  237. transport := p.Transport
  238. outreq := new(http.Request)
  239. // Shallow copies of maps, like header
  240. *outreq = *req
  241. if cn, ok := rw.(http.CloseNotifier); ok {
  242. if requestCanceler, ok := transport.(requestCanceler); ok {
  243. // After the Handler has returned, there is no guarantee
  244. // that the channel receives a value, so to make sure
  245. reqDone := make(chan struct{})
  246. defer close(reqDone)
  247. clientGone := cn.CloseNotify()
  248. go func() {
  249. select {
  250. case <-clientGone:
  251. requestCanceler.CancelRequest(outreq)
  252. case <-reqDone:
  253. }
  254. }()
  255. }
  256. }
  257. p.Director(outreq)
  258. outreq.Close = false
  259. if !rrr.UseTLS {
  260. //This seems to be routing to external sites
  261. //Do not keep the original host
  262. outreq.Host = rrr.OriginalHost
  263. }
  264. // We may modify the header (shallow copied above), so we only copy it.
  265. outreq.Header = make(http.Header)
  266. copyHeader(outreq.Header, req.Header)
  267. // Remove hop-by-hop headers listed in the "Connection" header, Remove hop-by-hop headers.
  268. removeHeaders(outreq.Header)
  269. // Add X-Forwarded-For Header.
  270. addXForwardedForHeader(outreq)
  271. res, err := transport.RoundTrip(outreq)
  272. if err != nil {
  273. if p.Verbal {
  274. p.logf("http: proxy error: %v", err)
  275. }
  276. //rw.WriteHeader(http.StatusBadGateway)
  277. return err
  278. }
  279. // Remove hop-by-hop headers listed in the "Connection" header of the response, Remove hop-by-hop headers.
  280. removeHeaders(res.Header)
  281. if p.ModifyResponse != nil {
  282. if err := p.ModifyResponse(res); err != nil {
  283. if p.Verbal {
  284. p.logf("http: proxy error: %v", err)
  285. }
  286. //rw.WriteHeader(http.StatusBadGateway)
  287. return err
  288. }
  289. }
  290. //Custom header rewriter functions
  291. if res.Header.Get("Location") != "" {
  292. locationRewrite := res.Header.Get("Location")
  293. originLocation := res.Header.Get("Location")
  294. res.Header.Set("zr-origin-location", originLocation)
  295. if strings.HasPrefix(originLocation, "http://") || strings.HasPrefix(originLocation, "https://") {
  296. //Full path
  297. //Replace the forwarded target with expected Host
  298. lr, err := replaceLocationHost(locationRewrite, rrr, req.TLS != nil)
  299. if err == nil {
  300. locationRewrite = lr
  301. }
  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. }