dpcore.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. package dpcore
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "log"
  7. "net"
  8. "net/http"
  9. "net/url"
  10. "strings"
  11. "sync"
  12. "time"
  13. )
  14. var onExitFlushLoop func()
  15. const (
  16. defaultTimeout = time.Minute * 5
  17. )
  18. // ReverseProxy is an HTTP Handler that takes an incoming request and
  19. // sends it to another server, proxying the response back to the
  20. // client, support http, also support https tunnel using http.hijacker
  21. type ReverseProxy struct {
  22. // Set the timeout of the proxy server, default is 5 minutes
  23. Timeout time.Duration
  24. // Director must be a function which modifies
  25. // the request into a new request to be sent
  26. // using Transport. Its response is then copied
  27. // back to the original client unmodified.
  28. // Director must not access the provided Request
  29. // after returning.
  30. Director func(*http.Request)
  31. // The transport used to perform proxy requests.
  32. // default is http.DefaultTransport.
  33. Transport http.RoundTripper
  34. // FlushInterval specifies the flush interval
  35. // to flush to the client while copying the
  36. // response body. If zero, no periodic flushing is done.
  37. FlushInterval time.Duration
  38. // ErrorLog specifies an optional logger for errors
  39. // that occur when attempting to proxy the request.
  40. // If nil, logging goes to os.Stderr via the log package's
  41. // standard logger.
  42. ErrorLog *log.Logger
  43. // ModifyResponse is an optional function that
  44. // modifies the Response from the backend.
  45. // If it returns an error, the proxy returns a StatusBadGateway error.
  46. ModifyResponse func(*http.Response) error
  47. //Prepender is an optional prepend text for URL rewrite
  48. //
  49. Prepender string
  50. Verbal bool
  51. }
  52. type ResponseRewriteRuleSet struct {
  53. ProxyDomain string
  54. OriginalHost string
  55. }
  56. type requestCanceler interface {
  57. CancelRequest(req *http.Request)
  58. }
  59. func NewDynamicProxyCore(target *url.URL, prepender string) *ReverseProxy {
  60. //targetQuery := target.RawQuery
  61. director := func(req *http.Request) {
  62. fmt.Println(target.Host, target.Path, req.URL.Path)
  63. /*
  64. req.URL.Scheme = target.Scheme
  65. req.URL.Host = target.Host
  66. req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
  67. // If Host is empty, the Request.Write method uses
  68. // the value of URL.Host.
  69. // force use URL.Host
  70. req.Host = req.URL.Host
  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. if _, ok := req.Header["User-Agent"]; !ok {
  77. req.Header.Set("User-Agent", "")
  78. }
  79. */
  80. }
  81. return &ReverseProxy{
  82. Director: director,
  83. Prepender: prepender,
  84. Verbal: false,
  85. }
  86. }
  87. func singleJoiningSlash(a, b string) string {
  88. aslash := strings.HasSuffix(a, "/")
  89. bslash := strings.HasPrefix(b, "/")
  90. switch {
  91. case aslash && bslash:
  92. return a + b[1:]
  93. case !aslash && !bslash:
  94. return a + "/" + b
  95. }
  96. return a + b
  97. }
  98. func copyHeader(dst, src http.Header) {
  99. for k, vv := range src {
  100. for _, v := range vv {
  101. dst.Add(k, v)
  102. }
  103. }
  104. }
  105. // Hop-by-hop headers. These are removed when sent to the backend.
  106. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
  107. var hopHeaders = []string{
  108. //"Connection",
  109. "Proxy-Connection", // non-standard but still sent by libcurl and rejected by e.g. google
  110. "Keep-Alive",
  111. "Proxy-Authenticate",
  112. "Proxy-Authorization",
  113. "Te", // canonicalized version of "TE"
  114. "Trailer", // not Trailers per URL above; http://www.rfc-editor.org/errata_search.php?eid=4522
  115. "Transfer-Encoding",
  116. //"Upgrade",
  117. }
  118. func (p *ReverseProxy) copyResponse(dst io.Writer, src io.Reader) {
  119. if p.FlushInterval != 0 {
  120. if wf, ok := dst.(writeFlusher); ok {
  121. mlw := &maxLatencyWriter{
  122. dst: wf,
  123. latency: p.FlushInterval,
  124. done: make(chan bool),
  125. }
  126. go mlw.flushLoop()
  127. defer mlw.stop()
  128. dst = mlw
  129. }
  130. }
  131. io.Copy(dst, src)
  132. }
  133. type writeFlusher interface {
  134. io.Writer
  135. http.Flusher
  136. }
  137. type maxLatencyWriter struct {
  138. dst writeFlusher
  139. latency time.Duration
  140. mu sync.Mutex
  141. done chan bool
  142. }
  143. func (m *maxLatencyWriter) Write(b []byte) (int, error) {
  144. m.mu.Lock()
  145. defer m.mu.Unlock()
  146. return m.dst.Write(b)
  147. }
  148. func (m *maxLatencyWriter) flushLoop() {
  149. t := time.NewTicker(m.latency)
  150. defer t.Stop()
  151. for {
  152. select {
  153. case <-m.done:
  154. if onExitFlushLoop != nil {
  155. onExitFlushLoop()
  156. }
  157. return
  158. case <-t.C:
  159. m.mu.Lock()
  160. m.dst.Flush()
  161. m.mu.Unlock()
  162. }
  163. }
  164. }
  165. func (m *maxLatencyWriter) stop() {
  166. m.done <- true
  167. }
  168. func (p *ReverseProxy) logf(format string, args ...interface{}) {
  169. if p.ErrorLog != nil {
  170. p.ErrorLog.Printf(format, args...)
  171. } else {
  172. log.Printf(format, args...)
  173. }
  174. }
  175. func removeHeaders(header http.Header) {
  176. // Remove hop-by-hop headers listed in the "Connection" header.
  177. if c := header.Get("Connection"); c != "" {
  178. for _, f := range strings.Split(c, ",") {
  179. if f = strings.TrimSpace(f); f != "" {
  180. header.Del(f)
  181. }
  182. }
  183. }
  184. // Remove hop-by-hop headers
  185. for _, h := range hopHeaders {
  186. if header.Get(h) != "" {
  187. header.Del(h)
  188. }
  189. }
  190. if header.Get("A-Upgrade") != "" {
  191. header.Set("Upgrade", header.Get("A-Upgrade"))
  192. header.Del("A-Upgrade")
  193. }
  194. }
  195. func addXForwardedForHeader(req *http.Request) {
  196. if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
  197. // If we aren't the first proxy retain prior
  198. // X-Forwarded-For information as a comma+space
  199. // separated list and fold multiple headers into one.
  200. if prior, ok := req.Header["X-Forwarded-For"]; ok {
  201. clientIP = strings.Join(prior, ", ") + ", " + clientIP
  202. }
  203. req.Header.Set("X-Forwarded-For", clientIP)
  204. }
  205. }
  206. func (p *ReverseProxy) ProxyHTTP(rw http.ResponseWriter, req *http.Request, rrr *ResponseRewriteRuleSet) error {
  207. transport := p.Transport
  208. if transport == nil {
  209. transport = http.DefaultTransport
  210. }
  211. outreq := new(http.Request)
  212. // Shallow copies of maps, like header
  213. *outreq = *req
  214. if cn, ok := rw.(http.CloseNotifier); ok {
  215. if requestCanceler, ok := transport.(requestCanceler); ok {
  216. // After the Handler has returned, there is no guarantee
  217. // that the channel receives a value, so to make sure
  218. reqDone := make(chan struct{})
  219. defer close(reqDone)
  220. clientGone := cn.CloseNotify()
  221. go func() {
  222. select {
  223. case <-clientGone:
  224. requestCanceler.CancelRequest(outreq)
  225. case <-reqDone:
  226. }
  227. }()
  228. }
  229. }
  230. fmt.Println("CHECKPOINT1", req.URL)
  231. p.Director(outreq)
  232. outreq.Close = false
  233. fmt.Println("CHECKPOINT2", req.URL)
  234. // We may modify the header (shallow copied above), so we only copy it.
  235. outreq.Header = make(http.Header)
  236. copyHeader(outreq.Header, req.Header)
  237. fmt.Println("CHECKPOINT3", req.URL)
  238. // Remove hop-by-hop headers listed in the "Connection" header, Remove hop-by-hop headers.
  239. removeHeaders(outreq.Header)
  240. fmt.Println("CHECKPOINT4", req.URL)
  241. // Add X-Forwarded-For Header.
  242. addXForwardedForHeader(outreq)
  243. fmt.Println("CHECKPOINT5", req.URL)
  244. res, err := transport.RoundTrip(outreq)
  245. if err != nil {
  246. if p.Verbal {
  247. p.logf("http: proxy error: %v", err)
  248. }
  249. //rw.WriteHeader(http.StatusBadGateway)
  250. return err
  251. }
  252. // Remove hop-by-hop headers listed in the "Connection" header of the response, Remove hop-by-hop headers.
  253. removeHeaders(res.Header)
  254. if p.ModifyResponse != nil {
  255. if err := p.ModifyResponse(res); err != nil {
  256. if p.Verbal {
  257. p.logf("http: proxy error: %v", err)
  258. }
  259. //rw.WriteHeader(http.StatusBadGateway)
  260. return err
  261. }
  262. }
  263. //Custom header rewriter functions
  264. if res.Header.Get("Location") != "" {
  265. fmt.Println(">>> REQ", req)
  266. fmt.Println(">>> OUTR", outreq)
  267. fmt.Println(">>> RESP", res)
  268. locationRewrite := res.Header.Get("Location")
  269. originLocation := res.Header.Get("Location")
  270. res.Header.Set("zr-origin-location", originLocation)
  271. domainWithoutPort := rrr.ProxyDomain
  272. if strings.Contains(rrr.ProxyDomain, ":") {
  273. //Split the port away
  274. domainWithoutPort = strings.Split(rrr.ProxyDomain, ":")[0]
  275. }
  276. //Replace the forwarded target with expected Host
  277. locationRewrite = strings.ReplaceAll(locationRewrite, rrr.ProxyDomain, rrr.OriginalHost)
  278. locationRewrite = strings.ReplaceAll(locationRewrite, domainWithoutPort, rrr.OriginalHost)
  279. //Custom redirection to this rproxy relative path
  280. res.Header.Set("Location", locationRewrite)
  281. }
  282. // Copy header from response to client.
  283. copyHeader(rw.Header(), res.Header)
  284. // The "Trailer" header isn't included in the Transport's response, Build it up from Trailer.
  285. if len(res.Trailer) > 0 {
  286. trailerKeys := make([]string, 0, len(res.Trailer))
  287. for k := range res.Trailer {
  288. trailerKeys = append(trailerKeys, k)
  289. }
  290. rw.Header().Add("Trailer", strings.Join(trailerKeys, ", "))
  291. }
  292. rw.WriteHeader(res.StatusCode)
  293. if len(res.Trailer) > 0 {
  294. // Force chunking if we saw a response trailer.
  295. // This prevents net/http from calculating the length for short
  296. // bodies and adding a Content-Length.
  297. if fl, ok := rw.(http.Flusher); ok {
  298. fl.Flush()
  299. }
  300. }
  301. p.copyResponse(rw, res.Body)
  302. // close now, instead of defer, to populate res.Trailer
  303. res.Body.Close()
  304. copyHeader(rw.Header(), res.Trailer)
  305. return nil
  306. }
  307. func (p *ReverseProxy) ProxyHTTPS(rw http.ResponseWriter, req *http.Request) error {
  308. hij, ok := rw.(http.Hijacker)
  309. if !ok {
  310. p.logf("http server does not support hijacker")
  311. return errors.New("http server does not support hijacker")
  312. }
  313. clientConn, _, err := hij.Hijack()
  314. if err != nil {
  315. if p.Verbal {
  316. p.logf("http: proxy error: %v", err)
  317. }
  318. return err
  319. }
  320. proxyConn, err := net.Dial("tcp", req.URL.Host)
  321. if err != nil {
  322. if p.Verbal {
  323. p.logf("http: proxy error: %v", err)
  324. }
  325. return err
  326. }
  327. // The returned net.Conn may have read or write deadlines
  328. // already set, depending on the configuration of the
  329. // Server, to set or clear those deadlines as needed
  330. // we set timeout to 5 minutes
  331. deadline := time.Now()
  332. if p.Timeout == 0 {
  333. deadline = deadline.Add(time.Minute * 5)
  334. } else {
  335. deadline = deadline.Add(p.Timeout)
  336. }
  337. err = clientConn.SetDeadline(deadline)
  338. if err != nil {
  339. if p.Verbal {
  340. p.logf("http: proxy error: %v", err)
  341. }
  342. return err
  343. }
  344. err = proxyConn.SetDeadline(deadline)
  345. if err != nil {
  346. if p.Verbal {
  347. p.logf("http: proxy error: %v", err)
  348. }
  349. return err
  350. }
  351. _, err = clientConn.Write([]byte("HTTP/1.0 200 OK\r\n\r\n"))
  352. if err != nil {
  353. if p.Verbal {
  354. p.logf("http: proxy error: %v", err)
  355. }
  356. return err
  357. }
  358. go func() {
  359. io.Copy(clientConn, proxyConn)
  360. clientConn.Close()
  361. proxyConn.Close()
  362. }()
  363. io.Copy(proxyConn, clientConn)
  364. proxyConn.Close()
  365. clientConn.Close()
  366. return nil
  367. }
  368. func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request, rrr *ResponseRewriteRuleSet) error {
  369. if req.Method == "CONNECT" {
  370. err := p.ProxyHTTPS(rw, req)
  371. return err
  372. } else {
  373. err := p.ProxyHTTP(rw, req, rrr)
  374. return err
  375. }
  376. }