client.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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. "context"
  8. "crypto/tls"
  9. "errors"
  10. "io"
  11. "io/ioutil"
  12. "net"
  13. "net/http"
  14. "net/http/httptrace"
  15. "net/url"
  16. "strings"
  17. "time"
  18. )
  19. // ErrBadHandshake is returned when the server response to opening handshake is
  20. // invalid.
  21. var ErrBadHandshake = errors.New("websocket: bad handshake")
  22. var errInvalidCompression = errors.New("websocket: invalid compression negotiation")
  23. // NewClient creates a new client connection using the given net connection.
  24. // The URL u specifies the host and request URI. Use requestHeader to specify
  25. // the origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies
  26. // (Cookie). Use the response.Header to get the selected subprotocol
  27. // (Sec-WebSocket-Protocol) and cookies (Set-Cookie).
  28. //
  29. // If the WebSocket handshake fails, ErrBadHandshake is returned along with a
  30. // non-nil *http.Response so that callers can handle redirects, authentication,
  31. // etc.
  32. //
  33. // Deprecated: Use Dialer instead.
  34. func NewClient(netConn net.Conn, u *url.URL, requestHeader http.Header, readBufSize, writeBufSize int) (c *Conn, response *http.Response, err error) {
  35. d := Dialer{
  36. ReadBufferSize: readBufSize,
  37. WriteBufferSize: writeBufSize,
  38. NetDial: func(net, addr string) (net.Conn, error) {
  39. return netConn, nil
  40. },
  41. }
  42. return d.Dial(u.String(), requestHeader)
  43. }
  44. // A Dialer contains options for connecting to WebSocket server.
  45. //
  46. // It is safe to call Dialer's methods concurrently.
  47. type Dialer struct {
  48. // NetDial specifies the dial function for creating TCP connections. If
  49. // NetDial is nil, net.Dial is used.
  50. NetDial func(network, addr string) (net.Conn, error)
  51. // NetDialContext specifies the dial function for creating TCP connections. If
  52. // NetDialContext is nil, NetDial is used.
  53. NetDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
  54. // NetDialTLSContext specifies the dial function for creating TLS/TCP connections. If
  55. // NetDialTLSContext is nil, NetDialContext is used.
  56. // If NetDialTLSContext is set, Dial assumes the TLS handshake is done there and
  57. // TLSClientConfig is ignored.
  58. NetDialTLSContext func(ctx context.Context, network, addr string) (net.Conn, error)
  59. // Proxy specifies a function to return a proxy for a given
  60. // Request. If the function returns a non-nil error, the
  61. // request is aborted with the provided error.
  62. // If Proxy is nil or returns a nil *URL, no proxy is used.
  63. Proxy func(*http.Request) (*url.URL, error)
  64. // TLSClientConfig specifies the TLS configuration to use with tls.Client.
  65. // If nil, the default configuration is used.
  66. // If either NetDialTLS or NetDialTLSContext are set, Dial assumes the TLS handshake
  67. // is done there and TLSClientConfig is ignored.
  68. TLSClientConfig *tls.Config
  69. // HandshakeTimeout specifies the duration for the handshake to complete.
  70. HandshakeTimeout time.Duration
  71. // ReadBufferSize and WriteBufferSize specify I/O buffer sizes in bytes. If a buffer
  72. // size is zero, then a useful default size is used. The I/O buffer sizes
  73. // do not limit the size of the messages that can be sent or received.
  74. ReadBufferSize, WriteBufferSize int
  75. // WriteBufferPool is a pool of buffers for write operations. If the value
  76. // is not set, then write buffers are allocated to the connection for the
  77. // lifetime of the connection.
  78. //
  79. // A pool is most useful when the application has a modest volume of writes
  80. // across a large number of connections.
  81. //
  82. // Applications should use a single pool for each unique value of
  83. // WriteBufferSize.
  84. WriteBufferPool BufferPool
  85. // Subprotocols specifies the client's requested subprotocols.
  86. Subprotocols []string
  87. // EnableCompression specifies if the client should attempt to negotiate
  88. // per message compression (RFC 7692). Setting this value to true does not
  89. // guarantee that compression will be supported. Currently only "no context
  90. // takeover" modes are supported.
  91. EnableCompression bool
  92. // Jar specifies the cookie jar.
  93. // If Jar is nil, cookies are not sent in requests and ignored
  94. // in responses.
  95. Jar http.CookieJar
  96. }
  97. // Dial creates a new client connection by calling DialContext with a background context.
  98. func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) {
  99. return d.DialContext(context.Background(), urlStr, requestHeader)
  100. }
  101. var errMalformedURL = errors.New("malformed ws or wss URL")
  102. func hostPortNoPort(u *url.URL) (hostPort, hostNoPort string) {
  103. hostPort = u.Host
  104. hostNoPort = u.Host
  105. if i := strings.LastIndex(u.Host, ":"); i > strings.LastIndex(u.Host, "]") {
  106. hostNoPort = hostNoPort[:i]
  107. } else {
  108. switch u.Scheme {
  109. case "wss":
  110. hostPort += ":443"
  111. case "https":
  112. hostPort += ":443"
  113. default:
  114. hostPort += ":80"
  115. }
  116. }
  117. return hostPort, hostNoPort
  118. }
  119. // DefaultDialer is a dialer with all fields set to the default values.
  120. var DefaultDialer = &Dialer{
  121. Proxy: http.ProxyFromEnvironment,
  122. HandshakeTimeout: 45 * time.Second,
  123. }
  124. // nilDialer is dialer to use when receiver is nil.
  125. var nilDialer = *DefaultDialer
  126. // DialContext creates a new client connection. Use requestHeader to specify the
  127. // origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies (Cookie).
  128. // Use the response.Header to get the selected subprotocol
  129. // (Sec-WebSocket-Protocol) and cookies (Set-Cookie).
  130. //
  131. // The context will be used in the request and in the Dialer.
  132. //
  133. // If the WebSocket handshake fails, ErrBadHandshake is returned along with a
  134. // non-nil *http.Response so that callers can handle redirects, authentication,
  135. // etcetera. The response body may not contain the entire response and does not
  136. // need to be closed by the application.
  137. func (d *Dialer) DialContext(ctx context.Context, urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) {
  138. if d == nil {
  139. d = &nilDialer
  140. }
  141. challengeKey, err := generateChallengeKey()
  142. if err != nil {
  143. return nil, nil, err
  144. }
  145. u, err := url.Parse(urlStr)
  146. if err != nil {
  147. return nil, nil, err
  148. }
  149. switch u.Scheme {
  150. case "ws":
  151. u.Scheme = "http"
  152. case "wss":
  153. u.Scheme = "https"
  154. default:
  155. return nil, nil, errMalformedURL
  156. }
  157. if u.User != nil {
  158. // User name and password are not allowed in websocket URIs.
  159. return nil, nil, errMalformedURL
  160. }
  161. req := &http.Request{
  162. Method: http.MethodGet,
  163. URL: u,
  164. Proto: "HTTP/1.1",
  165. ProtoMajor: 1,
  166. ProtoMinor: 1,
  167. Header: make(http.Header),
  168. Host: u.Host,
  169. }
  170. req = req.WithContext(ctx)
  171. // Set the cookies present in the cookie jar of the dialer
  172. if d.Jar != nil {
  173. for _, cookie := range d.Jar.Cookies(u) {
  174. req.AddCookie(cookie)
  175. }
  176. }
  177. // Set the request headers using the capitalization for names and values in
  178. // RFC examples. Although the capitalization shouldn't matter, there are
  179. // servers that depend on it. The Header.Set method is not used because the
  180. // method canonicalizes the header names.
  181. req.Header["Upgrade"] = []string{"websocket"}
  182. req.Header["Connection"] = []string{"Upgrade"}
  183. req.Header["Sec-WebSocket-Key"] = []string{challengeKey}
  184. req.Header["Sec-WebSocket-Version"] = []string{"13"}
  185. if len(d.Subprotocols) > 0 {
  186. req.Header["Sec-WebSocket-Protocol"] = []string{strings.Join(d.Subprotocols, ", ")}
  187. }
  188. for k, vs := range requestHeader {
  189. switch {
  190. case k == "Host":
  191. if len(vs) > 0 {
  192. req.Host = vs[0]
  193. }
  194. case k == "Upgrade" ||
  195. k == "Connection" ||
  196. k == "Sec-Websocket-Key" ||
  197. k == "Sec-Websocket-Version" ||
  198. k == "Sec-Websocket-Extensions" ||
  199. (k == "Sec-Websocket-Protocol" && len(d.Subprotocols) > 0):
  200. return nil, nil, errors.New("websocket: duplicate header not allowed: " + k)
  201. case k == "Sec-Websocket-Protocol":
  202. req.Header["Sec-WebSocket-Protocol"] = vs
  203. default:
  204. req.Header[k] = vs
  205. }
  206. }
  207. if d.EnableCompression {
  208. req.Header["Sec-WebSocket-Extensions"] = []string{"permessage-deflate; server_no_context_takeover; client_no_context_takeover"}
  209. }
  210. if d.HandshakeTimeout != 0 {
  211. var cancel func()
  212. ctx, cancel = context.WithTimeout(ctx, d.HandshakeTimeout)
  213. defer cancel()
  214. }
  215. // Get network dial function.
  216. var netDial func(network, add string) (net.Conn, error)
  217. switch u.Scheme {
  218. case "http":
  219. if d.NetDialContext != nil {
  220. netDial = func(network, addr string) (net.Conn, error) {
  221. return d.NetDialContext(ctx, network, addr)
  222. }
  223. } else if d.NetDial != nil {
  224. netDial = d.NetDial
  225. }
  226. case "https":
  227. if d.NetDialTLSContext != nil {
  228. netDial = func(network, addr string) (net.Conn, error) {
  229. return d.NetDialTLSContext(ctx, network, addr)
  230. }
  231. } else if d.NetDialContext != nil {
  232. netDial = func(network, addr string) (net.Conn, error) {
  233. return d.NetDialContext(ctx, network, addr)
  234. }
  235. } else if d.NetDial != nil {
  236. netDial = d.NetDial
  237. }
  238. default:
  239. return nil, nil, errMalformedURL
  240. }
  241. if netDial == nil {
  242. netDialer := &net.Dialer{}
  243. netDial = func(network, addr string) (net.Conn, error) {
  244. return netDialer.DialContext(ctx, network, addr)
  245. }
  246. }
  247. // If needed, wrap the dial function to set the connection deadline.
  248. if deadline, ok := ctx.Deadline(); ok {
  249. forwardDial := netDial
  250. netDial = func(network, addr string) (net.Conn, error) {
  251. c, err := forwardDial(network, addr)
  252. if err != nil {
  253. return nil, err
  254. }
  255. err = c.SetDeadline(deadline)
  256. if err != nil {
  257. c.Close()
  258. return nil, err
  259. }
  260. return c, nil
  261. }
  262. }
  263. // If needed, wrap the dial function to connect through a proxy.
  264. if d.Proxy != nil {
  265. proxyURL, err := d.Proxy(req)
  266. if err != nil {
  267. return nil, nil, err
  268. }
  269. if proxyURL != nil {
  270. dialer, err := proxy_FromURL(proxyURL, netDialerFunc(netDial))
  271. if err != nil {
  272. return nil, nil, err
  273. }
  274. netDial = dialer.Dial
  275. }
  276. }
  277. hostPort, hostNoPort := hostPortNoPort(u)
  278. trace := httptrace.ContextClientTrace(ctx)
  279. if trace != nil && trace.GetConn != nil {
  280. trace.GetConn(hostPort)
  281. }
  282. netConn, err := netDial("tcp", hostPort)
  283. if trace != nil && trace.GotConn != nil {
  284. trace.GotConn(httptrace.GotConnInfo{
  285. Conn: netConn,
  286. })
  287. }
  288. if err != nil {
  289. return nil, nil, err
  290. }
  291. defer func() {
  292. if netConn != nil {
  293. netConn.Close()
  294. }
  295. }()
  296. if u.Scheme == "https" && d.NetDialTLSContext == nil {
  297. // If NetDialTLSContext is set, assume that the TLS handshake has already been done
  298. cfg := cloneTLSConfig(d.TLSClientConfig)
  299. if cfg.ServerName == "" {
  300. cfg.ServerName = hostNoPort
  301. }
  302. tlsConn := tls.Client(netConn, cfg)
  303. netConn = tlsConn
  304. if trace != nil && trace.TLSHandshakeStart != nil {
  305. trace.TLSHandshakeStart()
  306. }
  307. err := doHandshake(ctx, tlsConn, cfg)
  308. if trace != nil && trace.TLSHandshakeDone != nil {
  309. trace.TLSHandshakeDone(tlsConn.ConnectionState(), err)
  310. }
  311. if err != nil {
  312. return nil, nil, err
  313. }
  314. }
  315. conn := newConn(netConn, false, d.ReadBufferSize, d.WriteBufferSize, d.WriteBufferPool, nil, nil)
  316. if err := req.Write(netConn); err != nil {
  317. return nil, nil, err
  318. }
  319. if trace != nil && trace.GotFirstResponseByte != nil {
  320. if peek, err := conn.br.Peek(1); err == nil && len(peek) == 1 {
  321. trace.GotFirstResponseByte()
  322. }
  323. }
  324. resp, err := http.ReadResponse(conn.br, req)
  325. if err != nil {
  326. return nil, nil, err
  327. }
  328. if d.Jar != nil {
  329. if rc := resp.Cookies(); len(rc) > 0 {
  330. d.Jar.SetCookies(u, rc)
  331. }
  332. }
  333. if resp.StatusCode != 101 ||
  334. !tokenListContainsValue(resp.Header, "Upgrade", "websocket") ||
  335. !tokenListContainsValue(resp.Header, "Connection", "upgrade") ||
  336. resp.Header.Get("Sec-Websocket-Accept") != computeAcceptKey(challengeKey) {
  337. // Before closing the network connection on return from this
  338. // function, slurp up some of the response to aid application
  339. // debugging.
  340. buf := make([]byte, 1024)
  341. n, _ := io.ReadFull(resp.Body, buf)
  342. resp.Body = ioutil.NopCloser(bytes.NewReader(buf[:n]))
  343. return nil, resp, ErrBadHandshake
  344. }
  345. for _, ext := range parseExtensions(resp.Header) {
  346. if ext[""] != "permessage-deflate" {
  347. continue
  348. }
  349. _, snct := ext["server_no_context_takeover"]
  350. _, cnct := ext["client_no_context_takeover"]
  351. if !snct || !cnct {
  352. return nil, resp, errInvalidCompression
  353. }
  354. conn.newCompressionWriter = compressNoContextTakeover
  355. conn.newDecompressionReader = decompressNoContextTakeover
  356. break
  357. }
  358. resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
  359. conn.subprotocol = resp.Header.Get("Sec-Websocket-Protocol")
  360. netConn.SetDeadline(time.Time{})
  361. netConn = nil // to avoid close in defer.
  362. return conn, resp, nil
  363. }
  364. func cloneTLSConfig(cfg *tls.Config) *tls.Config {
  365. if cfg == nil {
  366. return &tls.Config{}
  367. }
  368. return cfg.Clone()
  369. }