dpcore.go 13 KB

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