client.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. // Copyright 2013 Gary Burd. 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. "crypto/tls"
  7. "errors"
  8. "net"
  9. "net/http"
  10. "net/url"
  11. "strings"
  12. "time"
  13. )
  14. // ErrBadHandshake is returned when the server response to opening handshake is
  15. // invalid.
  16. var ErrBadHandshake = errors.New("websocket: bad handshake")
  17. // NewClient creates a new client connection using the given net connection.
  18. // The URL u specifies the host and request URI. Use requestHeader to specify
  19. // the origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies
  20. // (Cookie). Use the response.Header to get the selected subprotocol
  21. // (Sec-WebSocket-Protocol) and cookies (Set-Cookie).
  22. //
  23. // If the WebSocket handshake fails, ErrBadHandshake is returned along with a
  24. // non-nil *http.Response so that callers can handle redirects, authentication,
  25. // etc.
  26. func NewClient(netConn net.Conn, u *url.URL, requestHeader http.Header, readBufSize, writeBufSize int) (c *Conn, response *http.Response, err error) {
  27. challengeKey, err := generateChallengeKey()
  28. if err != nil {
  29. return nil, nil, err
  30. }
  31. acceptKey := computeAcceptKey(challengeKey)
  32. c = newConn(netConn, false, readBufSize, writeBufSize)
  33. p := c.writeBuf[:0]
  34. p = append(p, "GET "...)
  35. p = append(p, u.RequestURI()...)
  36. p = append(p, " HTTP/1.1\r\nHost: "...)
  37. p = append(p, u.Host...)
  38. // "Upgrade" is capitalized for servers that do not use case insensitive
  39. // comparisons on header tokens.
  40. p = append(p, "\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: "...)
  41. p = append(p, challengeKey...)
  42. p = append(p, "\r\n"...)
  43. for k, vs := range requestHeader {
  44. for _, v := range vs {
  45. p = append(p, k...)
  46. p = append(p, ": "...)
  47. p = append(p, v...)
  48. p = append(p, "\r\n"...)
  49. }
  50. }
  51. p = append(p, "\r\n"...)
  52. if _, err := netConn.Write(p); err != nil {
  53. return nil, nil, err
  54. }
  55. resp, err := http.ReadResponse(c.br, &http.Request{Method: "GET", URL: u})
  56. if err != nil {
  57. return nil, nil, err
  58. }
  59. if resp.StatusCode != 101 ||
  60. !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
  61. !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
  62. resp.Header.Get("Sec-Websocket-Accept") != acceptKey {
  63. return nil, resp, ErrBadHandshake
  64. }
  65. c.subprotocol = resp.Header.Get("Sec-Websocket-Protocol")
  66. return c, resp, nil
  67. }
  68. // A Dialer contains options for connecting to WebSocket server.
  69. type Dialer struct {
  70. // NetDial specifies the dial function for creating TCP connections. If
  71. // NetDial is nil, net.Dial is used.
  72. NetDial func(network, addr string) (net.Conn, error)
  73. // TLSClientConfig specifies the TLS configuration to use with tls.Client.
  74. // If nil, the default configuration is used.
  75. TLSClientConfig *tls.Config
  76. // HandshakeTimeout specifies the duration for the handshake to complete.
  77. HandshakeTimeout time.Duration
  78. // Input and output buffer sizes. If the buffer size is zero, then a
  79. // default value of 4096 is used.
  80. ReadBufferSize, WriteBufferSize int
  81. // Subprotocols specifies the client's requested subprotocols.
  82. Subprotocols []string
  83. }
  84. var errMalformedURL = errors.New("malformed ws or wss URL")
  85. func parseURL(u string) (useTLS bool, host, port, opaque string, err error) {
  86. // From the RFC:
  87. //
  88. // ws-URI = "ws:" "//" host [ ":" port ] path [ "?" query ]
  89. // wss-URI = "wss:" "//" host [ ":" port ] path [ "?" query ]
  90. //
  91. // We don't use the net/url parser here because the dialer interface does
  92. // not provide a way for applications to work around percent deocding in
  93. // the net/url parser.
  94. switch {
  95. case strings.HasPrefix(u, "ws://"):
  96. u = u[len("ws://"):]
  97. case strings.HasPrefix(u, "wss://"):
  98. u = u[len("wss://"):]
  99. useTLS = true
  100. default:
  101. return false, "", "", "", errMalformedURL
  102. }
  103. hostPort := u
  104. opaque = "/"
  105. if i := strings.Index(u, "/"); i >= 0 {
  106. hostPort = u[:i]
  107. opaque = u[i:]
  108. }
  109. host = hostPort
  110. port = ":80"
  111. if i := strings.LastIndex(hostPort, ":"); i > strings.LastIndex(hostPort, "]") {
  112. host = hostPort[:i]
  113. port = hostPort[i:]
  114. } else if useTLS {
  115. port = ":443"
  116. }
  117. return useTLS, host, port, opaque, nil
  118. }
  119. // DefaultDialer is a dialer with all fields set to the default zero values.
  120. var DefaultDialer *Dialer
  121. // Dial creates a new client connection. Use requestHeader to specify the
  122. // origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies (Cookie).
  123. // Use the response.Header to get the selected subprotocol
  124. // (Sec-WebSocket-Protocol) and cookies (Set-Cookie).
  125. //
  126. // If the WebSocket handshake fails, ErrBadHandshake is returned along with a
  127. // non-nil *http.Response so that callers can handle redirects, authentication,
  128. // etc.
  129. func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) {
  130. useTLS, host, port, opaque, err := parseURL(urlStr)
  131. if err != nil {
  132. return nil, nil, err
  133. }
  134. if d == nil {
  135. d = &Dialer{}
  136. }
  137. var deadline time.Time
  138. if d.HandshakeTimeout != 0 {
  139. deadline = time.Now().Add(d.HandshakeTimeout)
  140. }
  141. netDial := d.NetDial
  142. if netDial == nil {
  143. netDialer := &net.Dialer{Deadline: deadline}
  144. netDial = netDialer.Dial
  145. }
  146. netConn, err := netDial("tcp", host+port)
  147. if err != nil {
  148. return nil, nil, err
  149. }
  150. defer func() {
  151. if netConn != nil {
  152. netConn.Close()
  153. }
  154. }()
  155. if err := netConn.SetDeadline(deadline); err != nil {
  156. return nil, nil, err
  157. }
  158. if useTLS {
  159. cfg := d.TLSClientConfig
  160. if cfg == nil {
  161. cfg = &tls.Config{ServerName: host}
  162. } else if cfg.ServerName == "" {
  163. shallowCopy := *cfg
  164. cfg = &shallowCopy
  165. cfg.ServerName = host
  166. }
  167. tlsConn := tls.Client(netConn, cfg)
  168. netConn = tlsConn
  169. if err := tlsConn.Handshake(); err != nil {
  170. return nil, nil, err
  171. }
  172. if !cfg.InsecureSkipVerify {
  173. if err := tlsConn.VerifyHostname(cfg.ServerName); err != nil {
  174. return nil, nil, err
  175. }
  176. }
  177. }
  178. readBufferSize := d.ReadBufferSize
  179. if readBufferSize == 0 {
  180. readBufferSize = 4096
  181. }
  182. writeBufferSize := d.WriteBufferSize
  183. if writeBufferSize == 0 {
  184. writeBufferSize = 4096
  185. }
  186. if len(d.Subprotocols) > 0 {
  187. h := http.Header{}
  188. for k, v := range requestHeader {
  189. h[k] = v
  190. }
  191. h.Set("Sec-Websocket-Protocol", strings.Join(d.Subprotocols, ", "))
  192. requestHeader = h
  193. }
  194. conn, resp, err := NewClient(
  195. netConn,
  196. &url.URL{Host: host + port, Opaque: opaque},
  197. requestHeader, readBufferSize, writeBufferSize)
  198. if err != nil {
  199. return nil, resp, err
  200. }
  201. netConn.SetDeadline(time.Time{})
  202. netConn = nil // to avoid close in defer.
  203. return conn, resp, nil
  204. }