client.go 11 KB

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