dpcore.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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/domainsniff"
  13. "imuslab.com/zoraxy/mod/dynamicproxy/modh2c"
  14. "imuslab.com/zoraxy/mod/dynamicproxy/permissionpolicy"
  15. )
  16. // ReverseProxy is an HTTP Handler that takes an incoming request and
  17. // sends it to another server, proxying the response back to the
  18. // client, support http, also support https tunnel using http.hijacker
  19. type ReverseProxy struct {
  20. // Set the timeout of the proxy server, default is 5 minutes
  21. Timeout time.Duration
  22. // Director must be a function which modifies
  23. // the request into a new request to be sent
  24. // using Transport. Its response is then copied
  25. // back to the original client unmodified.
  26. // Director must not access the provided Request
  27. // after returning.
  28. Director func(*http.Request)
  29. // The transport used to perform proxy requests.
  30. // default is http.DefaultTransport.
  31. Transport http.RoundTripper
  32. // FlushInterval specifies the flush interval
  33. // to flush to the client while copying the
  34. // response body. If zero, no periodic flushing is done.
  35. FlushInterval time.Duration
  36. // ErrorLog specifies an optional logger for errors
  37. // that occur when attempting to proxy the request.
  38. // If nil, logging goes to os.Stderr via the log package's
  39. // standard logger.
  40. ErrorLog *log.Logger
  41. // ModifyResponse is an optional function that
  42. // modifies the Response from the backend.
  43. // If it returns an error, the proxy returns a StatusBadGateway error.
  44. ModifyResponse func(*http.Response) error
  45. //Prepender is an optional prepend text for URL rewrite
  46. Prepender string
  47. Verbal bool
  48. //Appended by Zoraxy project
  49. }
  50. type ResponseRewriteRuleSet struct {
  51. /* Basic Rewrite Rulesets */
  52. ProxyDomain string
  53. OriginalHost string
  54. UseTLS bool
  55. NoCache bool
  56. PathPrefix string //Vdir prefix for root, / will be rewrite to this
  57. UpstreamHeaders [][]string
  58. DownstreamHeaders [][]string
  59. /* Advance Usecase Options */
  60. HostHeaderOverwrite string //Force overwrite of request "Host" header (advanced usecase)
  61. NoRemoveHopByHop bool //Do not remove hop-by-hop headers (advanced usecase)
  62. /* System Information Payload */
  63. Version string //Version number of Zoraxy, use for X-Proxy-By
  64. }
  65. type requestCanceler interface {
  66. CancelRequest(req *http.Request)
  67. }
  68. type DpcoreOptions struct {
  69. IgnoreTLSVerification bool //Disable all TLS verification when request pass through this proxy router
  70. FlushInterval time.Duration //Duration to flush in normal requests. Stream request or keep-alive request will always flush with interval of -1 (immediately)
  71. UseH2CRoundTripper bool //Use H2C RoundTripper for HTTP/2.0 connection
  72. }
  73. func NewDynamicProxyCore(target *url.URL, prepender string, dpcOptions *DpcoreOptions) *ReverseProxy {
  74. targetQuery := target.RawQuery
  75. director := func(req *http.Request) {
  76. req.URL.Scheme = target.Scheme
  77. req.URL.Host = target.Host
  78. req.URL.Path, req.URL.RawPath = joinURLPath(target, req.URL)
  79. if targetQuery == "" || req.URL.RawQuery == "" {
  80. req.URL.RawQuery = targetQuery + req.URL.RawQuery
  81. } else {
  82. req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
  83. }
  84. }
  85. thisTransporter := http.DefaultTransport
  86. //Hack the default transporter to handle more connections
  87. optimalConcurrentConnection := 32
  88. thisTransporter.(*http.Transport).MaxIdleConns = optimalConcurrentConnection * 2
  89. thisTransporter.(*http.Transport).MaxIdleConnsPerHost = optimalConcurrentConnection
  90. thisTransporter.(*http.Transport).IdleConnTimeout = 30 * time.Second
  91. thisTransporter.(*http.Transport).MaxConnsPerHost = optimalConcurrentConnection * 2
  92. thisTransporter.(*http.Transport).DisableCompression = true
  93. if dpcOptions.IgnoreTLSVerification {
  94. //Ignore TLS certificate validation error
  95. thisTransporter.(*http.Transport).TLSClientConfig.InsecureSkipVerify = true
  96. }
  97. //TODO: Add user adjustable timeout option here
  98. if dpcOptions.UseH2CRoundTripper {
  99. //Use H2C RoundTripper for HTTP/2.0 connection
  100. thisTransporter = modh2c.NewH2CRoundTripper()
  101. }
  102. return &ReverseProxy{
  103. Director: director,
  104. Prepender: prepender,
  105. FlushInterval: dpcOptions.FlushInterval,
  106. Verbal: false,
  107. Transport: thisTransporter,
  108. }
  109. }
  110. func singleJoiningSlash(a, b string) string {
  111. aslash := strings.HasSuffix(a, "/")
  112. bslash := strings.HasPrefix(b, "/")
  113. switch {
  114. case aslash && bslash:
  115. return a + b[1:]
  116. case !aslash && !bslash:
  117. return a + "/" + b
  118. }
  119. return a + b
  120. }
  121. func joinURLPath(a, b *url.URL) (path, rawpath string) {
  122. if a.RawPath == "" && b.RawPath == "" {
  123. return singleJoiningSlash(a.Path, b.Path), ""
  124. }
  125. // Same as singleJoiningSlash, but uses EscapedPath to determine
  126. // whether a slash should be added
  127. apath := a.EscapedPath()
  128. bpath := b.EscapedPath()
  129. aslash := strings.HasSuffix(apath, "/")
  130. bslash := strings.HasPrefix(bpath, "/")
  131. switch {
  132. case aslash && bslash:
  133. return a.Path + b.Path[1:], apath + bpath[1:]
  134. case !aslash && !bslash:
  135. return a.Path + "/" + b.Path, apath + "/" + bpath
  136. }
  137. return a.Path + b.Path, apath + bpath
  138. }
  139. func copyHeader(dst, src http.Header) {
  140. for k, vv := range src {
  141. for _, v := range vv {
  142. dst.Add(k, v)
  143. }
  144. }
  145. }
  146. // Hop-by-hop headers. These are removed when sent to the backend.
  147. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
  148. var hopHeaders = []string{
  149. //"Connection",
  150. "Proxy-Connection", // non-standard but still sent by libcurl and rejected by e.g. google
  151. "Keep-Alive",
  152. "Proxy-Authenticate",
  153. "Proxy-Authorization",
  154. "Te", // canonicalized version of "TE"
  155. "Trailer", // not Trailers per URL above; http://www.rfc-editor.org/errata_search.php?eid=4522
  156. "Transfer-Encoding",
  157. //"Upgrade", // handled by websocket proxy in higher layer abstraction
  158. }
  159. // Copy response from src to dst with given flush interval, reference from httputil.ReverseProxy
  160. func (p *ReverseProxy) copyResponse(dst http.ResponseWriter, src io.Reader, flushInterval time.Duration) error {
  161. var w io.Writer = dst
  162. if flushInterval != 0 {
  163. mlw := &maxLatencyWriter{
  164. dst: dst,
  165. flush: http.NewResponseController(dst).Flush,
  166. latency: flushInterval,
  167. }
  168. defer mlw.stop()
  169. // set up initial timer so headers get flushed even if body writes are delayed
  170. mlw.flushPending = true
  171. mlw.t = time.AfterFunc(flushInterval, mlw.delayedFlush)
  172. w = mlw
  173. }
  174. var buf []byte
  175. _, err := p.copyBuffer(w, src, buf)
  176. return err
  177. }
  178. // Copy with given buffer size. Default to 64k
  179. func (p *ReverseProxy) copyBuffer(dst io.Writer, src io.Reader, buf []byte) (int64, error) {
  180. if len(buf) == 0 {
  181. buf = make([]byte, 64*1024)
  182. }
  183. var written int64
  184. for {
  185. nr, rerr := src.Read(buf)
  186. if rerr != nil && rerr != io.EOF && rerr != context.Canceled {
  187. p.logf("dpcore read error during body copy: %v", rerr)
  188. }
  189. if nr > 0 {
  190. nw, werr := dst.Write(buf[:nr])
  191. if nw > 0 {
  192. written += int64(nw)
  193. }
  194. if werr != nil {
  195. return written, werr
  196. }
  197. if nr != nw {
  198. return written, io.ErrShortWrite
  199. }
  200. }
  201. if rerr != nil {
  202. if rerr == io.EOF {
  203. rerr = nil
  204. }
  205. return written, rerr
  206. }
  207. }
  208. }
  209. func (p *ReverseProxy) logf(format string, args ...interface{}) {
  210. if p.ErrorLog != nil {
  211. p.ErrorLog.Printf(format, args...)
  212. } else {
  213. log.Printf(format, args...)
  214. }
  215. }
  216. func (p *ReverseProxy) ProxyHTTP(rw http.ResponseWriter, req *http.Request, rrr *ResponseRewriteRuleSet) (int, error) {
  217. transport := p.Transport
  218. outreq := new(http.Request)
  219. // Shallow copies of maps, like header
  220. *outreq = *req
  221. if cn, ok := rw.(http.CloseNotifier); ok {
  222. if requestCanceler, ok := transport.(requestCanceler); ok {
  223. // After the Handler has returned, there is no guarantee
  224. // that the channel receives a value, so to make sure
  225. reqDone := make(chan struct{})
  226. defer close(reqDone)
  227. clientGone := cn.CloseNotify()
  228. go func() {
  229. select {
  230. case <-clientGone:
  231. requestCanceler.CancelRequest(outreq)
  232. case <-reqDone:
  233. }
  234. }()
  235. }
  236. }
  237. p.Director(outreq)
  238. outreq.Close = false
  239. //Only skip origin rewrite iff proxy target require TLS and it is external domain name like github.com
  240. if rrr.HostHeaderOverwrite != "" {
  241. //Use user defined overwrite header value, see issue #255
  242. outreq.Host = rrr.HostHeaderOverwrite
  243. } else if !(rrr.UseTLS && isExternalDomainName(rrr.ProxyDomain)) {
  244. // Always use the original host, see issue #164
  245. outreq.Host = rrr.OriginalHost
  246. }
  247. // We may modify the header (shallow copied above), so we only copy it.
  248. outreq.Header = make(http.Header)
  249. copyHeader(outreq.Header, req.Header)
  250. // Remove hop-by-hop headers.
  251. if !rrr.NoRemoveHopByHop {
  252. removeHeaders(outreq.Header, rrr.NoCache)
  253. }
  254. // Add X-Forwarded-For Header.
  255. addXForwardedForHeader(outreq)
  256. // Add user defined headers (to upstream)
  257. injectUserDefinedHeaders(outreq.Header, rrr.UpstreamHeaders)
  258. // Rewrite outbound UA, must be after user headers
  259. rewriteUserAgent(outreq.Header, "Zoraxy/"+rrr.Version)
  260. //Fix proxmox transfer encoding bug if detected Proxmox Cookie
  261. if domainsniff.IsProxmox(req) {
  262. outreq.TransferEncoding = []string{"identity"}
  263. }
  264. res, err := transport.RoundTrip(outreq)
  265. if err != nil {
  266. if p.Verbal {
  267. p.logf("http: proxy error: %v", err)
  268. }
  269. //rw.WriteHeader(http.StatusBadGateway)
  270. return http.StatusBadGateway, err
  271. }
  272. // Remove hop-by-hop headers listed in the "Connection" header of the response, Remove hop-by-hop headers.
  273. if !rrr.NoRemoveHopByHop {
  274. removeHeaders(res.Header, rrr.NoCache)
  275. }
  276. //Remove the User-Agent header if exists
  277. if _, ok := res.Header["User-Agent"]; ok {
  278. //Server to client request should not contains a User-Agent header
  279. res.Header.Del("User-Agent")
  280. }
  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 http.StatusBadGateway, err
  288. }
  289. }
  290. //Add debug X-Proxy-By tracker
  291. res.Header.Set("x-proxy-by", "zoraxy/"+rrr.Version)
  292. //Custom Location header rewriter functions
  293. if res.Header.Get("Location") != "" {
  294. locationRewrite := res.Header.Get("Location")
  295. originLocation := res.Header.Get("Location")
  296. res.Header.Set("zr-origin-location", originLocation)
  297. if strings.HasPrefix(originLocation, "http://") || strings.HasPrefix(originLocation, "https://") {
  298. //Full path
  299. //Replace the forwarded target with expected Host
  300. lr, err := replaceLocationHost(locationRewrite, rrr, req.TLS != nil)
  301. if err == nil {
  302. locationRewrite = lr
  303. }
  304. } else if strings.HasPrefix(originLocation, "/") && rrr.PathPrefix != "" {
  305. //Back to the root of this proxy object
  306. //fmt.Println(rrr.ProxyDomain, rrr.OriginalHost)
  307. locationRewrite = strings.TrimSuffix(rrr.PathPrefix, "/") + originLocation
  308. } else {
  309. //Relative path. Do not modifiy location header
  310. }
  311. //Custom redirection to this rproxy relative path
  312. res.Header.Set("Location", locationRewrite)
  313. }
  314. // Add user defined headers (to downstream)
  315. injectUserDefinedHeaders(res.Header, rrr.DownstreamHeaders)
  316. // Copy header from response to client.
  317. copyHeader(rw.Header(), res.Header)
  318. // inject permission policy headers
  319. permissionpolicy.InjectPermissionPolicyHeader(rw, nil)
  320. // The "Trailer" header isn't included in the Transport's response, Build it up from Trailer.
  321. if len(res.Trailer) > 0 {
  322. trailerKeys := make([]string, 0, len(res.Trailer))
  323. for k := range res.Trailer {
  324. trailerKeys = append(trailerKeys, k)
  325. }
  326. rw.Header().Add("Trailer", strings.Join(trailerKeys, ", "))
  327. }
  328. rw.WriteHeader(res.StatusCode)
  329. if len(res.Trailer) > 0 {
  330. // Force chunking if we saw a response trailer.
  331. // This prevents net/http from calculating the length for short
  332. // bodies and adding a Content-Length.
  333. if fl, ok := rw.(http.Flusher); ok {
  334. fl.Flush()
  335. }
  336. }
  337. //Get flush interval in real time and start copying the request
  338. flushInterval := p.getFlushInterval(req, res)
  339. p.copyResponse(rw, res.Body, flushInterval)
  340. // close now, instead of defer, to populate res.Trailer
  341. res.Body.Close()
  342. copyHeader(rw.Header(), res.Trailer)
  343. return res.StatusCode, nil
  344. }
  345. func (p *ReverseProxy) ProxyHTTPS(rw http.ResponseWriter, req *http.Request) (int, error) {
  346. hij, ok := rw.(http.Hijacker)
  347. if !ok {
  348. p.logf("http server does not support hijacker")
  349. return http.StatusNotImplemented, errors.New("http server does not support hijacker")
  350. }
  351. clientConn, _, err := hij.Hijack()
  352. if err != nil {
  353. if p.Verbal {
  354. p.logf("http: proxy error: %v", err)
  355. }
  356. return http.StatusInternalServerError, err
  357. }
  358. proxyConn, err := net.Dial("tcp", req.URL.Host)
  359. if err != nil {
  360. if p.Verbal {
  361. p.logf("http: proxy error: %v", err)
  362. }
  363. return http.StatusInternalServerError, err
  364. }
  365. // The returned net.Conn may have read or write deadlines
  366. // already set, depending on the configuration of the
  367. // Server, to set or clear those deadlines as needed
  368. // we set timeout to 5 minutes
  369. deadline := time.Now()
  370. if p.Timeout == 0 {
  371. deadline = deadline.Add(time.Minute * 5)
  372. } else {
  373. deadline = deadline.Add(p.Timeout)
  374. }
  375. err = clientConn.SetDeadline(deadline)
  376. if err != nil {
  377. if p.Verbal {
  378. p.logf("http: proxy error: %v", err)
  379. }
  380. return http.StatusGatewayTimeout, err
  381. }
  382. err = proxyConn.SetDeadline(deadline)
  383. if err != nil {
  384. if p.Verbal {
  385. p.logf("http: proxy error: %v", err)
  386. }
  387. return http.StatusGatewayTimeout, err
  388. }
  389. _, err = clientConn.Write([]byte("HTTP/1.0 200 OK\r\n\r\n"))
  390. if err != nil {
  391. if p.Verbal {
  392. p.logf("http: proxy error: %v", err)
  393. }
  394. return http.StatusInternalServerError, err
  395. }
  396. go func() {
  397. io.Copy(clientConn, proxyConn)
  398. clientConn.Close()
  399. proxyConn.Close()
  400. }()
  401. io.Copy(proxyConn, clientConn)
  402. proxyConn.Close()
  403. clientConn.Close()
  404. return http.StatusOK, nil
  405. }
  406. func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request, rrr *ResponseRewriteRuleSet) (int, error) {
  407. if req.Method == "CONNECT" {
  408. return p.ProxyHTTPS(rw, req)
  409. } else {
  410. return p.ProxyHTTP(rw, req, rrr)
  411. }
  412. }