client.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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. if strings.Contains(u.Host, "@") {
  117. // WebSocket URIs do not contain user information.
  118. return nil, errMalformedURL
  119. }
  120. return &u, nil
  121. }
  122. func hostPortNoPort(u *url.URL) (hostPort, hostNoPort string) {
  123. hostPort = u.Host
  124. hostNoPort = u.Host
  125. if i := strings.LastIndex(u.Host, ":"); i > strings.LastIndex(u.Host, "]") {
  126. hostNoPort = hostNoPort[:i]
  127. } else {
  128. if u.Scheme == "wss" {
  129. hostPort += ":443"
  130. } else {
  131. hostPort += ":80"
  132. }
  133. }
  134. return hostPort, hostNoPort
  135. }
  136. // DefaultDialer is a dialer with all fields set to the default zero values.
  137. var DefaultDialer *Dialer
  138. // Dial creates a new client connection. Use requestHeader to specify the
  139. // origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies (Cookie).
  140. // Use the response.Header to get the selected subprotocol
  141. // (Sec-WebSocket-Protocol) and cookies (Set-Cookie).
  142. //
  143. // If the WebSocket handshake fails, ErrBadHandshake is returned along with a
  144. // non-nil *http.Response so that callers can handle redirects, authentication,
  145. // etcetera. The response body may not contain the entire response and does not
  146. // need to be closed by the application.
  147. func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) {
  148. u, err := parseURL(urlStr)
  149. if err != nil {
  150. return nil, nil, err
  151. }
  152. hostPort, hostNoPort := hostPortNoPort(u)
  153. if d == nil {
  154. d = &Dialer{}
  155. }
  156. var deadline time.Time
  157. if d.HandshakeTimeout != 0 {
  158. deadline = time.Now().Add(d.HandshakeTimeout)
  159. }
  160. netDial := d.NetDial
  161. if netDial == nil {
  162. netDialer := &net.Dialer{Deadline: deadline}
  163. netDial = netDialer.Dial
  164. }
  165. netConn, err := netDial("tcp", hostPort)
  166. if err != nil {
  167. return nil, nil, err
  168. }
  169. defer func() {
  170. if netConn != nil {
  171. netConn.Close()
  172. }
  173. }()
  174. if err := netConn.SetDeadline(deadline); err != nil {
  175. return nil, nil, err
  176. }
  177. if u.Scheme == "wss" {
  178. cfg := d.TLSClientConfig
  179. if cfg == nil {
  180. cfg = &tls.Config{ServerName: hostNoPort}
  181. } else if cfg.ServerName == "" {
  182. shallowCopy := *cfg
  183. cfg = &shallowCopy
  184. cfg.ServerName = hostNoPort
  185. }
  186. tlsConn := tls.Client(netConn, cfg)
  187. netConn = tlsConn
  188. if err := tlsConn.Handshake(); err != nil {
  189. return nil, nil, err
  190. }
  191. if !cfg.InsecureSkipVerify {
  192. if err := tlsConn.VerifyHostname(cfg.ServerName); err != nil {
  193. return nil, nil, err
  194. }
  195. }
  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. if len(requestHeader["Host"]) > 0 {
  206. // This can be used to supply a Host: header which is different from
  207. // the dial address.
  208. u.Host = requestHeader.Get("Host")
  209. // Drop "Host" header
  210. h := http.Header{}
  211. for k, v := range requestHeader {
  212. if k == "Host" {
  213. continue
  214. }
  215. h[k] = v
  216. }
  217. requestHeader = h
  218. }
  219. conn, resp, err := NewClient(netConn, u, requestHeader, d.ReadBufferSize, d.WriteBufferSize)
  220. if err != nil {
  221. if err == ErrBadHandshake {
  222. // Before closing the network connection on return from this
  223. // function, slurp up some of the response to aid application
  224. // debugging.
  225. buf := make([]byte, 1024)
  226. n, _ := io.ReadFull(resp.Body, buf)
  227. resp.Body = ioutil.NopCloser(bytes.NewReader(buf[:n]))
  228. }
  229. return nil, resp, err
  230. }
  231. netConn.SetDeadline(time.Time{})
  232. netConn = nil // to avoid close in defer.
  233. return conn, resp, nil
  234. }