dpcore.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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. if CF_Connecting_IP != "" {
  250. //Use CF Connecting IP
  251. req.Header.Set("X-Real-Ip", CF_Connecting_IP)
  252. } else {
  253. // Not exists. Fill it in with first entry in X-Forwarded-For
  254. ips := strings.Split(clientIP, ",")
  255. if len(ips) > 0 {
  256. req.Header.Set("X-Real-Ip", strings.TrimSpace(ips[0]))
  257. }
  258. }
  259. }
  260. }
  261. }
  262. func (p *ReverseProxy) ProxyHTTP(rw http.ResponseWriter, req *http.Request, rrr *ResponseRewriteRuleSet) error {
  263. transport := p.Transport
  264. outreq := new(http.Request)
  265. // Shallow copies of maps, like header
  266. *outreq = *req
  267. if cn, ok := rw.(http.CloseNotifier); ok {
  268. if requestCanceler, ok := transport.(requestCanceler); ok {
  269. // After the Handler has returned, there is no guarantee
  270. // that the channel receives a value, so to make sure
  271. reqDone := make(chan struct{})
  272. defer close(reqDone)
  273. clientGone := cn.CloseNotify()
  274. go func() {
  275. select {
  276. case <-clientGone:
  277. requestCanceler.CancelRequest(outreq)
  278. case <-reqDone:
  279. }
  280. }()
  281. }
  282. }
  283. p.Director(outreq)
  284. outreq.Close = false
  285. //Only skip origin rewrite iff proxy target require TLS and it is external domain name like github.com
  286. if !(rrr.UseTLS && isExternalDomainName(rrr.ProxyDomain)) {
  287. // Always use the original host, see issue #164
  288. outreq.Host = rrr.OriginalHost
  289. }
  290. // We may modify the header (shallow copied above), so we only copy it.
  291. outreq.Header = make(http.Header)
  292. copyHeader(outreq.Header, req.Header)
  293. // Remove hop-by-hop headers listed in the "Connection" header, Remove hop-by-hop headers.
  294. removeHeaders(outreq.Header, rrr.NoCache)
  295. // Add X-Forwarded-For Header.
  296. addXForwardedForHeader(outreq)
  297. res, err := transport.RoundTrip(outreq)
  298. if err != nil {
  299. if p.Verbal {
  300. p.logf("http: proxy error: %v", err)
  301. }
  302. //rw.WriteHeader(http.StatusBadGateway)
  303. return err
  304. }
  305. // Remove hop-by-hop headers listed in the "Connection" header of the response, Remove hop-by-hop headers.
  306. removeHeaders(res.Header, rrr.NoCache)
  307. //Remove the User-Agent header if exists
  308. if _, ok := res.Header["User-Agent"]; ok {
  309. //Server to client request should not contains a User-Agent header
  310. res.Header.Del("User-Agent")
  311. }
  312. if p.ModifyResponse != nil {
  313. if err := p.ModifyResponse(res); err != nil {
  314. if p.Verbal {
  315. p.logf("http: proxy error: %v", err)
  316. }
  317. //rw.WriteHeader(http.StatusBadGateway)
  318. return err
  319. }
  320. }
  321. //if res.StatusCode == 501 || res.StatusCode == 500 {
  322. // fmt.Println(outreq.Proto, outreq.RemoteAddr, outreq.RequestURI)
  323. // fmt.Println(">>>", outreq.Method, res.Header, res.ContentLength, res.StatusCode)
  324. // fmt.Println(outreq.Header, req.Host)
  325. //}
  326. //Custom header rewriter functions
  327. if res.Header.Get("Location") != "" {
  328. locationRewrite := res.Header.Get("Location")
  329. originLocation := res.Header.Get("Location")
  330. res.Header.Set("zr-origin-location", originLocation)
  331. if strings.HasPrefix(originLocation, "http://") || strings.HasPrefix(originLocation, "https://") {
  332. //Full path
  333. //Replace the forwarded target with expected Host
  334. lr, err := replaceLocationHost(locationRewrite, rrr, req.TLS != nil)
  335. if err == nil {
  336. locationRewrite = lr
  337. }
  338. } else if strings.HasPrefix(originLocation, "/") && rrr.PathPrefix != "" {
  339. //Back to the root of this proxy object
  340. //fmt.Println(rrr.ProxyDomain, rrr.OriginalHost)
  341. locationRewrite = strings.TrimSuffix(rrr.PathPrefix, "/") + originLocation
  342. } else {
  343. //Relative path. Do not modifiy location header
  344. }
  345. //Custom redirection to this rproxy relative path
  346. res.Header.Set("Location", locationRewrite)
  347. }
  348. // Copy header from response to client.
  349. copyHeader(rw.Header(), res.Header)
  350. // inject permission policy headers
  351. //TODO: Load permission policy from rrr
  352. permissionpolicy.InjectPermissionPolicyHeader(rw, nil)
  353. // The "Trailer" header isn't included in the Transport's response, Build it up from Trailer.
  354. if len(res.Trailer) > 0 {
  355. trailerKeys := make([]string, 0, len(res.Trailer))
  356. for k := range res.Trailer {
  357. trailerKeys = append(trailerKeys, k)
  358. }
  359. rw.Header().Add("Trailer", strings.Join(trailerKeys, ", "))
  360. }
  361. rw.WriteHeader(res.StatusCode)
  362. if len(res.Trailer) > 0 {
  363. // Force chunking if we saw a response trailer.
  364. // This prevents net/http from calculating the length for short
  365. // bodies and adding a Content-Length.
  366. if fl, ok := rw.(http.Flusher); ok {
  367. fl.Flush()
  368. }
  369. }
  370. //Get flush interval in real time and start copying the request
  371. flushInterval := p.getFlushInterval(req, res)
  372. p.copyResponse(rw, res.Body, flushInterval)
  373. // close now, instead of defer, to populate res.Trailer
  374. res.Body.Close()
  375. copyHeader(rw.Header(), res.Trailer)
  376. return nil
  377. }
  378. func (p *ReverseProxy) ProxyHTTPS(rw http.ResponseWriter, req *http.Request) error {
  379. hij, ok := rw.(http.Hijacker)
  380. if !ok {
  381. p.logf("http server does not support hijacker")
  382. return errors.New("http server does not support hijacker")
  383. }
  384. clientConn, _, err := hij.Hijack()
  385. if err != nil {
  386. if p.Verbal {
  387. p.logf("http: proxy error: %v", err)
  388. }
  389. return err
  390. }
  391. proxyConn, err := net.Dial("tcp", req.URL.Host)
  392. if err != nil {
  393. if p.Verbal {
  394. p.logf("http: proxy error: %v", err)
  395. }
  396. return err
  397. }
  398. // The returned net.Conn may have read or write deadlines
  399. // already set, depending on the configuration of the
  400. // Server, to set or clear those deadlines as needed
  401. // we set timeout to 5 minutes
  402. deadline := time.Now()
  403. if p.Timeout == 0 {
  404. deadline = deadline.Add(time.Minute * 5)
  405. } else {
  406. deadline = deadline.Add(p.Timeout)
  407. }
  408. err = clientConn.SetDeadline(deadline)
  409. if err != nil {
  410. if p.Verbal {
  411. p.logf("http: proxy error: %v", err)
  412. }
  413. return err
  414. }
  415. err = proxyConn.SetDeadline(deadline)
  416. if err != nil {
  417. if p.Verbal {
  418. p.logf("http: proxy error: %v", err)
  419. }
  420. return err
  421. }
  422. _, err = clientConn.Write([]byte("HTTP/1.0 200 OK\r\n\r\n"))
  423. if err != nil {
  424. if p.Verbal {
  425. p.logf("http: proxy error: %v", err)
  426. }
  427. return err
  428. }
  429. go func() {
  430. io.Copy(clientConn, proxyConn)
  431. clientConn.Close()
  432. proxyConn.Close()
  433. }()
  434. io.Copy(proxyConn, clientConn)
  435. proxyConn.Close()
  436. clientConn.Close()
  437. return nil
  438. }
  439. func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request, rrr *ResponseRewriteRuleSet) error {
  440. if req.Method == "CONNECT" {
  441. err := p.ProxyHTTPS(rw, req)
  442. return err
  443. } else {
  444. err := p.ProxyHTTP(rw, req, rrr)
  445. return err
  446. }
  447. }