websocketproxy.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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. Verbal bool
  41. }
  42. // ProxyHandler returns a new http.Handler interface that reverse proxies the
  43. // request to the given target.
  44. func ProxyHandler(target *url.URL) http.Handler { return NewProxy(target) }
  45. // NewProxy returns a new Websocket reverse proxy that rewrites the
  46. // URL's to the scheme, host and base path provider in target.
  47. func NewProxy(target *url.URL) *WebsocketProxy {
  48. backend := func(r *http.Request) *url.URL {
  49. // Shallow copy
  50. u := *target
  51. u.Fragment = r.URL.Fragment
  52. u.Path = r.URL.Path
  53. u.RawQuery = r.URL.RawQuery
  54. return &u
  55. }
  56. return &WebsocketProxy{Backend: backend, Verbal: false}
  57. }
  58. // ServeHTTP implements the http.Handler that proxies WebSocket connections.
  59. func (w *WebsocketProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
  60. if w.Backend == nil {
  61. log.Println("websocketproxy: backend function is not defined")
  62. http.Error(rw, "internal server error (code: 1)", http.StatusInternalServerError)
  63. return
  64. }
  65. backendURL := w.Backend(req)
  66. if backendURL == nil {
  67. log.Println("websocketproxy: backend URL is nil")
  68. http.Error(rw, "internal server error (code: 2)", http.StatusInternalServerError)
  69. return
  70. }
  71. dialer := w.Dialer
  72. if w.Dialer == nil {
  73. dialer = DefaultDialer
  74. }
  75. // Pass headers from the incoming request to the dialer to forward them to
  76. // the final destinations.
  77. requestHeader := http.Header{}
  78. if origin := req.Header.Get("Origin"); origin != "" {
  79. requestHeader.Add("Origin", origin)
  80. }
  81. for _, prot := range req.Header[http.CanonicalHeaderKey("Sec-WebSocket-Protocol")] {
  82. requestHeader.Add("Sec-WebSocket-Protocol", prot)
  83. }
  84. for _, cookie := range req.Header[http.CanonicalHeaderKey("Cookie")] {
  85. requestHeader.Add("Cookie", cookie)
  86. }
  87. if req.Host != "" {
  88. requestHeader.Set("Host", req.Host)
  89. }
  90. // Pass X-Forwarded-For headers too, code below is a part of
  91. // httputil.ReverseProxy. See http://en.wikipedia.org/wiki/X-Forwarded-For
  92. // for more information
  93. // TODO: use RFC7239 http://tools.ietf.org/html/rfc7239
  94. if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
  95. // If we aren't the first proxy retain prior
  96. // X-Forwarded-For information as a comma+space
  97. // separated list and fold multiple headers into one.
  98. if prior, ok := req.Header["X-Forwarded-For"]; ok {
  99. clientIP = strings.Join(prior, ", ") + ", " + clientIP
  100. }
  101. requestHeader.Set("X-Forwarded-For", clientIP)
  102. }
  103. // Set the originating protocol of the incoming HTTP request. The SSL might
  104. // be terminated on our site and because we doing proxy adding this would
  105. // be helpful for applications on the backend.
  106. requestHeader.Set("X-Forwarded-Proto", "http")
  107. if req.TLS != nil {
  108. requestHeader.Set("X-Forwarded-Proto", "https")
  109. }
  110. // Enable the director to copy any additional headers it desires for
  111. // forwarding to the remote server.
  112. if w.Director != nil {
  113. w.Director(req, requestHeader)
  114. }
  115. // Connect to the backend URL, also pass the headers we get from the requst
  116. // together with the Forwarded headers we prepared above.
  117. // TODO: support multiplexing on the same backend connection instead of
  118. // opening a new TCP connection time for each request. This should be
  119. // optional:
  120. // http://tools.ietf.org/html/draft-ietf-hybi-websocket-multiplexing-01
  121. connBackend, resp, err := dialer.Dial(backendURL.String(), requestHeader)
  122. if err != nil {
  123. log.Printf("websocketproxy: couldn't dial to remote backend url %s", err)
  124. if resp != nil {
  125. // If the WebSocket handshake fails, ErrBadHandshake is returned
  126. // along with a non-nil *http.Response so that callers can handle
  127. // redirects, authentication, etcetera.
  128. if err := copyResponse(rw, resp); err != nil {
  129. log.Printf("websocketproxy: couldn't write response after failed remote backend handshake: %s", err)
  130. }
  131. } else {
  132. http.Error(rw, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
  133. }
  134. return
  135. }
  136. defer connBackend.Close()
  137. upgrader := w.Upgrader
  138. if w.Upgrader == nil {
  139. upgrader = DefaultUpgrader
  140. }
  141. // Only pass those headers to the upgrader.
  142. upgradeHeader := http.Header{}
  143. if hdr := resp.Header.Get("Sec-Websocket-Protocol"); hdr != "" {
  144. upgradeHeader.Set("Sec-Websocket-Protocol", hdr)
  145. }
  146. if hdr := resp.Header.Get("Set-Cookie"); hdr != "" {
  147. upgradeHeader.Set("Set-Cookie", hdr)
  148. }
  149. // Now upgrade the existing incoming request to a WebSocket connection.
  150. // Also pass the header that we gathered from the Dial handshake.
  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. if w.Verbal {
  191. //Only print message on verbal mode
  192. log.Printf(message, err)
  193. }
  194. }
  195. }
  196. func copyHeader(dst, src http.Header) {
  197. for k, vv := range src {
  198. for _, v := range vv {
  199. dst.Add(k, v)
  200. }
  201. }
  202. }
  203. func copyResponse(rw http.ResponseWriter, resp *http.Response) error {
  204. copyHeader(rw.Header(), resp.Header)
  205. rw.WriteHeader(resp.StatusCode)
  206. defer resp.Body.Close()
  207. _, err := io.Copy(rw, resp.Body)
  208. return err
  209. }