client.go 6.6 KB

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