websocketproxy.go 7.9 KB

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