dpcore.go 9.4 KB

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