client.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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. type Dialer struct {
  69. // NetDial specifies the dial function for creating TCP connections. If
  70. // NetDial is nil, net.Dial is used.
  71. NetDial func(network, addr string) (net.Conn, error)
  72. // TLSClientConfig specifies the TLS configuration to use with tls.Client.
  73. // If nil, the default configuration is used.
  74. TLSClientConfig *tls.Config
  75. // HandshakeTimeout specifies the duration for the handshake to complete.
  76. HandshakeTimeout time.Duration
  77. // Input and output buffer sizes. If the buffer size is zero, then a
  78. // default value of 4096 is used.
  79. ReadBufferSize, WriteBufferSize int
  80. // Subprotocols specifies the client's requested subprotocols.
  81. Subprotocols []string
  82. }
  83. var errMalformedURL = errors.New("malformed ws or wss URL")
  84. func parseURL(u string) (useTLS bool, host, port, opaque string, err error) {
  85. // From the RFC:
  86. //
  87. // ws-URI = "ws:" "//" host [ ":" port ] path [ "?" query ]
  88. // wss-URI = "wss:" "//" host [ ":" port ] path [ "?" query ]
  89. //
  90. // We don't use the net/url parser here because the dialer interface does
  91. // not provide a way for applications to work around percent deocding in
  92. // the net/url parser.
  93. switch {
  94. case strings.HasPrefix(u, "ws://"):
  95. u = u[len("ws://"):]
  96. case strings.HasPrefix(u, "wss://"):
  97. u = u[len("wss://"):]
  98. useTLS = true
  99. default:
  100. return false, "", "", "", errMalformedURL
  101. }
  102. hostPort := u
  103. opaque = "/"
  104. if i := strings.Index(u, "/"); i >= 0 {
  105. hostPort = u[:i]
  106. opaque = u[i:]
  107. }
  108. host = hostPort
  109. port = ":80"
  110. if i := strings.LastIndex(hostPort, ":"); i > strings.LastIndex(hostPort, "]") {
  111. host = hostPort[:i]
  112. port = hostPort[i:]
  113. } else if useTLS {
  114. port = ":443"
  115. }
  116. return useTLS, host, port, opaque, nil
  117. }
  118. var DefaultDialer *Dialer
  119. // Dial creates a new client connection. Use requestHeader to specify the
  120. // origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies (Cookie).
  121. // Use the response.Header to get the selected subprotocol
  122. // (Sec-WebSocket-Protocol) and cookies (Set-Cookie).
  123. //
  124. // If the WebSocket handshake fails, ErrBadHandshake is returned along with a
  125. // non-nil *http.Response so that callers can handle redirects, authentication,
  126. // etc.
  127. func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) {
  128. useTLS, host, port, opaque, err := parseURL(urlStr)
  129. if err != nil {
  130. return nil, nil, err
  131. }
  132. if d == nil {
  133. d = &Dialer{}
  134. }
  135. var deadline time.Time
  136. if d.HandshakeTimeout != 0 {
  137. deadline = time.Now().Add(d.HandshakeTimeout)
  138. }
  139. netDial := d.NetDial
  140. if netDial == nil {
  141. netDialer := &net.Dialer{Deadline: deadline}
  142. netDial = netDialer.Dial
  143. }
  144. netConn, err := netDial("tcp", host+port)
  145. if err != nil {
  146. return nil, nil, err
  147. }
  148. defer func() {
  149. if netConn != nil {
  150. netConn.Close()
  151. }
  152. }()
  153. if err := netConn.SetDeadline(deadline); err != nil {
  154. return nil, nil, err
  155. }
  156. if useTLS {
  157. cfg := d.TLSClientConfig
  158. if cfg == nil {
  159. cfg = &tls.Config{ServerName: host}
  160. } else if cfg.ServerName == "" {
  161. shallowCopy := *cfg
  162. cfg = &shallowCopy
  163. cfg.ServerName = host
  164. }
  165. tlsConn := tls.Client(netConn, cfg)
  166. netConn = tlsConn
  167. if err := tlsConn.Handshake(); err != nil {
  168. return nil, nil, err
  169. }
  170. if !cfg.InsecureSkipVerify {
  171. if err := tlsConn.VerifyHostname(cfg.ServerName); err != nil {
  172. return nil, nil, err
  173. }
  174. }
  175. }
  176. readBufferSize := d.ReadBufferSize
  177. if readBufferSize == 0 {
  178. readBufferSize = 4096
  179. }
  180. writeBufferSize := d.WriteBufferSize
  181. if writeBufferSize == 0 {
  182. writeBufferSize = 4096
  183. }
  184. if len(d.Subprotocols) > 0 {
  185. h := http.Header{}
  186. for k, v := range requestHeader {
  187. h[k] = v
  188. }
  189. h.Set("Sec-Websocket-Protocol", strings.Join(d.Subprotocols, ", "))
  190. requestHeader = h
  191. }
  192. conn, resp, err := NewClient(
  193. netConn,
  194. &url.URL{Host: host + port, Opaque: opaque},
  195. requestHeader, readBufferSize, writeBufferSize)
  196. if err != nil {
  197. return nil, resp, err
  198. }
  199. netConn.SetDeadline(time.Time{})
  200. netConn = nil // to avoid close in defer.
  201. return conn, resp, nil
  202. }