client.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. // Input and output buffer sizes. If the buffer size is zero, then a
  60. // default value of 4096 is used.
  61. ReadBufferSize, WriteBufferSize int
  62. // Subprotocols specifies the client's requested subprotocols.
  63. Subprotocols []string
  64. // EnableCompression specifies if the client should attempt to negotiate
  65. // per message compression (RFC 7692). Setting this value to true does not
  66. // guarantee that compression will be supported. Currently only "no context
  67. // takeover" modes are supported.
  68. EnableCompression bool
  69. // Jar specifies the cookie jar.
  70. // If Jar is nil, cookies are not sent in requests and ignored
  71. // in responses.
  72. Jar http.CookieJar
  73. }
  74. var errMalformedURL = errors.New("malformed ws or wss URL")
  75. // parseURL parses the URL.
  76. //
  77. // This function is a replacement for the standard library url.Parse function.
  78. // In Go 1.4 and earlier, url.Parse loses information from the path.
  79. func parseURL(s string) (*url.URL, error) {
  80. // From the RFC:
  81. //
  82. // ws-URI = "ws:" "//" host [ ":" port ] path [ "?" query ]
  83. // wss-URI = "wss:" "//" host [ ":" port ] path [ "?" query ]
  84. var u url.URL
  85. switch {
  86. case strings.HasPrefix(s, "ws://"):
  87. u.Scheme = "ws"
  88. s = s[len("ws://"):]
  89. case strings.HasPrefix(s, "wss://"):
  90. u.Scheme = "wss"
  91. s = s[len("wss://"):]
  92. default:
  93. return nil, errMalformedURL
  94. }
  95. if i := strings.Index(s, "?"); i >= 0 {
  96. u.RawQuery = s[i+1:]
  97. s = s[:i]
  98. }
  99. if i := strings.Index(s, "/"); i >= 0 {
  100. u.Opaque = s[i:]
  101. s = s[:i]
  102. } else {
  103. u.Opaque = "/"
  104. }
  105. u.Host = s
  106. if strings.Contains(u.Host, "@") {
  107. // Don't bother parsing user information because user information is
  108. // not allowed in websocket URIs.
  109. return nil, errMalformedURL
  110. }
  111. return &u, nil
  112. }
  113. func hostPortNoPort(u *url.URL) (hostPort, hostNoPort string) {
  114. hostPort = u.Host
  115. hostNoPort = u.Host
  116. if i := strings.LastIndex(u.Host, ":"); i > strings.LastIndex(u.Host, "]") {
  117. hostNoPort = hostNoPort[:i]
  118. } else {
  119. switch u.Scheme {
  120. case "wss":
  121. hostPort += ":443"
  122. case "https":
  123. hostPort += ":443"
  124. default:
  125. hostPort += ":80"
  126. }
  127. }
  128. return hostPort, hostNoPort
  129. }
  130. // DefaultDialer is a dialer with all fields set to the default zero values.
  131. var DefaultDialer = &Dialer{
  132. Proxy: http.ProxyFromEnvironment,
  133. }
  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. if d == nil {
  145. d = &Dialer{
  146. Proxy: http.ProxyFromEnvironment,
  147. }
  148. }
  149. challengeKey, err := generateChallengeKey()
  150. if err != nil {
  151. return nil, nil, err
  152. }
  153. u, err := parseURL(urlStr)
  154. if err != nil {
  155. return nil, nil, err
  156. }
  157. switch u.Scheme {
  158. case "ws":
  159. u.Scheme = "http"
  160. case "wss":
  161. u.Scheme = "https"
  162. default:
  163. return nil, nil, errMalformedURL
  164. }
  165. if u.User != nil {
  166. // User name and password are not allowed in websocket URIs.
  167. return nil, nil, errMalformedURL
  168. }
  169. req := &http.Request{
  170. Method: "GET",
  171. URL: u,
  172. Proto: "HTTP/1.1",
  173. ProtoMajor: 1,
  174. ProtoMinor: 1,
  175. Header: make(http.Header),
  176. Host: u.Host,
  177. }
  178. // Set the cookies present in the cookie jar of the dialer
  179. if d.Jar != nil {
  180. for _, cookie := range d.Jar.Cookies(u) {
  181. req.AddCookie(cookie)
  182. }
  183. }
  184. // Set the request headers using the capitalization for names and values in
  185. // RFC examples. Although the capitalization shouldn't matter, there are
  186. // servers that depend on it. The Header.Set method is not used because the
  187. // method canonicalizes the header names.
  188. req.Header["Upgrade"] = []string{"websocket"}
  189. req.Header["Connection"] = []string{"Upgrade"}
  190. req.Header["Sec-WebSocket-Key"] = []string{challengeKey}
  191. req.Header["Sec-WebSocket-Version"] = []string{"13"}
  192. if len(d.Subprotocols) > 0 {
  193. req.Header["Sec-WebSocket-Protocol"] = []string{strings.Join(d.Subprotocols, ", ")}
  194. }
  195. for k, vs := range requestHeader {
  196. switch {
  197. case k == "Host":
  198. if len(vs) > 0 {
  199. req.Host = vs[0]
  200. }
  201. case k == "Upgrade" ||
  202. k == "Connection" ||
  203. k == "Sec-Websocket-Key" ||
  204. k == "Sec-Websocket-Version" ||
  205. k == "Sec-Websocket-Extensions" ||
  206. (k == "Sec-Websocket-Protocol" && len(d.Subprotocols) > 0):
  207. return nil, nil, errors.New("websocket: duplicate header not allowed: " + k)
  208. default:
  209. req.Header[k] = vs
  210. }
  211. }
  212. if d.EnableCompression {
  213. req.Header.Set("Sec-Websocket-Extensions", "permessage-deflate; server_no_context_takeover; client_no_context_takeover")
  214. }
  215. hostPort, hostNoPort := hostPortNoPort(u)
  216. var proxyURL *url.URL
  217. // Check wether the proxy method has been configured
  218. if d.Proxy != nil {
  219. proxyURL, err = d.Proxy(req)
  220. }
  221. if err != nil {
  222. return nil, nil, err
  223. }
  224. var targetHostPort string
  225. if proxyURL != nil {
  226. targetHostPort, _ = hostPortNoPort(proxyURL)
  227. } else {
  228. targetHostPort = hostPort
  229. }
  230. var deadline time.Time
  231. if d.HandshakeTimeout != 0 {
  232. deadline = time.Now().Add(d.HandshakeTimeout)
  233. }
  234. netDial := d.NetDial
  235. if netDial == nil {
  236. netDialer := &net.Dialer{Deadline: deadline}
  237. netDial = netDialer.Dial
  238. }
  239. netConn, err := netDial("tcp", targetHostPort)
  240. if err != nil {
  241. return nil, nil, err
  242. }
  243. defer func() {
  244. if netConn != nil {
  245. netConn.Close()
  246. }
  247. }()
  248. if err := netConn.SetDeadline(deadline); err != nil {
  249. return nil, nil, err
  250. }
  251. if proxyURL != nil {
  252. connectHeader := make(http.Header)
  253. if user := proxyURL.User; user != nil {
  254. proxyUser := user.Username()
  255. if proxyPassword, passwordSet := user.Password(); passwordSet {
  256. credential := base64.StdEncoding.EncodeToString([]byte(proxyUser + ":" + proxyPassword))
  257. connectHeader.Set("Proxy-Authorization", "Basic "+credential)
  258. }
  259. }
  260. connectReq := &http.Request{
  261. Method: "CONNECT",
  262. URL: &url.URL{Opaque: hostPort},
  263. Host: hostPort,
  264. Header: connectHeader,
  265. }
  266. connectReq.Write(netConn)
  267. // Read response.
  268. // Okay to use and discard buffered reader here, because
  269. // TLS server will not speak until spoken to.
  270. br := bufio.NewReader(netConn)
  271. resp, err := http.ReadResponse(br, connectReq)
  272. if err != nil {
  273. return nil, nil, err
  274. }
  275. if resp.StatusCode != 200 {
  276. f := strings.SplitN(resp.Status, " ", 2)
  277. return nil, nil, errors.New(f[1])
  278. }
  279. }
  280. if u.Scheme == "https" {
  281. cfg := cloneTLSConfig(d.TLSClientConfig)
  282. if cfg.ServerName == "" {
  283. cfg.ServerName = hostNoPort
  284. }
  285. tlsConn := tls.Client(netConn, cfg)
  286. netConn = tlsConn
  287. if err := tlsConn.Handshake(); err != nil {
  288. return nil, nil, err
  289. }
  290. if !cfg.InsecureSkipVerify {
  291. if err := tlsConn.VerifyHostname(cfg.ServerName); err != nil {
  292. return nil, nil, err
  293. }
  294. }
  295. }
  296. conn := newConn(netConn, false, d.ReadBufferSize, d.WriteBufferSize)
  297. if err := req.Write(netConn); err != nil {
  298. return nil, nil, err
  299. }
  300. resp, err := http.ReadResponse(conn.br, req)
  301. if err != nil {
  302. return nil, nil, err
  303. }
  304. if d.Jar != nil {
  305. if rc := resp.Cookies(); len(rc) > 0 {
  306. d.Jar.SetCookies(u, rc)
  307. }
  308. }
  309. if resp.StatusCode != 101 ||
  310. !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
  311. !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
  312. resp.Header.Get("Sec-Websocket-Accept") != computeAcceptKey(challengeKey) {
  313. // Before closing the network connection on return from this
  314. // function, slurp up some of the response to aid application
  315. // debugging.
  316. buf := make([]byte, 1024)
  317. n, _ := io.ReadFull(resp.Body, buf)
  318. resp.Body = ioutil.NopCloser(bytes.NewReader(buf[:n]))
  319. return nil, resp, ErrBadHandshake
  320. }
  321. for _, ext := range parseExtensions(req.Header) {
  322. if ext[""] != "permessage-deflate" {
  323. continue
  324. }
  325. _, snct := ext["server_no_context_takeover"]
  326. _, cnct := ext["client_no_context_takeover"]
  327. if !snct || !cnct {
  328. return nil, resp, errInvalidCompression
  329. }
  330. conn.newCompressionWriter = compressNoContextTakeover
  331. conn.newDecompressionReader = decompressNoContextTakeover
  332. break
  333. }
  334. resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
  335. conn.subprotocol = resp.Header.Get("Sec-Websocket-Protocol")
  336. netConn.SetDeadline(time.Time{})
  337. netConn = nil // to avoid close in defer.
  338. return conn, resp, nil
  339. }