client.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. "errors"
  10. "io"
  11. "io/ioutil"
  12. "net"
  13. "net/http"
  14. "net/url"
  15. "strings"
  16. "time"
  17. )
  18. // ErrBadHandshake is returned when the server response to opening handshake is
  19. // invalid.
  20. var ErrBadHandshake = errors.New("websocket: bad handshake")
  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. // Input and output buffer sizes. If the buffer size is zero, then a
  58. // default value of 4096 is used.
  59. ReadBufferSize, WriteBufferSize int
  60. // Subprotocols specifies the client's requested subprotocols.
  61. Subprotocols []string
  62. }
  63. var errMalformedURL = errors.New("malformed ws or wss URL")
  64. // parseURL parses the URL.
  65. //
  66. // This function is a replacement for the standard library url.Parse function.
  67. // In Go 1.4 and earlier, url.Parse loses information from the path.
  68. func parseURL(s string) (*url.URL, error) {
  69. // From the RFC:
  70. //
  71. // ws-URI = "ws:" "//" host [ ":" port ] path [ "?" query ]
  72. // wss-URI = "wss:" "//" host [ ":" port ] path [ "?" query ]
  73. var u url.URL
  74. switch {
  75. case strings.HasPrefix(s, "ws://"):
  76. u.Scheme = "ws"
  77. s = s[len("ws://"):]
  78. case strings.HasPrefix(s, "wss://"):
  79. u.Scheme = "wss"
  80. s = s[len("wss://"):]
  81. default:
  82. return nil, errMalformedURL
  83. }
  84. u.Host = s
  85. u.Opaque = "/"
  86. if i := strings.Index(s, "/"); i >= 0 {
  87. u.Host = s[:i]
  88. u.Opaque = s[i:]
  89. }
  90. if strings.Contains(u.Host, "@") {
  91. // Don't bother parsing user information because user information is
  92. // not allowed in websocket URIs.
  93. return nil, errMalformedURL
  94. }
  95. return &u, nil
  96. }
  97. func hostPortNoPort(u *url.URL) (hostPort, hostNoPort string) {
  98. hostPort = u.Host
  99. hostNoPort = u.Host
  100. if i := strings.LastIndex(u.Host, ":"); i > strings.LastIndex(u.Host, "]") {
  101. hostNoPort = hostNoPort[:i]
  102. } else {
  103. switch u.Scheme {
  104. case "wss":
  105. hostPort += ":443"
  106. case "https":
  107. hostPort += ":443"
  108. default:
  109. hostPort += ":80"
  110. }
  111. }
  112. return hostPort, hostNoPort
  113. }
  114. // DefaultDialer is a dialer with all fields set to the default zero values.
  115. var DefaultDialer = &Dialer{
  116. Proxy: http.ProxyFromEnvironment,
  117. }
  118. // Dial creates a new client connection. Use requestHeader to specify the
  119. // origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies (Cookie).
  120. // Use the response.Header to get the selected subprotocol
  121. // (Sec-WebSocket-Protocol) and cookies (Set-Cookie).
  122. //
  123. // If the WebSocket handshake fails, ErrBadHandshake is returned along with a
  124. // non-nil *http.Response so that callers can handle redirects, authentication,
  125. // etcetera. The response body may not contain the entire response and does not
  126. // need to be closed by the application.
  127. func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) {
  128. if d == nil {
  129. d = &Dialer{
  130. Proxy: http.ProxyFromEnvironment,
  131. }
  132. }
  133. challengeKey, err := generateChallengeKey()
  134. if err != nil {
  135. return nil, nil, err
  136. }
  137. u, err := parseURL(urlStr)
  138. if err != nil {
  139. return nil, nil, err
  140. }
  141. switch u.Scheme {
  142. case "ws":
  143. u.Scheme = "http"
  144. case "wss":
  145. u.Scheme = "https"
  146. default:
  147. return nil, nil, errMalformedURL
  148. }
  149. if u.User != nil {
  150. // User name and password are not allowed in websocket URIs.
  151. return nil, nil, errMalformedURL
  152. }
  153. req := &http.Request{
  154. Method: "GET",
  155. URL: u,
  156. Proto: "HTTP/1.1",
  157. ProtoMajor: 1,
  158. ProtoMinor: 1,
  159. Header: make(http.Header),
  160. Host: u.Host,
  161. }
  162. // Set the request headers using the capitalization for names and values in
  163. // RFC examples. Although the capitalization shouldn't matter, there are
  164. // servers that depend on it. The Header.Set method is not used because the
  165. // method canonicalizes the header names.
  166. req.Header["Upgrade"] = []string{"websocket"}
  167. req.Header["Connection"] = []string{"Upgrade"}
  168. req.Header["Sec-WebSocket-Key"] = []string{challengeKey}
  169. req.Header["Sec-WebSocket-Version"] = []string{"13"}
  170. if len(d.Subprotocols) > 0 {
  171. req.Header["Sec-WebSocket-Protocol"] = []string{strings.Join(d.Subprotocols, ", ")}
  172. }
  173. for k, vs := range requestHeader {
  174. switch {
  175. case k == "Host":
  176. if len(vs) > 0 {
  177. req.Host = vs[0]
  178. }
  179. case k == "Upgrade" ||
  180. k == "Connection" ||
  181. k == "Sec-Websocket-Key" ||
  182. k == "Sec-Websocket-Version" ||
  183. (k == "Sec-Websocket-Protocol" && len(d.Subprotocols) > 0):
  184. return nil, nil, errors.New("websocket: duplicate header not allowed: " + k)
  185. default:
  186. req.Header[k] = vs
  187. }
  188. }
  189. hostPort, hostNoPort := hostPortNoPort(u)
  190. var proxyURL *url.URL
  191. // Check wether the proxy method has been configured
  192. if d.Proxy != nil {
  193. proxyURL, err = d.Proxy(req)
  194. }
  195. if err != nil {
  196. return nil, nil, err
  197. }
  198. var targetHostPort string
  199. if proxyURL != nil {
  200. targetHostPort, _ = hostPortNoPort(proxyURL)
  201. } else {
  202. targetHostPort = hostPort
  203. }
  204. var deadline time.Time
  205. if d.HandshakeTimeout != 0 {
  206. deadline = time.Now().Add(d.HandshakeTimeout)
  207. }
  208. netDial := d.NetDial
  209. if netDial == nil {
  210. netDialer := &net.Dialer{Deadline: deadline}
  211. netDial = netDialer.Dial
  212. }
  213. netConn, err := netDial("tcp", targetHostPort)
  214. if err != nil {
  215. return nil, nil, err
  216. }
  217. defer func() {
  218. if netConn != nil {
  219. netConn.Close()
  220. }
  221. }()
  222. if err := netConn.SetDeadline(deadline); err != nil {
  223. return nil, nil, err
  224. }
  225. if proxyURL != nil {
  226. connectReq := &http.Request{
  227. Method: "CONNECT",
  228. URL: &url.URL{Opaque: hostPort},
  229. Host: hostPort,
  230. Header: make(http.Header),
  231. }
  232. connectReq.Write(netConn)
  233. // Read response.
  234. // Okay to use and discard buffered reader here, because
  235. // TLS server will not speak until spoken to.
  236. br := bufio.NewReader(netConn)
  237. resp, err := http.ReadResponse(br, connectReq)
  238. if err != nil {
  239. return nil, nil, err
  240. }
  241. if resp.StatusCode != 200 {
  242. f := strings.SplitN(resp.Status, " ", 2)
  243. return nil, nil, errors.New(f[1])
  244. }
  245. }
  246. if u.Scheme == "https" {
  247. cfg := d.TLSClientConfig
  248. if cfg == nil {
  249. cfg = &tls.Config{ServerName: hostNoPort}
  250. } else if cfg.ServerName == "" {
  251. shallowCopy := *cfg
  252. cfg = &shallowCopy
  253. cfg.ServerName = hostNoPort
  254. }
  255. tlsConn := tls.Client(netConn, cfg)
  256. netConn = tlsConn
  257. if err := tlsConn.Handshake(); err != nil {
  258. return nil, nil, err
  259. }
  260. if !cfg.InsecureSkipVerify {
  261. if err := tlsConn.VerifyHostname(cfg.ServerName); err != nil {
  262. return nil, nil, err
  263. }
  264. }
  265. }
  266. conn := newConn(netConn, false, d.ReadBufferSize, d.WriteBufferSize)
  267. if err := req.Write(netConn); err != nil {
  268. return nil, nil, err
  269. }
  270. resp, err := http.ReadResponse(conn.br, req)
  271. if err != nil {
  272. return nil, nil, err
  273. }
  274. if resp.StatusCode != 101 ||
  275. !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
  276. !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
  277. resp.Header.Get("Sec-Websocket-Accept") != computeAcceptKey(challengeKey) {
  278. // Before closing the network connection on return from this
  279. // function, slurp up some of the response to aid application
  280. // debugging.
  281. buf := make([]byte, 1024)
  282. n, _ := io.ReadFull(resp.Body, buf)
  283. resp.Body = ioutil.NopCloser(bytes.NewReader(buf[:n]))
  284. return nil, resp, ErrBadHandshake
  285. }
  286. resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
  287. conn.subprotocol = resp.Header.Get("Sec-Websocket-Protocol")
  288. netConn.SetDeadline(time.Time{})
  289. netConn = nil // to avoid close in defer.
  290. return conn, resp, nil
  291. }