websocketproxy.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. // Package websocketproxy is a reverse proxy for WebSocket connections.
  2. package websocketproxy
  3. import (
  4. "fmt"
  5. "io"
  6. "log"
  7. "net"
  8. "net/http"
  9. "net/url"
  10. "strings"
  11. "github.com/gorilla/websocket"
  12. )
  13. var (
  14. // DefaultUpgrader specifies the parameters for upgrading an HTTP
  15. // connection to a WebSocket connection.
  16. DefaultUpgrader = &websocket.Upgrader{
  17. ReadBufferSize: 1024,
  18. WriteBufferSize: 1024,
  19. }
  20. // DefaultDialer is a dialer with all fields set to the default zero values.
  21. DefaultDialer = websocket.DefaultDialer
  22. )
  23. // WebsocketProxy is an HTTP Handler that takes an incoming WebSocket
  24. // connection and proxies it to another server.
  25. type WebsocketProxy struct {
  26. // Director, if non-nil, is a function that may copy additional request
  27. // headers from the incoming WebSocket connection into the output headers
  28. // which will be forwarded to another server.
  29. Director func(incoming *http.Request, out http.Header)
  30. // Backend returns the backend URL which the proxy uses to reverse proxy
  31. // the incoming WebSocket connection. Request is the initial incoming and
  32. // unmodified request.
  33. Backend func(*http.Request) *url.URL
  34. // Upgrader specifies the parameters for upgrading a incoming HTTP
  35. // connection to a WebSocket connection. If nil, DefaultUpgrader is used.
  36. Upgrader *websocket.Upgrader
  37. // Dialer contains options for connecting to the backend WebSocket server.
  38. // If nil, DefaultDialer is used.
  39. Dialer *websocket.Dialer
  40. }
  41. // ProxyHandler returns a new http.Handler interface that reverse proxies the
  42. // request to the given target.
  43. func ProxyHandler(target *url.URL) http.Handler { return NewProxy(target) }
  44. // NewProxy returns a new Websocket reverse proxy that rewrites the
  45. // URL's to the scheme, host and base path provider in target.
  46. func NewProxy(target *url.URL) *WebsocketProxy {
  47. backend := func(r *http.Request) *url.URL {
  48. // Shallow copy
  49. u := *target
  50. u.Fragment = r.URL.Fragment
  51. u.Path = r.URL.Path
  52. u.RawQuery = r.URL.RawQuery
  53. return &u
  54. }
  55. return &WebsocketProxy{Backend: backend}
  56. }
  57. // ServeHTTP implements the http.Handler that proxies WebSocket connections.
  58. func (w *WebsocketProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
  59. if w.Backend == nil {
  60. log.Println("websocketproxy: backend function is not defined")
  61. http.Error(rw, "internal server error (code: 1)", http.StatusInternalServerError)
  62. return
  63. }
  64. backendURL := w.Backend(req)
  65. if backendURL == nil {
  66. log.Println("websocketproxy: backend URL is nil")
  67. http.Error(rw, "internal server error (code: 2)", http.StatusInternalServerError)
  68. return
  69. }
  70. dialer := w.Dialer
  71. if w.Dialer == nil {
  72. dialer = DefaultDialer
  73. }
  74. // Pass headers from the incoming request to the dialer to forward them to
  75. // the final destinations.
  76. requestHeader := http.Header{}
  77. if origin := req.Header.Get("Origin"); origin != "" {
  78. requestHeader.Add("Origin", origin)
  79. }
  80. for _, prot := range req.Header[http.CanonicalHeaderKey("Sec-WebSocket-Protocol")] {
  81. requestHeader.Add("Sec-WebSocket-Protocol", prot)
  82. }
  83. for _, cookie := range req.Header[http.CanonicalHeaderKey("Cookie")] {
  84. requestHeader.Add("Cookie", cookie)
  85. }
  86. if req.Host != "" {
  87. requestHeader.Set("Host", req.Host)
  88. }
  89. // Pass X-Forwarded-For headers too, code below is a part of
  90. // httputil.ReverseProxy. See http://en.wikipedia.org/wiki/X-Forwarded-For
  91. // for more information
  92. // TODO: use RFC7239 http://tools.ietf.org/html/rfc7239
  93. if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
  94. // If we aren't the first proxy retain prior
  95. // X-Forwarded-For information as a comma+space
  96. // separated list and fold multiple headers into one.
  97. if prior, ok := req.Header["X-Forwarded-For"]; ok {
  98. clientIP = strings.Join(prior, ", ") + ", " + clientIP
  99. }
  100. requestHeader.Set("X-Forwarded-For", clientIP)
  101. }
  102. // Set the originating protocol of the incoming HTTP request. The SSL might
  103. // be terminated on our site and because we doing proxy adding this would
  104. // be helpful for applications on the backend.
  105. requestHeader.Set("X-Forwarded-Proto", "http")
  106. if req.TLS != nil {
  107. requestHeader.Set("X-Forwarded-Proto", "https")
  108. }
  109. // Enable the director to copy any additional headers it desires for
  110. // forwarding to the remote server.
  111. if w.Director != nil {
  112. w.Director(req, requestHeader)
  113. }
  114. // Connect to the backend URL, also pass the headers we get from the requst
  115. // together with the Forwarded headers we prepared above.
  116. // TODO: support multiplexing on the same backend connection instead of
  117. // opening a new TCP connection time for each request. This should be
  118. // optional:
  119. // http://tools.ietf.org/html/draft-ietf-hybi-websocket-multiplexing-01
  120. connBackend, resp, err := dialer.Dial(backendURL.String(), requestHeader)
  121. if err != nil {
  122. log.Printf("websocketproxy: couldn't dial to remote backend url %s", err)
  123. if resp != nil {
  124. // If the WebSocket handshake fails, ErrBadHandshake is returned
  125. // along with a non-nil *http.Response so that callers can handle
  126. // redirects, authentication, etcetera.
  127. if err := copyResponse(rw, resp); err != nil {
  128. log.Printf("websocketproxy: couldn't write response after failed remote backend handshake: %s", err)
  129. }
  130. } else {
  131. http.Error(rw, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
  132. }
  133. return
  134. }
  135. defer connBackend.Close()
  136. upgrader := w.Upgrader
  137. if w.Upgrader == nil {
  138. upgrader = DefaultUpgrader
  139. }
  140. // Only pass those headers to the upgrader.
  141. upgradeHeader := http.Header{}
  142. if hdr := resp.Header.Get("Sec-Websocket-Protocol"); hdr != "" {
  143. upgradeHeader.Set("Sec-Websocket-Protocol", hdr)
  144. }
  145. if hdr := resp.Header.Get("Set-Cookie"); hdr != "" {
  146. upgradeHeader.Set("Set-Cookie", hdr)
  147. }
  148. // Now upgrade the existing incoming request to a WebSocket connection.
  149. // Also pass the header that we gathered from the Dial handshake.
  150. upgrader.CheckOrigin = func(r *http.Request) bool { return true }
  151. connPub, err := upgrader.Upgrade(rw, req, upgradeHeader)
  152. if err != nil {
  153. log.Printf("websocketproxy: couldn't upgrade %s", err)
  154. return
  155. }
  156. defer connPub.Close()
  157. errClient := make(chan error, 1)
  158. errBackend := make(chan error, 1)
  159. replicateWebsocketConn := func(dst, src *websocket.Conn, errc chan error) {
  160. for {
  161. msgType, msg, err := src.ReadMessage()
  162. if err != nil {
  163. m := websocket.FormatCloseMessage(websocket.CloseNormalClosure, fmt.Sprintf("%v", err))
  164. if e, ok := err.(*websocket.CloseError); ok {
  165. if e.Code != websocket.CloseNoStatusReceived {
  166. m = websocket.FormatCloseMessage(e.Code, e.Text)
  167. }
  168. }
  169. errc <- err
  170. dst.WriteMessage(websocket.CloseMessage, m)
  171. break
  172. }
  173. err = dst.WriteMessage(msgType, msg)
  174. if err != nil {
  175. errc <- err
  176. break
  177. }
  178. }
  179. }
  180. go replicateWebsocketConn(connPub, connBackend, errClient)
  181. go replicateWebsocketConn(connBackend, connPub, errBackend)
  182. var message string
  183. select {
  184. case err = <-errClient:
  185. message = "websocketproxy: Error when copying from backend to client: %v"
  186. case err = <-errBackend:
  187. message = "websocketproxy: Error when copying from client to backend: %v"
  188. }
  189. if e, ok := err.(*websocket.CloseError); !ok || e.Code == websocket.CloseAbnormalClosure {
  190. log.Printf(message, err)
  191. }
  192. }
  193. func copyHeader(dst, src http.Header) {
  194. for k, vv := range src {
  195. for _, v := range vv {
  196. dst.Add(k, v)
  197. }
  198. }
  199. }
  200. func copyResponse(rw http.ResponseWriter, resp *http.Response) error {
  201. copyHeader(rw.Header(), resp.Header)
  202. rw.WriteHeader(resp.StatusCode)
  203. defer resp.Body.Close()
  204. _, err := io.Copy(rw, resp.Body)
  205. return err
  206. }