client.go 9.7 KB

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