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