dpcore.go 14 KB

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