client.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. if k == "Host" {
  175. if len(vs) > 0 {
  176. req.Host = vs[0]
  177. }
  178. } else {
  179. req.Header[k] = vs
  180. }
  181. }
  182. hostPort, hostNoPort := hostPortNoPort(u)
  183. var proxyURL *url.URL
  184. // Check wether the proxy method has been configured
  185. if d.Proxy != nil {
  186. proxyURL, err = d.Proxy(req)
  187. }
  188. if err != nil {
  189. return nil, nil, err
  190. }
  191. var targetHostPort string
  192. if proxyURL != nil {
  193. targetHostPort, _ = hostPortNoPort(proxyURL)
  194. } else {
  195. targetHostPort = hostPort
  196. }
  197. var deadline time.Time
  198. if d.HandshakeTimeout != 0 {
  199. deadline = time.Now().Add(d.HandshakeTimeout)
  200. }
  201. netDial := d.NetDial
  202. if netDial == nil {
  203. netDialer := &net.Dialer{Deadline: deadline}
  204. netDial = netDialer.Dial
  205. }
  206. netConn, err := netDial("tcp", targetHostPort)
  207. if err != nil {
  208. return nil, nil, err
  209. }
  210. defer func() {
  211. if netConn != nil {
  212. netConn.Close()
  213. }
  214. }()
  215. if err := netConn.SetDeadline(deadline); err != nil {
  216. return nil, nil, err
  217. }
  218. if proxyURL != nil {
  219. connectReq := &http.Request{
  220. Method: "CONNECT",
  221. URL: &url.URL{Opaque: hostPort},
  222. Host: hostPort,
  223. Header: make(http.Header),
  224. }
  225. connectReq.Write(netConn)
  226. // Read response.
  227. // Okay to use and discard buffered reader here, because
  228. // TLS server will not speak until spoken to.
  229. br := bufio.NewReader(netConn)
  230. resp, err := http.ReadResponse(br, connectReq)
  231. if err != nil {
  232. return nil, nil, err
  233. }
  234. if resp.StatusCode != 200 {
  235. f := strings.SplitN(resp.Status, " ", 2)
  236. return nil, nil, errors.New(f[1])
  237. }
  238. }
  239. if u.Scheme == "https" {
  240. cfg := d.TLSClientConfig
  241. if cfg == nil {
  242. cfg = &tls.Config{ServerName: hostNoPort}
  243. } else if cfg.ServerName == "" {
  244. shallowCopy := *cfg
  245. cfg = &shallowCopy
  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 resp.StatusCode != 101 ||
  268. !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
  269. !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
  270. resp.Header.Get("Sec-Websocket-Accept") != computeAcceptKey(challengeKey) {
  271. // Before closing the network connection on return from this
  272. // function, slurp up some of the response to aid application
  273. // debugging.
  274. buf := make([]byte, 1024)
  275. n, _ := io.ReadFull(resp.Body, buf)
  276. resp.Body = ioutil.NopCloser(bytes.NewReader(buf[:n]))
  277. return nil, resp, ErrBadHandshake
  278. }
  279. resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
  280. conn.subprotocol = resp.Header.Get("Sec-Websocket-Protocol")
  281. netConn.SetDeadline(time.Time{})
  282. netConn = nil // to avoid close in defer.
  283. return conn, resp, nil
  284. }