dpcore.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. package dpcore
  2. import (
  3. "context"
  4. "errors"
  5. "io"
  6. "log"
  7. "net"
  8. "net/http"
  9. "net/url"
  10. "strings"
  11. "time"
  12. "imuslab.com/zoraxy/mod/dynamicproxy/permissionpolicy"
  13. )
  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. UpstreamHeaders [][]string
  55. DownstreamHeaders [][]string
  56. }
  57. type requestCanceler interface {
  58. CancelRequest(req *http.Request)
  59. }
  60. type DpcoreOptions struct {
  61. IgnoreTLSVerification bool
  62. FlushInterval time.Duration
  63. }
  64. func NewDynamicProxyCore(target *url.URL, prepender string, dpcOptions *DpcoreOptions) *ReverseProxy {
  65. targetQuery := target.RawQuery
  66. director := func(req *http.Request) {
  67. req.URL.Scheme = target.Scheme
  68. req.URL.Host = target.Host
  69. req.URL.Path, req.URL.RawPath = joinURLPath(target, req.URL)
  70. if targetQuery == "" || req.URL.RawQuery == "" {
  71. req.URL.RawQuery = targetQuery + req.URL.RawQuery
  72. } else {
  73. req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
  74. }
  75. }
  76. //Hack the default transporter to handle more connections
  77. thisTransporter := http.DefaultTransport
  78. optimalConcurrentConnection := 32
  79. thisTransporter.(*http.Transport).MaxIdleConns = optimalConcurrentConnection * 2
  80. thisTransporter.(*http.Transport).MaxIdleConnsPerHost = optimalConcurrentConnection
  81. thisTransporter.(*http.Transport).IdleConnTimeout = 30 * time.Second
  82. thisTransporter.(*http.Transport).MaxConnsPerHost = optimalConcurrentConnection * 2
  83. thisTransporter.(*http.Transport).DisableCompression = true
  84. if dpcOptions.IgnoreTLSVerification {
  85. //Ignore TLS certificate validation error
  86. thisTransporter.(*http.Transport).TLSClientConfig.InsecureSkipVerify = true
  87. }
  88. return &ReverseProxy{
  89. Director: director,
  90. Prepender: prepender,
  91. FlushInterval: dpcOptions.FlushInterval,
  92. Verbal: false,
  93. Transport: thisTransporter,
  94. }
  95. }
  96. func singleJoiningSlash(a, b string) string {
  97. aslash := strings.HasSuffix(a, "/")
  98. bslash := strings.HasPrefix(b, "/")
  99. switch {
  100. case aslash && bslash:
  101. return a + b[1:]
  102. case !aslash && !bslash:
  103. return a + "/" + b
  104. }
  105. return a + b
  106. }
  107. func joinURLPath(a, b *url.URL) (path, rawpath string) {
  108. if a.RawPath == "" && b.RawPath == "" {
  109. return singleJoiningSlash(a.Path, b.Path), ""
  110. }
  111. // Same as singleJoiningSlash, but uses EscapedPath to determine
  112. // whether a slash should be added
  113. apath := a.EscapedPath()
  114. bpath := b.EscapedPath()
  115. aslash := strings.HasSuffix(apath, "/")
  116. bslash := strings.HasPrefix(bpath, "/")
  117. switch {
  118. case aslash && bslash:
  119. return a.Path + b.Path[1:], apath + bpath[1:]
  120. case !aslash && !bslash:
  121. return a.Path + "/" + b.Path, apath + "/" + bpath
  122. }
  123. return a.Path + b.Path, apath + bpath
  124. }
  125. func copyHeader(dst, src http.Header) {
  126. for k, vv := range src {
  127. for _, v := range vv {
  128. dst.Add(k, v)
  129. }
  130. }
  131. }
  132. // Hop-by-hop headers. These are removed when sent to the backend.
  133. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
  134. var hopHeaders = []string{
  135. //"Connection",
  136. "Proxy-Connection", // non-standard but still sent by libcurl and rejected by e.g. google
  137. "Keep-Alive",
  138. "Proxy-Authenticate",
  139. "Proxy-Authorization",
  140. "Te", // canonicalized version of "TE"
  141. "Trailer", // not Trailers per URL above; http://www.rfc-editor.org/errata_search.php?eid=4522
  142. "Transfer-Encoding",
  143. //"Upgrade",
  144. }
  145. // Copy response from src to dst with given flush interval, reference from httputil.ReverseProxy
  146. func (p *ReverseProxy) copyResponse(dst http.ResponseWriter, src io.Reader, flushInterval time.Duration) error {
  147. var w io.Writer = dst
  148. if flushInterval != 0 {
  149. mlw := &maxLatencyWriter{
  150. dst: dst,
  151. flush: http.NewResponseController(dst).Flush,
  152. latency: flushInterval,
  153. }
  154. defer mlw.stop()
  155. // set up initial timer so headers get flushed even if body writes are delayed
  156. mlw.flushPending = true
  157. mlw.t = time.AfterFunc(flushInterval, mlw.delayedFlush)
  158. w = mlw
  159. }
  160. var buf []byte
  161. _, err := p.copyBuffer(w, src, buf)
  162. return err
  163. }
  164. // Copy with given buffer size. Default to 64k
  165. func (p *ReverseProxy) copyBuffer(dst io.Writer, src io.Reader, buf []byte) (int64, error) {
  166. if len(buf) == 0 {
  167. buf = make([]byte, 64*1024)
  168. }
  169. var written int64
  170. for {
  171. nr, rerr := src.Read(buf)
  172. if rerr != nil && rerr != io.EOF && rerr != context.Canceled {
  173. p.logf("dpcore read error during body copy: %v", rerr)
  174. }
  175. if nr > 0 {
  176. nw, werr := dst.Write(buf[:nr])
  177. if nw > 0 {
  178. written += int64(nw)
  179. }
  180. if werr != nil {
  181. return written, werr
  182. }
  183. if nr != nw {
  184. return written, io.ErrShortWrite
  185. }
  186. }
  187. if rerr != nil {
  188. if rerr == io.EOF {
  189. rerr = nil
  190. }
  191. return written, rerr
  192. }
  193. }
  194. }
  195. func (p *ReverseProxy) logf(format string, args ...interface{}) {
  196. if p.ErrorLog != nil {
  197. p.ErrorLog.Printf(format, args...)
  198. } else {
  199. log.Printf(format, args...)
  200. }
  201. }
  202. func removeHeaders(header http.Header, noCache bool) {
  203. // Remove hop-by-hop headers listed in the "Connection" header.
  204. if c := header.Get("Connection"); c != "" {
  205. for _, f := range strings.Split(c, ",") {
  206. if f = strings.TrimSpace(f); f != "" {
  207. header.Del(f)
  208. }
  209. }
  210. }
  211. // Remove hop-by-hop headers
  212. for _, h := range hopHeaders {
  213. if header.Get(h) != "" {
  214. header.Del(h)
  215. }
  216. }
  217. //Restore the Upgrade header if any
  218. if header.Get("Zr-Origin-Upgrade") != "" {
  219. header.Set("Upgrade", header.Get("Zr-Origin-Upgrade"))
  220. header.Del("Zr-Origin-Upgrade")
  221. }
  222. //Disable cache if nocache is set
  223. if noCache {
  224. header.Del("Cache-Control")
  225. header.Set("Cache-Control", "no-store")
  226. }
  227. //Hide Go-HTTP-Client UA if the client didnt sent us one
  228. if _, ok := header["User-Agent"]; !ok {
  229. // If the outbound request doesn't have a User-Agent header set,
  230. // don't send the default Go HTTP client User-Agent.
  231. header.Set("User-Agent", "")
  232. }
  233. }
  234. func addXForwardedForHeader(req *http.Request) {
  235. if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
  236. // If we aren't the first proxy retain prior
  237. // X-Forwarded-For information as a comma+space
  238. // separated list and fold multiple headers into one.
  239. if prior, ok := req.Header["X-Forwarded-For"]; ok {
  240. clientIP = strings.Join(prior, ", ") + ", " + clientIP
  241. }
  242. req.Header.Set("X-Forwarded-For", clientIP)
  243. if req.TLS != nil {
  244. req.Header.Set("X-Forwarded-Proto", "https")
  245. } else {
  246. req.Header.Set("X-Forwarded-Proto", "http")
  247. }
  248. if req.Header.Get("X-Real-Ip") == "" {
  249. //Check if CF-Connecting-IP header exists
  250. CF_Connecting_IP := req.Header.Get("CF-Connecting-IP")
  251. Fastly_Client_IP := req.Header.Get("Fastly-Client-IP")
  252. if CF_Connecting_IP != "" {
  253. //Use CF Connecting IP
  254. req.Header.Set("X-Real-Ip", CF_Connecting_IP)
  255. } else if Fastly_Client_IP != "" {
  256. //Use Fastly Client IP
  257. req.Header.Set("X-Real-Ip", Fastly_Client_IP)
  258. } else {
  259. // Not exists. Fill it in with first entry in X-Forwarded-For
  260. ips := strings.Split(clientIP, ",")
  261. if len(ips) > 0 {
  262. req.Header.Set("X-Real-Ip", strings.TrimSpace(ips[0]))
  263. }
  264. }
  265. }
  266. }
  267. }
  268. func (p *ReverseProxy) ProxyHTTP(rw http.ResponseWriter, req *http.Request, rrr *ResponseRewriteRuleSet) error {
  269. transport := p.Transport
  270. outreq := new(http.Request)
  271. // Shallow copies of maps, like header
  272. *outreq = *req
  273. if cn, ok := rw.(http.CloseNotifier); ok {
  274. if requestCanceler, ok := transport.(requestCanceler); ok {
  275. // After the Handler has returned, there is no guarantee
  276. // that the channel receives a value, so to make sure
  277. reqDone := make(chan struct{})
  278. defer close(reqDone)
  279. clientGone := cn.CloseNotify()
  280. go func() {
  281. select {
  282. case <-clientGone:
  283. requestCanceler.CancelRequest(outreq)
  284. case <-reqDone:
  285. }
  286. }()
  287. }
  288. }
  289. p.Director(outreq)
  290. outreq.Close = false
  291. //Only skip origin rewrite iff proxy target require TLS and it is external domain name like github.com
  292. if !(rrr.UseTLS && isExternalDomainName(rrr.ProxyDomain)) {
  293. // Always use the original host, see issue #164
  294. outreq.Host = rrr.OriginalHost
  295. }
  296. // We may modify the header (shallow copied above), so we only copy it.
  297. outreq.Header = make(http.Header)
  298. copyHeader(outreq.Header, req.Header)
  299. // Remove hop-by-hop headers listed in the "Connection" header, Remove hop-by-hop headers.
  300. removeHeaders(outreq.Header, rrr.NoCache)
  301. // Add X-Forwarded-For Header.
  302. addXForwardedForHeader(outreq)
  303. res, err := transport.RoundTrip(outreq)
  304. if err != nil {
  305. if p.Verbal {
  306. p.logf("http: proxy error: %v", err)
  307. }
  308. //rw.WriteHeader(http.StatusBadGateway)
  309. return err
  310. }
  311. // Remove hop-by-hop headers listed in the "Connection" header of the response, Remove hop-by-hop headers.
  312. removeHeaders(res.Header, rrr.NoCache)
  313. //Remove the User-Agent header if exists
  314. if _, ok := res.Header["User-Agent"]; ok {
  315. //Server to client request should not contains a User-Agent header
  316. res.Header.Del("User-Agent")
  317. }
  318. if p.ModifyResponse != nil {
  319. if err := p.ModifyResponse(res); err != nil {
  320. if p.Verbal {
  321. p.logf("http: proxy error: %v", err)
  322. }
  323. //rw.WriteHeader(http.StatusBadGateway)
  324. return err
  325. }
  326. }
  327. //if res.StatusCode == 501 || res.StatusCode == 500 {
  328. // fmt.Println(outreq.Proto, outreq.RemoteAddr, outreq.RequestURI)
  329. // fmt.Println(">>>", outreq.Method, res.Header, res.ContentLength, res.StatusCode)
  330. // fmt.Println(outreq.Header, req.Host)
  331. //}
  332. //Custom header rewriter functions
  333. if res.Header.Get("Location") != "" {
  334. locationRewrite := res.Header.Get("Location")
  335. originLocation := res.Header.Get("Location")
  336. res.Header.Set("zr-origin-location", originLocation)
  337. if strings.HasPrefix(originLocation, "http://") || strings.HasPrefix(originLocation, "https://") {
  338. //Full path
  339. //Replace the forwarded target with expected Host
  340. lr, err := replaceLocationHost(locationRewrite, rrr, req.TLS != nil)
  341. if err == nil {
  342. locationRewrite = lr
  343. }
  344. } else if strings.HasPrefix(originLocation, "/") && rrr.PathPrefix != "" {
  345. //Back to the root of this proxy object
  346. //fmt.Println(rrr.ProxyDomain, rrr.OriginalHost)
  347. locationRewrite = strings.TrimSuffix(rrr.PathPrefix, "/") + originLocation
  348. } else {
  349. //Relative path. Do not modifiy location header
  350. }
  351. //Custom redirection to this rproxy relative path
  352. res.Header.Set("Location", locationRewrite)
  353. }
  354. // Copy header from response to client.
  355. copyHeader(rw.Header(), res.Header)
  356. // inject permission policy headers
  357. //TODO: Load permission policy from rrr
  358. permissionpolicy.InjectPermissionPolicyHeader(rw, nil)
  359. // The "Trailer" header isn't included in the Transport's response, Build it up from Trailer.
  360. if len(res.Trailer) > 0 {
  361. trailerKeys := make([]string, 0, len(res.Trailer))
  362. for k := range res.Trailer {
  363. trailerKeys = append(trailerKeys, k)
  364. }
  365. rw.Header().Add("Trailer", strings.Join(trailerKeys, ", "))
  366. }
  367. rw.WriteHeader(res.StatusCode)
  368. if len(res.Trailer) > 0 {
  369. // Force chunking if we saw a response trailer.
  370. // This prevents net/http from calculating the length for short
  371. // bodies and adding a Content-Length.
  372. if fl, ok := rw.(http.Flusher); ok {
  373. fl.Flush()
  374. }
  375. }
  376. //Get flush interval in real time and start copying the request
  377. flushInterval := p.getFlushInterval(req, res)
  378. p.copyResponse(rw, res.Body, flushInterval)
  379. // close now, instead of defer, to populate res.Trailer
  380. res.Body.Close()
  381. copyHeader(rw.Header(), res.Trailer)
  382. return nil
  383. }
  384. func (p *ReverseProxy) ProxyHTTPS(rw http.ResponseWriter, req *http.Request) error {
  385. hij, ok := rw.(http.Hijacker)
  386. if !ok {
  387. p.logf("http server does not support hijacker")
  388. return errors.New("http server does not support hijacker")
  389. }
  390. clientConn, _, err := hij.Hijack()
  391. if err != nil {
  392. if p.Verbal {
  393. p.logf("http: proxy error: %v", err)
  394. }
  395. return err
  396. }
  397. proxyConn, err := net.Dial("tcp", req.URL.Host)
  398. if err != nil {
  399. if p.Verbal {
  400. p.logf("http: proxy error: %v", err)
  401. }
  402. return err
  403. }
  404. // The returned net.Conn may have read or write deadlines
  405. // already set, depending on the configuration of the
  406. // Server, to set or clear those deadlines as needed
  407. // we set timeout to 5 minutes
  408. deadline := time.Now()
  409. if p.Timeout == 0 {
  410. deadline = deadline.Add(time.Minute * 5)
  411. } else {
  412. deadline = deadline.Add(p.Timeout)
  413. }
  414. err = clientConn.SetDeadline(deadline)
  415. if err != nil {
  416. if p.Verbal {
  417. p.logf("http: proxy error: %v", err)
  418. }
  419. return err
  420. }
  421. err = proxyConn.SetDeadline(deadline)
  422. if err != nil {
  423. if p.Verbal {
  424. p.logf("http: proxy error: %v", err)
  425. }
  426. return err
  427. }
  428. _, err = clientConn.Write([]byte("HTTP/1.0 200 OK\r\n\r\n"))
  429. if err != nil {
  430. if p.Verbal {
  431. p.logf("http: proxy error: %v", err)
  432. }
  433. return err
  434. }
  435. go func() {
  436. io.Copy(clientConn, proxyConn)
  437. clientConn.Close()
  438. proxyConn.Close()
  439. }()
  440. io.Copy(proxyConn, clientConn)
  441. proxyConn.Close()
  442. clientConn.Close()
  443. return nil
  444. }
  445. func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request, rrr *ResponseRewriteRuleSet) error {
  446. if req.Method == "CONNECT" {
  447. err := p.ProxyHTTPS(rw, req)
  448. return err
  449. } else {
  450. err := p.ProxyHTTP(rw, req, rrr)
  451. return err
  452. }
  453. }