websocketproxy.go 8.6 KB

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