websocketproxy.go 11 KB

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