dpcore.go 12 KB

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