client.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. var errInvalidCompression = errors.New("websocket: invalid compression negotiation")
  21. // NewClient creates a new client connection using the given net connection.
  22. // The URL u specifies the host and request URI. Use requestHeader to specify
  23. // the origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies
  24. // (Cookie). Use the response.Header to get the selected subprotocol
  25. // (Sec-WebSocket-Protocol) and cookies (Set-Cookie).
  26. //
  27. // If the WebSocket handshake fails, ErrBadHandshake is returned along with a
  28. // non-nil *http.Response so that callers can handle redirects, authentication,
  29. // etc.
  30. //
  31. // Deprecated: Use Dialer instead.
  32. func NewClient(netConn net.Conn, u *url.URL, requestHeader http.Header, readBufSize, writeBufSize int) (c *Conn, response *http.Response, err error) {
  33. d := Dialer{
  34. ReadBufferSize: readBufSize,
  35. WriteBufferSize: writeBufSize,
  36. NetDial: func(net, addr string) (net.Conn, error) {
  37. return netConn, nil
  38. },
  39. }
  40. return d.Dial(u.String(), requestHeader)
  41. }
  42. // A Dialer contains options for connecting to WebSocket server.
  43. type Dialer struct {
  44. // NetDial specifies the dial function for creating TCP connections. If
  45. // NetDial is nil, net.Dial is used.
  46. NetDial func(network, addr string) (net.Conn, error)
  47. // Proxy specifies a function to return a proxy for a given
  48. // Request. If the function returns a non-nil error, the
  49. // request is aborted with the provided error.
  50. // If Proxy is nil or returns a nil *URL, no proxy is used.
  51. Proxy func(*http.Request) (*url.URL, error)
  52. // TLSClientConfig specifies the TLS configuration to use with tls.Client.
  53. // If nil, the default configuration is used.
  54. TLSClientConfig *tls.Config
  55. // HandshakeTimeout specifies the duration for the handshake to complete.
  56. HandshakeTimeout time.Duration
  57. // ReadBufferSize and WriteBufferSize specify I/O buffer sizes. If a buffer
  58. // size is zero, then a useful default size is used. The I/O buffer sizes
  59. // do not limit the size of the messages that can be sent or received.
  60. ReadBufferSize, WriteBufferSize int
  61. // Subprotocols specifies the client's requested subprotocols.
  62. Subprotocols []string
  63. // EnableCompression specifies if the client should attempt to negotiate
  64. // per message compression (RFC 7692). Setting this value to true does not
  65. // guarantee that compression will be supported. Currently only "no context
  66. // takeover" modes are supported.
  67. EnableCompression bool
  68. // Jar specifies the cookie jar.
  69. // If Jar is nil, cookies are not sent in requests and ignored
  70. // in responses.
  71. Jar http.CookieJar
  72. }
  73. var errMalformedURL = errors.New("malformed ws or wss URL")
  74. func hostPortNoPort(u *url.URL) (hostPort, hostNoPort string) {
  75. hostPort = u.Host
  76. hostNoPort = u.Host
  77. if i := strings.LastIndex(u.Host, ":"); i > strings.LastIndex(u.Host, "]") {
  78. hostNoPort = hostNoPort[:i]
  79. } else {
  80. switch u.Scheme {
  81. case "wss":
  82. hostPort += ":443"
  83. case "https":
  84. hostPort += ":443"
  85. default:
  86. hostPort += ":80"
  87. }
  88. }
  89. return hostPort, hostNoPort
  90. }
  91. // DefaultDialer is a dialer with all fields set to the default values.
  92. var DefaultDialer = &Dialer{
  93. Proxy: http.ProxyFromEnvironment,
  94. HandshakeTimeout: 45 * time.Second,
  95. }
  96. // nilDialer is dialer to use when receiver is nil.
  97. var nilDialer Dialer = *DefaultDialer
  98. // Dial creates a new client connection. Use requestHeader to specify the
  99. // origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies (Cookie).
  100. // Use the response.Header to get the selected subprotocol
  101. // (Sec-WebSocket-Protocol) and cookies (Set-Cookie).
  102. //
  103. // If the WebSocket handshake fails, ErrBadHandshake is returned along with a
  104. // non-nil *http.Response so that callers can handle redirects, authentication,
  105. // etcetera. The response body may not contain the entire response and does not
  106. // need to be closed by the application.
  107. func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) {
  108. if d == nil {
  109. d = &nilDialer
  110. }
  111. challengeKey, err := generateChallengeKey()
  112. if err != nil {
  113. return nil, nil, err
  114. }
  115. u, err := url.Parse(urlStr)
  116. if err != nil {
  117. return nil, nil, err
  118. }
  119. switch u.Scheme {
  120. case "ws":
  121. u.Scheme = "http"
  122. case "wss":
  123. u.Scheme = "https"
  124. default:
  125. return nil, nil, errMalformedURL
  126. }
  127. if u.User != nil {
  128. // User name and password are not allowed in websocket URIs.
  129. return nil, nil, errMalformedURL
  130. }
  131. req := &http.Request{
  132. Method: "GET",
  133. URL: u,
  134. Proto: "HTTP/1.1",
  135. ProtoMajor: 1,
  136. ProtoMinor: 1,
  137. Header: make(http.Header),
  138. Host: u.Host,
  139. }
  140. // Set the cookies present in the cookie jar of the dialer
  141. if d.Jar != nil {
  142. for _, cookie := range d.Jar.Cookies(u) {
  143. req.AddCookie(cookie)
  144. }
  145. }
  146. // Set the request headers using the capitalization for names and values in
  147. // RFC examples. Although the capitalization shouldn't matter, there are
  148. // servers that depend on it. The Header.Set method is not used because the
  149. // method canonicalizes the header names.
  150. req.Header["Upgrade"] = []string{"websocket"}
  151. req.Header["Connection"] = []string{"Upgrade"}
  152. req.Header["Sec-WebSocket-Key"] = []string{challengeKey}
  153. req.Header["Sec-WebSocket-Version"] = []string{"13"}
  154. if len(d.Subprotocols) > 0 {
  155. req.Header["Sec-WebSocket-Protocol"] = []string{strings.Join(d.Subprotocols, ", ")}
  156. }
  157. for k, vs := range requestHeader {
  158. switch {
  159. case k == "Host":
  160. if len(vs) > 0 {
  161. req.Host = vs[0]
  162. }
  163. case k == "Upgrade" ||
  164. k == "Connection" ||
  165. k == "Sec-Websocket-Key" ||
  166. k == "Sec-Websocket-Version" ||
  167. k == "Sec-Websocket-Extensions" ||
  168. (k == "Sec-Websocket-Protocol" && len(d.Subprotocols) > 0):
  169. return nil, nil, errors.New("websocket: duplicate header not allowed: " + k)
  170. case k == "Sec-Websocket-Protocol":
  171. req.Header["Sec-WebSocket-Protocol"] = vs
  172. default:
  173. req.Header[k] = vs
  174. }
  175. }
  176. if d.EnableCompression {
  177. req.Header["Sec-WebSocket-Extensions"] = []string{"permessage-deflate; server_no_context_takeover; client_no_context_takeover"}
  178. }
  179. var deadline time.Time
  180. if d.HandshakeTimeout != 0 {
  181. deadline = time.Now().Add(d.HandshakeTimeout)
  182. }
  183. // Get network dial function.
  184. netDial := d.NetDial
  185. if netDial == nil {
  186. netDialer := &net.Dialer{Deadline: deadline}
  187. netDial = netDialer.Dial
  188. }
  189. // If needed, wrap the dial function to set the connection deadline.
  190. if !deadline.Equal(time.Time{}) {
  191. forwardDial := netDial
  192. netDial = func(network, addr string) (net.Conn, error) {
  193. c, err := forwardDial(network, addr)
  194. if err != nil {
  195. return nil, err
  196. }
  197. err = c.SetDeadline(deadline)
  198. if err != nil {
  199. c.Close()
  200. return nil, err
  201. }
  202. return c, nil
  203. }
  204. }
  205. // If needed, wrap the dial function to connect through a proxy.
  206. if d.Proxy != nil {
  207. proxyURL, err := d.Proxy(req)
  208. if err != nil {
  209. return nil, nil, err
  210. }
  211. if proxyURL != nil {
  212. dialer, err := proxy_FromURL(proxyURL, netDialerFunc(netDial))
  213. if err != nil {
  214. return nil, nil, err
  215. }
  216. netDial = dialer.Dial
  217. }
  218. }
  219. hostPort, hostNoPort := hostPortNoPort(u)
  220. netConn, err := netDial("tcp", hostPort)
  221. if err != nil {
  222. return nil, nil, err
  223. }
  224. defer func() {
  225. if netConn != nil {
  226. netConn.Close()
  227. }
  228. }()
  229. if u.Scheme == "https" {
  230. cfg := cloneTLSConfig(d.TLSClientConfig)
  231. if cfg.ServerName == "" {
  232. cfg.ServerName = hostNoPort
  233. }
  234. tlsConn := tls.Client(netConn, cfg)
  235. netConn = tlsConn
  236. if err := tlsConn.Handshake(); err != nil {
  237. return nil, nil, err
  238. }
  239. if !cfg.InsecureSkipVerify {
  240. if err := tlsConn.VerifyHostname(cfg.ServerName); err != nil {
  241. return nil, nil, err
  242. }
  243. }
  244. }
  245. conn := newConn(netConn, false, d.ReadBufferSize, d.WriteBufferSize)
  246. if err := req.Write(netConn); err != nil {
  247. return nil, nil, err
  248. }
  249. resp, err := http.ReadResponse(conn.br, req)
  250. if err != nil {
  251. return nil, nil, err
  252. }
  253. if d.Jar != nil {
  254. if rc := resp.Cookies(); len(rc) > 0 {
  255. d.Jar.SetCookies(u, rc)
  256. }
  257. }
  258. if resp.StatusCode != 101 ||
  259. !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
  260. !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
  261. resp.Header.Get("Sec-Websocket-Accept") != computeAcceptKey(challengeKey) {
  262. // Before closing the network connection on return from this
  263. // function, slurp up some of the response to aid application
  264. // debugging.
  265. buf := make([]byte, 1024)
  266. n, _ := io.ReadFull(resp.Body, buf)
  267. resp.Body = ioutil.NopCloser(bytes.NewReader(buf[:n]))
  268. return nil, resp, ErrBadHandshake
  269. }
  270. for _, ext := range parseExtensions(resp.Header) {
  271. if ext[""] != "permessage-deflate" {
  272. continue
  273. }
  274. _, snct := ext["server_no_context_takeover"]
  275. _, cnct := ext["client_no_context_takeover"]
  276. if !snct || !cnct {
  277. return nil, resp, errInvalidCompression
  278. }
  279. conn.newCompressionWriter = compressNoContextTakeover
  280. conn.newDecompressionReader = decompressNoContextTakeover
  281. break
  282. }
  283. resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
  284. conn.subprotocol = resp.Header.Get("Sec-Websocket-Protocol")
  285. netConn.SetDeadline(time.Time{})
  286. netConn = nil // to avoid close in defer.
  287. return conn, resp, nil
  288. }