dpcore.go 14 KB

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