dpcore.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. package dpcore
  2. import (
  3. "errors"
  4. "io"
  5. "log"
  6. "net"
  7. "net/http"
  8. "net/url"
  9. "strings"
  10. "sync"
  11. "time"
  12. )
  13. var onExitFlushLoop func()
  14. const (
  15. defaultTimeout = time.Minute * 5
  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. //
  48. Prepender string
  49. Verbal bool
  50. }
  51. type ResponseRewriteRuleSet struct {
  52. ProxyDomain string
  53. OriginalHost string
  54. UseTLS bool
  55. PathPrefix string //Vdir prefix for root, / will be rewrite to this
  56. }
  57. type requestCanceler interface {
  58. CancelRequest(req *http.Request)
  59. }
  60. func NewDynamicProxyCore(target *url.URL, prepender string) *ReverseProxy {
  61. targetQuery := target.RawQuery
  62. director := func(req *http.Request) {
  63. req.URL.Scheme = target.Scheme
  64. req.URL.Host = target.Host
  65. req.URL.Path, req.URL.RawPath = joinURLPath(target, req.URL)
  66. if targetQuery == "" || req.URL.RawQuery == "" {
  67. req.URL.RawQuery = targetQuery + req.URL.RawQuery
  68. } else {
  69. req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
  70. }
  71. if _, ok := req.Header["User-Agent"]; !ok {
  72. req.Header.Set("User-Agent", "")
  73. }
  74. }
  75. return &ReverseProxy{
  76. Director: director,
  77. Prepender: prepender,
  78. Verbal: false,
  79. }
  80. }
  81. func singleJoiningSlash(a, b string) string {
  82. aslash := strings.HasSuffix(a, "/")
  83. bslash := strings.HasPrefix(b, "/")
  84. switch {
  85. case aslash && bslash:
  86. return a + b[1:]
  87. case !aslash && !bslash:
  88. return a + "/" + b
  89. }
  90. return a + b
  91. }
  92. func joinURLPath(a, b *url.URL) (path, rawpath string) {
  93. if a.RawPath == "" && b.RawPath == "" {
  94. return singleJoiningSlash(a.Path, b.Path), ""
  95. }
  96. // Same as singleJoiningSlash, but uses EscapedPath to determine
  97. // whether a slash should be added
  98. apath := a.EscapedPath()
  99. bpath := b.EscapedPath()
  100. aslash := strings.HasSuffix(apath, "/")
  101. bslash := strings.HasPrefix(bpath, "/")
  102. switch {
  103. case aslash && bslash:
  104. return a.Path + b.Path[1:], apath + bpath[1:]
  105. case !aslash && !bslash:
  106. return a.Path + "/" + b.Path, apath + "/" + bpath
  107. }
  108. return a.Path + b.Path, apath + bpath
  109. }
  110. func copyHeader(dst, src http.Header) {
  111. for k, vv := range src {
  112. for _, v := range vv {
  113. dst.Add(k, v)
  114. }
  115. }
  116. }
  117. // Hop-by-hop headers. These are removed when sent to the backend.
  118. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
  119. var hopHeaders = []string{
  120. //"Connection",
  121. "Proxy-Connection", // non-standard but still sent by libcurl and rejected by e.g. google
  122. "Keep-Alive",
  123. "Proxy-Authenticate",
  124. "Proxy-Authorization",
  125. "Te", // canonicalized version of "TE"
  126. "Trailer", // not Trailers per URL above; http://www.rfc-editor.org/errata_search.php?eid=4522
  127. "Transfer-Encoding",
  128. //"Upgrade",
  129. }
  130. func (p *ReverseProxy) copyResponse(dst io.Writer, src io.Reader) {
  131. if p.FlushInterval != 0 {
  132. if wf, ok := dst.(writeFlusher); ok {
  133. mlw := &maxLatencyWriter{
  134. dst: wf,
  135. latency: p.FlushInterval,
  136. done: make(chan bool),
  137. }
  138. go mlw.flushLoop()
  139. defer mlw.stop()
  140. dst = mlw
  141. }
  142. }
  143. io.Copy(dst, src)
  144. }
  145. type writeFlusher interface {
  146. io.Writer
  147. http.Flusher
  148. }
  149. type maxLatencyWriter struct {
  150. dst writeFlusher
  151. latency time.Duration
  152. mu sync.Mutex
  153. done chan bool
  154. }
  155. func (m *maxLatencyWriter) Write(b []byte) (int, error) {
  156. m.mu.Lock()
  157. defer m.mu.Unlock()
  158. return m.dst.Write(b)
  159. }
  160. func (m *maxLatencyWriter) flushLoop() {
  161. t := time.NewTicker(m.latency)
  162. defer t.Stop()
  163. for {
  164. select {
  165. case <-m.done:
  166. if onExitFlushLoop != nil {
  167. onExitFlushLoop()
  168. }
  169. return
  170. case <-t.C:
  171. m.mu.Lock()
  172. m.dst.Flush()
  173. m.mu.Unlock()
  174. }
  175. }
  176. }
  177. func (m *maxLatencyWriter) stop() {
  178. m.done <- true
  179. }
  180. func (p *ReverseProxy) logf(format string, args ...interface{}) {
  181. if p.ErrorLog != nil {
  182. p.ErrorLog.Printf(format, args...)
  183. } else {
  184. log.Printf(format, args...)
  185. }
  186. }
  187. func removeHeaders(header http.Header) {
  188. // Remove hop-by-hop headers listed in the "Connection" header.
  189. if c := header.Get("Connection"); c != "" {
  190. for _, f := range strings.Split(c, ",") {
  191. if f = strings.TrimSpace(f); f != "" {
  192. header.Del(f)
  193. }
  194. }
  195. }
  196. // Remove hop-by-hop headers
  197. for _, h := range hopHeaders {
  198. if header.Get(h) != "" {
  199. header.Del(h)
  200. }
  201. }
  202. if header.Get("A-Upgrade") != "" {
  203. header.Set("Upgrade", header.Get("A-Upgrade"))
  204. header.Del("A-Upgrade")
  205. }
  206. }
  207. func addXForwardedForHeader(req *http.Request) {
  208. if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
  209. // If we aren't the first proxy retain prior
  210. // X-Forwarded-For information as a comma+space
  211. // separated list and fold multiple headers into one.
  212. if prior, ok := req.Header["X-Forwarded-For"]; ok {
  213. clientIP = strings.Join(prior, ", ") + ", " + clientIP
  214. }
  215. req.Header.Set("X-Forwarded-For", clientIP)
  216. }
  217. }
  218. func (p *ReverseProxy) ProxyHTTP(rw http.ResponseWriter, req *http.Request, rrr *ResponseRewriteRuleSet) error {
  219. transport := p.Transport
  220. if transport == nil {
  221. transport = http.DefaultTransport
  222. }
  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. outreq.Host = rrr.OriginalHost
  245. // We may modify the header (shallow copied above), so we only copy it.
  246. outreq.Header = make(http.Header)
  247. copyHeader(outreq.Header, req.Header)
  248. // Remove hop-by-hop headers listed in the "Connection" header, Remove hop-by-hop headers.
  249. removeHeaders(outreq.Header)
  250. // Add X-Forwarded-For Header.
  251. addXForwardedForHeader(outreq)
  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. removeHeaders(res.Header)
  262. if p.ModifyResponse != nil {
  263. if err := p.ModifyResponse(res); err != nil {
  264. if p.Verbal {
  265. p.logf("http: proxy error: %v", err)
  266. }
  267. //rw.WriteHeader(http.StatusBadGateway)
  268. return err
  269. }
  270. }
  271. //Custom header rewriter functions
  272. if res.Header.Get("Location") != "" {
  273. /*
  274. fmt.Println(">>> REQ", req)
  275. fmt.Println(">>> OUTR", outreq)
  276. fmt.Println(">>> RESP", res)
  277. */
  278. locationRewrite := res.Header.Get("Location")
  279. originLocation := res.Header.Get("Location")
  280. res.Header.Set("zr-origin-location", originLocation)
  281. if strings.HasPrefix(originLocation, "http://") || strings.HasPrefix(originLocation, "https://") {
  282. //Full path
  283. //Replace the forwarded target with expected Host
  284. lr, err := replaceLocationHost(locationRewrite, rrr.OriginalHost, req.TLS != nil)
  285. if err == nil {
  286. locationRewrite = lr
  287. }
  288. //locationRewrite = strings.ReplaceAll(locationRewrite, rrr.ProxyDomain, rrr.OriginalHost)
  289. //locationRewrite = strings.ReplaceAll(locationRewrite, domainWithoutPort, rrr.OriginalHost)
  290. } else if strings.HasPrefix(originLocation, "/") && rrr.PathPrefix != "" {
  291. //Back to the root of this proxy object
  292. //fmt.Println(rrr.ProxyDomain, domainWithoutPort, rrr.OriginalHost)
  293. locationRewrite = strings.TrimSuffix(rrr.PathPrefix, "/") + originLocation
  294. } else {
  295. //Relative path. Do not modifiy location header
  296. }
  297. //Custom redirection to this rproxy relative path
  298. res.Header.Set("Location", locationRewrite)
  299. }
  300. // Copy header from response to client.
  301. copyHeader(rw.Header(), res.Header)
  302. // The "Trailer" header isn't included in the Transport's response, Build it up from Trailer.
  303. if len(res.Trailer) > 0 {
  304. trailerKeys := make([]string, 0, len(res.Trailer))
  305. for k := range res.Trailer {
  306. trailerKeys = append(trailerKeys, k)
  307. }
  308. rw.Header().Add("Trailer", strings.Join(trailerKeys, ", "))
  309. }
  310. rw.WriteHeader(res.StatusCode)
  311. if len(res.Trailer) > 0 {
  312. // Force chunking if we saw a response trailer.
  313. // This prevents net/http from calculating the length for short
  314. // bodies and adding a Content-Length.
  315. if fl, ok := rw.(http.Flusher); ok {
  316. fl.Flush()
  317. }
  318. }
  319. p.copyResponse(rw, res.Body)
  320. // close now, instead of defer, to populate res.Trailer
  321. res.Body.Close()
  322. copyHeader(rw.Header(), res.Trailer)
  323. return nil
  324. }
  325. func (p *ReverseProxy) ProxyHTTPS(rw http.ResponseWriter, req *http.Request) error {
  326. hij, ok := rw.(http.Hijacker)
  327. if !ok {
  328. p.logf("http server does not support hijacker")
  329. return errors.New("http server does not support hijacker")
  330. }
  331. clientConn, _, err := hij.Hijack()
  332. if err != nil {
  333. if p.Verbal {
  334. p.logf("http: proxy error: %v", err)
  335. }
  336. return err
  337. }
  338. proxyConn, err := net.Dial("tcp", req.URL.Host)
  339. if err != nil {
  340. if p.Verbal {
  341. p.logf("http: proxy error: %v", err)
  342. }
  343. return err
  344. }
  345. // The returned net.Conn may have read or write deadlines
  346. // already set, depending on the configuration of the
  347. // Server, to set or clear those deadlines as needed
  348. // we set timeout to 5 minutes
  349. deadline := time.Now()
  350. if p.Timeout == 0 {
  351. deadline = deadline.Add(time.Minute * 5)
  352. } else {
  353. deadline = deadline.Add(p.Timeout)
  354. }
  355. err = clientConn.SetDeadline(deadline)
  356. if err != nil {
  357. if p.Verbal {
  358. p.logf("http: proxy error: %v", err)
  359. }
  360. return err
  361. }
  362. err = proxyConn.SetDeadline(deadline)
  363. if err != nil {
  364. if p.Verbal {
  365. p.logf("http: proxy error: %v", err)
  366. }
  367. return err
  368. }
  369. _, err = clientConn.Write([]byte("HTTP/1.0 200 OK\r\n\r\n"))
  370. if err != nil {
  371. if p.Verbal {
  372. p.logf("http: proxy error: %v", err)
  373. }
  374. return err
  375. }
  376. go func() {
  377. io.Copy(clientConn, proxyConn)
  378. clientConn.Close()
  379. proxyConn.Close()
  380. }()
  381. io.Copy(proxyConn, clientConn)
  382. proxyConn.Close()
  383. clientConn.Close()
  384. return nil
  385. }
  386. func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request, rrr *ResponseRewriteRuleSet) error {
  387. if req.Method == "CONNECT" {
  388. err := p.ProxyHTTPS(rw, req)
  389. return err
  390. } else {
  391. err := p.ProxyHTTP(rw, req, rrr)
  392. return err
  393. }
  394. }