dpcore.go 13 KB

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