1
0

client.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. }
  95. // Dial creates a new client connection. Use requestHeader to specify the
  96. // origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies (Cookie).
  97. // Use the response.Header to get the selected subprotocol
  98. // (Sec-WebSocket-Protocol) and cookies (Set-Cookie).
  99. //
  100. // If the WebSocket handshake fails, ErrBadHandshake is returned along with a
  101. // non-nil *http.Response so that callers can handle redirects, authentication,
  102. // etcetera. The response body may not contain the entire response and does not
  103. // need to be closed by the application.
  104. func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) {
  105. if d == nil {
  106. d = &Dialer{
  107. Proxy: http.ProxyFromEnvironment,
  108. }
  109. }
  110. challengeKey, err := generateChallengeKey()
  111. if err != nil {
  112. return nil, nil, err
  113. }
  114. u, err := url.Parse(urlStr)
  115. if err != nil {
  116. return nil, nil, err
  117. }
  118. switch u.Scheme {
  119. case "ws":
  120. u.Scheme = "http"
  121. case "wss":
  122. u.Scheme = "https"
  123. default:
  124. return nil, nil, errMalformedURL
  125. }
  126. if u.User != nil {
  127. // User name and password are not allowed in websocket URIs.
  128. return nil, nil, errMalformedURL
  129. }
  130. req := &http.Request{
  131. Method: "GET",
  132. URL: u,
  133. Proto: "HTTP/1.1",
  134. ProtoMajor: 1,
  135. ProtoMinor: 1,
  136. Header: make(http.Header),
  137. Host: u.Host,
  138. }
  139. // Set the cookies present in the cookie jar of the dialer
  140. if d.Jar != nil {
  141. for _, cookie := range d.Jar.Cookies(u) {
  142. req.AddCookie(cookie)
  143. }
  144. }
  145. // Set the request headers using the capitalization for names and values in
  146. // RFC examples. Although the capitalization shouldn't matter, there are
  147. // servers that depend on it. The Header.Set method is not used because the
  148. // method canonicalizes the header names.
  149. req.Header["Upgrade"] = []string{"websocket"}
  150. req.Header["Connection"] = []string{"Upgrade"}
  151. req.Header["Sec-WebSocket-Key"] = []string{challengeKey}
  152. req.Header["Sec-WebSocket-Version"] = []string{"13"}
  153. if len(d.Subprotocols) > 0 {
  154. req.Header["Sec-WebSocket-Protocol"] = []string{strings.Join(d.Subprotocols, ", ")}
  155. }
  156. for k, vs := range requestHeader {
  157. switch {
  158. case k == "Host":
  159. if len(vs) > 0 {
  160. req.Host = vs[0]
  161. }
  162. case k == "Upgrade" ||
  163. k == "Connection" ||
  164. k == "Sec-Websocket-Key" ||
  165. k == "Sec-Websocket-Version" ||
  166. k == "Sec-Websocket-Extensions" ||
  167. (k == "Sec-Websocket-Protocol" && len(d.Subprotocols) > 0):
  168. return nil, nil, errors.New("websocket: duplicate header not allowed: " + k)
  169. default:
  170. req.Header[k] = vs
  171. }
  172. }
  173. if d.EnableCompression {
  174. req.Header.Set("Sec-Websocket-Extensions", "permessage-deflate; server_no_context_takeover; client_no_context_takeover")
  175. }
  176. var deadline time.Time
  177. if d.HandshakeTimeout != 0 {
  178. deadline = time.Now().Add(d.HandshakeTimeout)
  179. }
  180. // Get network dial function.
  181. netDial := d.NetDial
  182. if netDial == nil {
  183. netDialer := &net.Dialer{Deadline: deadline}
  184. netDial = netDialer.Dial
  185. }
  186. // If needed, wrap the dial function to set the connection deadline.
  187. if !deadline.Equal(time.Time{}) {
  188. forwardDial := netDial
  189. netDial = func(network, addr string) (net.Conn, error) {
  190. c, err := forwardDial(network, addr)
  191. if err != nil {
  192. return nil, err
  193. }
  194. err = c.SetDeadline(deadline)
  195. if err != nil {
  196. c.Close()
  197. return nil, err
  198. }
  199. return c, nil
  200. }
  201. }
  202. // If needed, wrap the dial function to connect through a proxy.
  203. if d.Proxy != nil {
  204. proxyURL, err := d.Proxy(req)
  205. if err != nil {
  206. return nil, nil, err
  207. }
  208. if proxyURL != nil {
  209. dialer, err := proxy_FromURL(proxyURL, netDialerFunc(netDial))
  210. if err != nil {
  211. return nil, nil, err
  212. }
  213. netDial = dialer.Dial
  214. }
  215. }
  216. hostPort, hostNoPort := hostPortNoPort(u)
  217. netConn, err := netDial("tcp", hostPort)
  218. if err != nil {
  219. return nil, nil, err
  220. }
  221. defer func() {
  222. if netConn != nil {
  223. netConn.Close()
  224. }
  225. }()
  226. if u.Scheme == "https" {
  227. cfg := cloneTLSConfig(d.TLSClientConfig)
  228. if cfg.ServerName == "" {
  229. cfg.ServerName = hostNoPort
  230. }
  231. tlsConn := tls.Client(netConn, cfg)
  232. netConn = tlsConn
  233. if err := tlsConn.Handshake(); err != nil {
  234. return nil, nil, err
  235. }
  236. if !cfg.InsecureSkipVerify {
  237. if err := tlsConn.VerifyHostname(cfg.ServerName); err != nil {
  238. return nil, nil, err
  239. }
  240. }
  241. }
  242. conn := newConn(netConn, false, d.ReadBufferSize, d.WriteBufferSize)
  243. if err := req.Write(netConn); err != nil {
  244. return nil, nil, err
  245. }
  246. resp, err := http.ReadResponse(conn.br, req)
  247. if err != nil {
  248. return nil, nil, err
  249. }
  250. if d.Jar != nil {
  251. if rc := resp.Cookies(); len(rc) > 0 {
  252. d.Jar.SetCookies(u, rc)
  253. }
  254. }
  255. if resp.StatusCode != 101 ||
  256. !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
  257. !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
  258. resp.Header.Get("Sec-Websocket-Accept") != computeAcceptKey(challengeKey) {
  259. // Before closing the network connection on return from this
  260. // function, slurp up some of the response to aid application
  261. // debugging.
  262. buf := make([]byte, 1024)
  263. n, _ := io.ReadFull(resp.Body, buf)
  264. resp.Body = ioutil.NopCloser(bytes.NewReader(buf[:n]))
  265. return nil, resp, ErrBadHandshake
  266. }
  267. for _, ext := range parseExtensions(resp.Header) {
  268. if ext[""] != "permessage-deflate" {
  269. continue
  270. }
  271. _, snct := ext["server_no_context_takeover"]
  272. _, cnct := ext["client_no_context_takeover"]
  273. if !snct || !cnct {
  274. return nil, resp, errInvalidCompression
  275. }
  276. conn.newCompressionWriter = compressNoContextTakeover
  277. conn.newDecompressionReader = decompressNoContextTakeover
  278. break
  279. }
  280. resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
  281. conn.subprotocol = resp.Header.Get("Sec-Websocket-Protocol")
  282. netConn.SetDeadline(time.Time{})
  283. netConn = nil // to avoid close in defer.
  284. return conn, resp, nil
  285. }