1
0

websocketproxy.go 8.2 KB

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