client.go 6.9 KB

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