client.go 5.8 KB

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