client.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package websocket
  5. import (
  6. "bytes"
  7. "crypto/tls"
  8. "errors"
  9. "io"
  10. "io/ioutil"
  11. "net"
  12. "net/http"
  13. "net/url"
  14. "strings"
  15. "time"
  16. )
  17. // ErrBadHandshake is returned when the server response to opening handshake is
  18. // invalid.
  19. var ErrBadHandshake = errors.New("websocket: bad handshake")
  20. var errInvalidCompression = errors.New("websocket: invalid compression negotiation")
  21. // NewClient creates a new client connection using the given net connection.
  22. // The URL u specifies the host and request URI. Use requestHeader to specify
  23. // the origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies
  24. // (Cookie). Use the response.Header to get the selected subprotocol
  25. // (Sec-WebSocket-Protocol) and cookies (Set-Cookie).
  26. //
  27. // If the WebSocket handshake fails, ErrBadHandshake is returned along with a
  28. // non-nil *http.Response so that callers can handle redirects, authentication,
  29. // etc.
  30. //
  31. // Deprecated: Use Dialer instead.
  32. func NewClient(netConn net.Conn, u *url.URL, requestHeader http.Header, readBufSize, writeBufSize int) (c *Conn, response *http.Response, err error) {
  33. d := Dialer{
  34. ReadBufferSize: readBufSize,
  35. WriteBufferSize: writeBufSize,
  36. NetDial: func(net, addr string) (net.Conn, error) {
  37. return netConn, nil
  38. },
  39. HandshakeTimeout: 5 * time.Second,
  40. }
  41. return d.Dial(u.String(), requestHeader)
  42. }
  43. // A Dialer contains options for connecting to WebSocket server.
  44. type Dialer struct {
  45. // NetDial specifies the dial function for creating TCP connections. If
  46. // NetDial is nil, net.Dial is used.
  47. NetDial func(network, addr string) (net.Conn, error)
  48. // Proxy specifies a function to return a proxy for a given
  49. // Request. If the function returns a non-nil error, the
  50. // request is aborted with the provided error.
  51. // If Proxy is nil or returns a nil *URL, no proxy is used.
  52. Proxy func(*http.Request) (*url.URL, error)
  53. // TLSClientConfig specifies the TLS configuration to use with tls.Client.
  54. // If nil, the default configuration is used.
  55. TLSClientConfig *tls.Config
  56. // HandshakeTimeout specifies the duration for the handshake to complete.
  57. HandshakeTimeout time.Duration
  58. // ReadBufferSize and WriteBufferSize specify I/O buffer sizes. If a buffer
  59. // size is zero, then a useful default size is used. The I/O buffer sizes
  60. // do not limit the size of the messages that can be sent or received.
  61. ReadBufferSize, WriteBufferSize int
  62. // Subprotocols specifies the client's requested subprotocols.
  63. Subprotocols []string
  64. // EnableCompression specifies if the client should attempt to negotiate
  65. // per message compression (RFC 7692). Setting this value to true does not
  66. // guarantee that compression will be supported. Currently only "no context
  67. // takeover" modes are supported.
  68. EnableCompression bool
  69. // Jar specifies the cookie jar.
  70. // If Jar is nil, cookies are not sent in requests and ignored
  71. // in responses.
  72. Jar http.CookieJar
  73. }
  74. var errMalformedURL = errors.New("malformed ws or wss URL")
  75. func hostPortNoPort(u *url.URL) (hostPort, hostNoPort string) {
  76. hostPort = u.Host
  77. hostNoPort = u.Host
  78. if i := strings.LastIndex(u.Host, ":"); i > strings.LastIndex(u.Host, "]") {
  79. hostNoPort = hostNoPort[:i]
  80. } else {
  81. switch u.Scheme {
  82. case "wss":
  83. hostPort += ":443"
  84. case "https":
  85. hostPort += ":443"
  86. default:
  87. hostPort += ":80"
  88. }
  89. }
  90. return hostPort, hostNoPort
  91. }
  92. // DefaultDialer is a dialer with all fields set to the default values.
  93. var DefaultDialer = &Dialer{
  94. Proxy: http.ProxyFromEnvironment,
  95. HandshakeTimeout: 5 * time.Second,
  96. }
  97. // Dial creates a new client connection. Use requestHeader to specify the
  98. // origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies (Cookie).
  99. // Use the response.Header to get the selected subprotocol
  100. // (Sec-WebSocket-Protocol) and cookies (Set-Cookie).
  101. //
  102. // If the WebSocket handshake fails, ErrBadHandshake is returned along with a
  103. // non-nil *http.Response so that callers can handle redirects, authentication,
  104. // etcetera. The response body may not contain the entire response and does not
  105. // need to be closed by the application.
  106. func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) {
  107. if d == nil {
  108. d = &Dialer{
  109. Proxy: http.ProxyFromEnvironment,
  110. HandshakeTimeout: 5 * time.Second,
  111. }
  112. }
  113. challengeKey, err := generateChallengeKey()
  114. if err != nil {
  115. return nil, nil, err
  116. }
  117. u, err := url.Parse(urlStr)
  118. if err != nil {
  119. return nil, nil, err
  120. }
  121. switch u.Scheme {
  122. case "ws":
  123. u.Scheme = "http"
  124. case "wss":
  125. u.Scheme = "https"
  126. default:
  127. return nil, nil, errMalformedURL
  128. }
  129. if u.User != nil {
  130. // User name and password are not allowed in websocket URIs.
  131. return nil, nil, errMalformedURL
  132. }
  133. req := &http.Request{
  134. Method: "GET",
  135. URL: u,
  136. Proto: "HTTP/1.1",
  137. ProtoMajor: 1,
  138. ProtoMinor: 1,
  139. Header: make(http.Header),
  140. Host: u.Host,
  141. }
  142. // Set the cookies present in the cookie jar of the dialer
  143. if d.Jar != nil {
  144. for _, cookie := range d.Jar.Cookies(u) {
  145. req.AddCookie(cookie)
  146. }
  147. }
  148. // Set the request headers using the capitalization for names and values in
  149. // RFC examples. Although the capitalization shouldn't matter, there are
  150. // servers that depend on it. The Header.Set method is not used because the
  151. // method canonicalizes the header names.
  152. req.Header["Upgrade"] = []string{"websocket"}
  153. req.Header["Connection"] = []string{"Upgrade"}
  154. req.Header["Sec-WebSocket-Key"] = []string{challengeKey}
  155. req.Header["Sec-WebSocket-Version"] = []string{"13"}
  156. if len(d.Subprotocols) > 0 {
  157. req.Header["Sec-WebSocket-Protocol"] = []string{strings.Join(d.Subprotocols, ", ")}
  158. }
  159. for k, vs := range requestHeader {
  160. switch {
  161. case k == "Host":
  162. if len(vs) > 0 {
  163. req.Host = vs[0]
  164. }
  165. case k == "Upgrade" ||
  166. k == "Connection" ||
  167. k == "Sec-Websocket-Key" ||
  168. k == "Sec-Websocket-Version" ||
  169. k == "Sec-Websocket-Extensions" ||
  170. (k == "Sec-Websocket-Protocol" && len(d.Subprotocols) > 0):
  171. return nil, nil, errors.New("websocket: duplicate header not allowed: " + k)
  172. case k == "Sec-Websocket-Protocol":
  173. req.Header["Sec-WebSocket-Protocol"] = vs
  174. default:
  175. req.Header[k] = vs
  176. }
  177. }
  178. if d.EnableCompression {
  179. req.Header.Set("Sec-Websocket-Extensions", "permessage-deflate; server_no_context_takeover; client_no_context_takeover")
  180. }
  181. var deadline time.Time
  182. if d.HandshakeTimeout != 0 {
  183. deadline = time.Now().Add(d.HandshakeTimeout)
  184. }
  185. // Get network dial function.
  186. netDial := d.NetDial
  187. if netDial == nil {
  188. netDialer := &net.Dialer{Deadline: deadline}
  189. netDial = netDialer.Dial
  190. }
  191. // If needed, wrap the dial function to set the connection deadline.
  192. if !deadline.Equal(time.Time{}) {
  193. forwardDial := netDial
  194. netDial = func(network, addr string) (net.Conn, error) {
  195. c, err := forwardDial(network, addr)
  196. if err != nil {
  197. return nil, err
  198. }
  199. err = c.SetDeadline(deadline)
  200. if err != nil {
  201. c.Close()
  202. return nil, err
  203. }
  204. return c, nil
  205. }
  206. }
  207. // If needed, wrap the dial function to connect through a proxy.
  208. if d.Proxy != nil {
  209. proxyURL, err := d.Proxy(req)
  210. if err != nil {
  211. return nil, nil, err
  212. }
  213. if proxyURL != nil {
  214. dialer, err := proxy_FromURL(proxyURL, netDialerFunc(netDial))
  215. if err != nil {
  216. return nil, nil, err
  217. }
  218. netDial = dialer.Dial
  219. }
  220. }
  221. hostPort, hostNoPort := hostPortNoPort(u)
  222. netConn, err := netDial("tcp", hostPort)
  223. if err != nil {
  224. return nil, nil, err
  225. }
  226. defer func() {
  227. if netConn != nil {
  228. netConn.Close()
  229. }
  230. }()
  231. if u.Scheme == "https" {
  232. cfg := cloneTLSConfig(d.TLSClientConfig)
  233. if cfg.ServerName == "" {
  234. cfg.ServerName = hostNoPort
  235. }
  236. tlsConn := tls.Client(netConn, cfg)
  237. netConn = tlsConn
  238. if err := tlsConn.Handshake(); err != nil {
  239. return nil, nil, err
  240. }
  241. if !cfg.InsecureSkipVerify {
  242. if err := tlsConn.VerifyHostname(cfg.ServerName); err != nil {
  243. return nil, nil, err
  244. }
  245. }
  246. }
  247. conn := newConn(netConn, false, d.ReadBufferSize, d.WriteBufferSize)
  248. if err := req.Write(netConn); err != nil {
  249. return nil, nil, err
  250. }
  251. resp, err := http.ReadResponse(conn.br, req)
  252. if err != nil {
  253. return nil, nil, err
  254. }
  255. if d.Jar != nil {
  256. if rc := resp.Cookies(); len(rc) > 0 {
  257. d.Jar.SetCookies(u, rc)
  258. }
  259. }
  260. if resp.StatusCode != 101 ||
  261. !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
  262. !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
  263. resp.Header.Get("Sec-Websocket-Accept") != computeAcceptKey(challengeKey) {
  264. // Before closing the network connection on return from this
  265. // function, slurp up some of the response to aid application
  266. // debugging.
  267. buf := make([]byte, 1024)
  268. n, _ := io.ReadFull(resp.Body, buf)
  269. resp.Body = ioutil.NopCloser(bytes.NewReader(buf[:n]))
  270. return nil, resp, ErrBadHandshake
  271. }
  272. for _, ext := range parseExtensions(resp.Header) {
  273. if ext[""] != "permessage-deflate" {
  274. continue
  275. }
  276. _, snct := ext["server_no_context_takeover"]
  277. _, cnct := ext["client_no_context_takeover"]
  278. if !snct || !cnct {
  279. return nil, resp, errInvalidCompression
  280. }
  281. conn.newCompressionWriter = compressNoContextTakeover
  282. conn.newDecompressionReader = decompressNoContextTakeover
  283. break
  284. }
  285. resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
  286. conn.subprotocol = resp.Header.Get("Sec-Websocket-Protocol")
  287. netConn.SetDeadline(time.Time{})
  288. netConn = nil // to avoid close in defer.
  289. return conn, resp, nil
  290. }