1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/websockets/websocket_basic_handshake_stream.h"
13 #include "base/base64.h"
14 #include "base/basictypes.h"
15 #include "base/bind.h"
16 #include "base/compiler_specific.h"
17 #include "base/containers/hash_tables.h"
18 #include "base/logging.h"
19 #include "base/metrics/histogram_macros.h"
20 #include "base/metrics/sparse_histogram.h"
21 #include "base/stl_util.h"
22 #include "base/strings/string_number_conversions.h"
23 #include "base/strings/string_piece.h"
24 #include "base/strings/string_util.h"
25 #include "base/strings/stringprintf.h"
26 #include "base/time/time.h"
27 #include "crypto/random.h"
28 #include "net/base/io_buffer.h"
29 #include "net/http/http_request_headers.h"
30 #include "net/http/http_request_info.h"
31 #include "net/http/http_response_body_drainer.h"
32 #include "net/http/http_response_headers.h"
33 #include "net/http/http_status_code.h"
34 #include "net/http/http_stream_parser.h"
35 #include "net/socket/client_socket_handle.h"
36 #include "net/socket/websocket_transport_client_socket_pool.h"
37 #include "net/websockets/websocket_basic_stream.h"
38 #include "net/websockets/websocket_deflate_predictor.h"
39 #include "net/websockets/websocket_deflate_predictor_impl.h"
40 #include "net/websockets/websocket_deflate_stream.h"
41 #include "net/websockets/websocket_deflater.h"
42 #include "net/websockets/websocket_extension_parser.h"
43 #include "net/websockets/websocket_handshake_challenge.h"
44 #include "net/websockets/websocket_handshake_constants.h"
45 #include "net/websockets/websocket_handshake_request_info.h"
46 #include "net/websockets/websocket_handshake_response_info.h"
47 #include "net/websockets/websocket_stream.h"
53 const char kConnectionErrorStatusLine
[] = "HTTP/1.1 503 Connection Error";
57 // TODO(ricea): If more extensions are added, replace this with a more general
59 struct WebSocketExtensionParams
{
60 WebSocketExtensionParams()
61 : deflate_enabled(false),
62 client_window_bits(15),
63 deflate_mode(WebSocketDeflater::TAKE_OVER_CONTEXT
) {}
66 int client_window_bits
;
67 WebSocketDeflater::ContextTakeOverMode deflate_mode
;
72 enum GetHeaderResult
{
78 std::string
MissingHeaderMessage(const std::string
& header_name
) {
79 return std::string("'") + header_name
+ "' header is missing";
82 std::string
MultipleHeaderValuesMessage(const std::string
& header_name
) {
86 "' header must not appear more than once in a response";
89 std::string
GenerateHandshakeChallenge() {
90 std::string
raw_challenge(websockets::kRawChallengeLength
, '\0');
91 crypto::RandBytes(string_as_array(&raw_challenge
), raw_challenge
.length());
92 std::string encoded_challenge
;
93 base::Base64Encode(raw_challenge
, &encoded_challenge
);
94 return encoded_challenge
;
97 void AddVectorHeaderIfNonEmpty(const char* name
,
98 const std::vector
<std::string
>& value
,
99 HttpRequestHeaders
* headers
) {
102 headers
->SetHeader(name
, base::JoinString(value
, ", "));
105 GetHeaderResult
GetSingleHeaderValue(const HttpResponseHeaders
* headers
,
106 const base::StringPiece
& name
,
107 std::string
* value
) {
108 void* state
= nullptr;
109 size_t num_values
= 0;
110 std::string temp_value
;
111 while (headers
->EnumerateHeader(&state
, name
, &temp_value
)) {
112 if (++num_values
> 1)
113 return GET_HEADER_MULTIPLE
;
116 return num_values
> 0 ? GET_HEADER_OK
: GET_HEADER_MISSING
;
119 bool ValidateHeaderHasSingleValue(GetHeaderResult result
,
120 const std::string
& header_name
,
121 std::string
* failure_message
) {
122 if (result
== GET_HEADER_MISSING
) {
123 *failure_message
= MissingHeaderMessage(header_name
);
126 if (result
== GET_HEADER_MULTIPLE
) {
127 *failure_message
= MultipleHeaderValuesMessage(header_name
);
130 DCHECK_EQ(result
, GET_HEADER_OK
);
134 bool ValidateUpgrade(const HttpResponseHeaders
* headers
,
135 std::string
* failure_message
) {
137 GetHeaderResult result
=
138 GetSingleHeaderValue(headers
, websockets::kUpgrade
, &value
);
139 if (!ValidateHeaderHasSingleValue(result
,
140 websockets::kUpgrade
,
145 if (!base::LowerCaseEqualsASCII(value
, websockets::kWebSocketLowercase
)) {
147 "'Upgrade' header value is not 'WebSocket': " + value
;
153 bool ValidateSecWebSocketAccept(const HttpResponseHeaders
* headers
,
154 const std::string
& expected
,
155 std::string
* failure_message
) {
157 GetHeaderResult result
=
158 GetSingleHeaderValue(headers
, websockets::kSecWebSocketAccept
, &actual
);
159 if (!ValidateHeaderHasSingleValue(result
,
160 websockets::kSecWebSocketAccept
,
165 if (expected
!= actual
) {
166 *failure_message
= "Incorrect 'Sec-WebSocket-Accept' header value";
172 bool ValidateConnection(const HttpResponseHeaders
* headers
,
173 std::string
* failure_message
) {
174 // Connection header is permitted to contain other tokens.
175 if (!headers
->HasHeader(HttpRequestHeaders::kConnection
)) {
176 *failure_message
= MissingHeaderMessage(HttpRequestHeaders::kConnection
);
179 if (!headers
->HasHeaderValue(HttpRequestHeaders::kConnection
,
180 websockets::kUpgrade
)) {
181 *failure_message
= "'Connection' header value must contain 'Upgrade'";
187 bool ValidateSubProtocol(
188 const HttpResponseHeaders
* headers
,
189 const std::vector
<std::string
>& requested_sub_protocols
,
190 std::string
* sub_protocol
,
191 std::string
* failure_message
) {
192 void* state
= nullptr;
194 base::hash_set
<std::string
> requested_set(requested_sub_protocols
.begin(),
195 requested_sub_protocols
.end());
197 bool has_multiple_protocols
= false;
198 bool has_invalid_protocol
= false;
200 while (!has_invalid_protocol
|| !has_multiple_protocols
) {
201 std::string temp_value
;
202 if (!headers
->EnumerateHeader(
203 &state
, websockets::kSecWebSocketProtocol
, &temp_value
))
206 if (requested_set
.count(value
) == 0)
207 has_invalid_protocol
= true;
209 has_multiple_protocols
= true;
212 if (has_multiple_protocols
) {
214 MultipleHeaderValuesMessage(websockets::kSecWebSocketProtocol
);
216 } else if (count
> 0 && requested_sub_protocols
.size() == 0) {
218 std::string("Response must not include 'Sec-WebSocket-Protocol' "
219 "header if not present in request: ")
222 } else if (has_invalid_protocol
) {
224 "'Sec-WebSocket-Protocol' header value '" +
226 "' in response does not match any of sent values";
228 } else if (requested_sub_protocols
.size() > 0 && count
== 0) {
230 "Sent non-empty 'Sec-WebSocket-Protocol' header "
231 "but no response was received";
234 *sub_protocol
= value
;
238 bool DeflateError(std::string
* message
, const base::StringPiece
& piece
) {
239 *message
= "Error in permessage-deflate: ";
240 piece
.AppendToString(message
);
244 bool ValidatePerMessageDeflateExtension(const WebSocketExtension
& extension
,
245 std::string
* failure_message
,
246 WebSocketExtensionParams
* params
) {
247 static const char kClientPrefix
[] = "client_";
248 static const char kServerPrefix
[] = "server_";
249 static const char kNoContextTakeover
[] = "no_context_takeover";
250 static const char kMaxWindowBits
[] = "max_window_bits";
251 const size_t kPrefixLen
= arraysize(kClientPrefix
) - 1;
252 static_assert(kPrefixLen
== arraysize(kServerPrefix
) - 1,
253 "the strings server and client must be the same length");
254 typedef std::vector
<WebSocketExtension::Parameter
> ParameterVector
;
256 DCHECK_EQ("permessage-deflate", extension
.name());
257 const ParameterVector
& parameters
= extension
.parameters();
258 std::set
<std::string
> seen_names
;
259 for (ParameterVector::const_iterator it
= parameters
.begin();
260 it
!= parameters
.end(); ++it
) {
261 const std::string
& name
= it
->name();
262 if (seen_names
.count(name
) != 0) {
265 "Received duplicate permessage-deflate extension parameter " + name
);
267 seen_names
.insert(name
);
268 const std::string
client_or_server(name
, 0, kPrefixLen
);
269 const bool is_client
= (client_or_server
== kClientPrefix
);
270 if (!is_client
&& client_or_server
!= kServerPrefix
) {
273 "Received an unexpected permessage-deflate extension parameter");
275 const std::string
rest(name
, kPrefixLen
);
276 if (rest
== kNoContextTakeover
) {
277 if (it
->HasValue()) {
278 return DeflateError(failure_message
,
279 "Received invalid " + name
+ " parameter");
282 params
->deflate_mode
= WebSocketDeflater::DO_NOT_TAKE_OVER_CONTEXT
;
283 } else if (rest
== kMaxWindowBits
) {
285 return DeflateError(failure_message
, name
+ " must have value");
287 if (!base::StringToInt(it
->value(), &bits
) || bits
< 8 || bits
> 15 ||
288 it
->value()[0] == '0' ||
289 it
->value().find_first_not_of("0123456789") != std::string::npos
) {
290 return DeflateError(failure_message
,
291 "Received invalid " + name
+ " parameter");
294 params
->client_window_bits
= bits
;
298 "Received an unexpected permessage-deflate extension parameter");
301 params
->deflate_enabled
= true;
305 bool ValidateExtensions(const HttpResponseHeaders
* headers
,
306 std::string
* accepted_extensions_descriptor
,
307 std::string
* failure_message
,
308 WebSocketExtensionParams
* params
) {
309 void* state
= nullptr;
310 std::string header_value
;
311 std::vector
<std::string
> header_values
;
312 // TODO(ricea): If adding support for additional extensions, generalise this
314 bool seen_permessage_deflate
= false;
315 while (headers
->EnumerateHeader(&state
, websockets::kSecWebSocketExtensions
,
317 WebSocketExtensionParser parser
;
318 if (!parser
.Parse(header_value
)) {
319 // TODO(yhirano) Set appropriate failure message.
321 "'Sec-WebSocket-Extensions' header value is "
322 "rejected by the parser: " +
327 const std::vector
<WebSocketExtension
>& extensions
= parser
.extensions();
328 for (const auto& extension
: extensions
) {
329 if (extension
.name() == "permessage-deflate") {
330 if (seen_permessage_deflate
) {
331 *failure_message
= "Received duplicate permessage-deflate response";
334 seen_permessage_deflate
= true;
336 if (!ValidatePerMessageDeflateExtension(extension
, failure_message
,
340 header_values
.push_back(header_value
);
342 *failure_message
= "Found an unsupported extension '" +
344 "' in 'Sec-WebSocket-Extensions' header";
349 *accepted_extensions_descriptor
= base::JoinString(header_values
, ", ");
355 WebSocketBasicHandshakeStream::WebSocketBasicHandshakeStream(
356 scoped_ptr
<ClientSocketHandle
> connection
,
357 WebSocketStream::ConnectDelegate
* connect_delegate
,
359 std::vector
<std::string
> requested_sub_protocols
,
360 std::vector
<std::string
> requested_extensions
,
361 std::string
* failure_message
)
362 : state_(connection
.release(), using_proxy
),
363 connect_delegate_(connect_delegate
),
364 http_response_info_(nullptr),
365 requested_sub_protocols_(requested_sub_protocols
),
366 requested_extensions_(requested_extensions
),
367 failure_message_(failure_message
) {
368 DCHECK(connect_delegate
);
369 DCHECK(failure_message
);
372 WebSocketBasicHandshakeStream::~WebSocketBasicHandshakeStream() {}
374 int WebSocketBasicHandshakeStream::InitializeStream(
375 const HttpRequestInfo
* request_info
,
376 RequestPriority priority
,
377 const BoundNetLog
& net_log
,
378 const CompletionCallback
& callback
) {
379 url_
= request_info
->url
;
380 state_
.Initialize(request_info
, priority
, net_log
, callback
);
384 int WebSocketBasicHandshakeStream::SendRequest(
385 const HttpRequestHeaders
& headers
,
386 HttpResponseInfo
* response
,
387 const CompletionCallback
& callback
) {
388 DCHECK(!headers
.HasHeader(websockets::kSecWebSocketKey
));
389 DCHECK(!headers
.HasHeader(websockets::kSecWebSocketProtocol
));
390 DCHECK(!headers
.HasHeader(websockets::kSecWebSocketExtensions
));
391 DCHECK(headers
.HasHeader(HttpRequestHeaders::kOrigin
));
392 DCHECK(headers
.HasHeader(websockets::kUpgrade
));
393 DCHECK(headers
.HasHeader(HttpRequestHeaders::kConnection
));
394 DCHECK(headers
.HasHeader(websockets::kSecWebSocketVersion
));
397 http_response_info_
= response
;
399 // Create a copy of the headers object, so that we can add the
400 // Sec-WebSockey-Key header.
401 HttpRequestHeaders enriched_headers
;
402 enriched_headers
.CopyFrom(headers
);
403 std::string handshake_challenge
;
404 if (handshake_challenge_for_testing_
) {
405 handshake_challenge
= *handshake_challenge_for_testing_
;
406 handshake_challenge_for_testing_
.reset();
408 handshake_challenge
= GenerateHandshakeChallenge();
410 enriched_headers
.SetHeader(websockets::kSecWebSocketKey
, handshake_challenge
);
412 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketExtensions
,
413 requested_extensions_
,
415 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketProtocol
,
416 requested_sub_protocols_
,
419 handshake_challenge_response_
=
420 ComputeSecWebSocketAccept(handshake_challenge
);
422 DCHECK(connect_delegate_
);
423 scoped_ptr
<WebSocketHandshakeRequestInfo
> request(
424 new WebSocketHandshakeRequestInfo(url_
, base::Time::Now()));
425 request
->headers
.CopyFrom(enriched_headers
);
426 connect_delegate_
->OnStartOpeningHandshake(request
.Pass());
428 return parser()->SendRequest(
429 state_
.GenerateRequestLine(), enriched_headers
, response
, callback
);
432 int WebSocketBasicHandshakeStream::ReadResponseHeaders(
433 const CompletionCallback
& callback
) {
434 // HttpStreamParser uses a weak pointer when reading from the
435 // socket, so it won't be called back after being destroyed. The
436 // HttpStreamParser is owned by HttpBasicState which is owned by this object,
437 // so this use of base::Unretained() is safe.
438 int rv
= parser()->ReadResponseHeaders(
439 base::Bind(&WebSocketBasicHandshakeStream::ReadResponseHeadersCallback
,
440 base::Unretained(this),
442 if (rv
== ERR_IO_PENDING
)
444 return ValidateResponse(rv
);
447 int WebSocketBasicHandshakeStream::ReadResponseBody(
450 const CompletionCallback
& callback
) {
451 return parser()->ReadResponseBody(buf
, buf_len
, callback
);
454 void WebSocketBasicHandshakeStream::Close(bool not_reusable
) {
455 // This class ignores the value of |not_reusable| and never lets the socket be
458 parser()->Close(true);
461 bool WebSocketBasicHandshakeStream::IsResponseBodyComplete() const {
462 return parser()->IsResponseBodyComplete();
465 bool WebSocketBasicHandshakeStream::IsConnectionReused() const {
466 return parser()->IsConnectionReused();
469 void WebSocketBasicHandshakeStream::SetConnectionReused() {
470 parser()->SetConnectionReused();
473 bool WebSocketBasicHandshakeStream::CanReuseConnection() const {
477 int64
WebSocketBasicHandshakeStream::GetTotalReceivedBytes() const {
481 int64_t WebSocketBasicHandshakeStream::GetTotalSentBytes() const {
485 bool WebSocketBasicHandshakeStream::GetLoadTimingInfo(
486 LoadTimingInfo
* load_timing_info
) const {
487 return state_
.connection()->GetLoadTimingInfo(IsConnectionReused(),
491 void WebSocketBasicHandshakeStream::GetSSLInfo(SSLInfo
* ssl_info
) {
492 parser()->GetSSLInfo(ssl_info
);
495 void WebSocketBasicHandshakeStream::GetSSLCertRequestInfo(
496 SSLCertRequestInfo
* cert_request_info
) {
497 parser()->GetSSLCertRequestInfo(cert_request_info
);
500 void WebSocketBasicHandshakeStream::Drain(HttpNetworkSession
* session
) {
501 HttpResponseBodyDrainer
* drainer
= new HttpResponseBodyDrainer(this);
502 drainer
->Start(session
);
503 // |drainer| will delete itself.
506 void WebSocketBasicHandshakeStream::SetPriority(RequestPriority priority
) {
507 // TODO(ricea): See TODO comment in HttpBasicStream::SetPriority(). If it is
508 // gone, then copy whatever has happened there over here.
511 UploadProgress
WebSocketBasicHandshakeStream::GetUploadProgress() const {
512 return UploadProgress();
515 HttpStream
* WebSocketBasicHandshakeStream::RenewStreamForAuth() {
516 // Return null because we don't support renewing the stream.
520 scoped_ptr
<WebSocketStream
> WebSocketBasicHandshakeStream::Upgrade() {
521 // The HttpStreamParser object has a pointer to our ClientSocketHandle. Make
522 // sure it does not touch it again before it is destroyed.
523 state_
.DeleteParser();
524 WebSocketTransportClientSocketPool::UnlockEndpoint(state_
.connection());
525 scoped_ptr
<WebSocketStream
> basic_stream(
526 new WebSocketBasicStream(state_
.ReleaseConnection(),
530 DCHECK(extension_params_
.get());
531 if (extension_params_
->deflate_enabled
) {
532 UMA_HISTOGRAM_ENUMERATION(
533 "Net.WebSocket.DeflateMode",
534 extension_params_
->deflate_mode
,
535 WebSocketDeflater::NUM_CONTEXT_TAKEOVER_MODE_TYPES
);
537 return scoped_ptr
<WebSocketStream
>(
538 new WebSocketDeflateStream(basic_stream
.Pass(),
539 extension_params_
->deflate_mode
,
540 extension_params_
->client_window_bits
,
541 scoped_ptr
<WebSocketDeflatePredictor
>(
542 new WebSocketDeflatePredictorImpl
)));
544 return basic_stream
.Pass();
548 void WebSocketBasicHandshakeStream::SetWebSocketKeyForTesting(
549 const std::string
& key
) {
550 handshake_challenge_for_testing_
.reset(new std::string(key
));
553 void WebSocketBasicHandshakeStream::ReadResponseHeadersCallback(
554 const CompletionCallback
& callback
,
556 callback
.Run(ValidateResponse(result
));
559 void WebSocketBasicHandshakeStream::OnFinishOpeningHandshake() {
560 DCHECK(http_response_info_
);
561 WebSocketDispatchOnFinishOpeningHandshake(connect_delegate_
,
563 http_response_info_
->headers
,
564 http_response_info_
->response_time
);
567 int WebSocketBasicHandshakeStream::ValidateResponse(int rv
) {
568 DCHECK(http_response_info_
);
569 // Most net errors happen during connection, so they are not seen by this
570 // method. The histogram for error codes is created in
571 // Delegate::OnResponseStarted in websocket_stream.cc instead.
573 const HttpResponseHeaders
* headers
= http_response_info_
->headers
.get();
574 const int response_code
= headers
->response_code();
575 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.WebSocket.ResponseCode", response_code
);
576 switch (response_code
) {
577 case HTTP_SWITCHING_PROTOCOLS
:
578 OnFinishOpeningHandshake();
579 return ValidateUpgradeResponse(headers
);
581 // We need to pass these through for authentication to work.
582 case HTTP_UNAUTHORIZED
:
583 case HTTP_PROXY_AUTHENTICATION_REQUIRED
:
586 // Other status codes are potentially risky (see the warnings in the
587 // WHATWG WebSocket API spec) and so are dropped by default.
589 // A WebSocket server cannot be using HTTP/0.9, so if we see version
590 // 0.9, it means the response was garbage.
591 // Reporting "Unexpected response code: 200" in this case is not
592 // helpful, so use a different error message.
593 if (headers
->GetHttpVersion() == HttpVersion(0, 9)) {
595 "Error during WebSocket handshake: Invalid status line");
597 set_failure_message(base::StringPrintf(
598 "Error during WebSocket handshake: Unexpected response code: %d",
599 headers
->response_code()));
601 OnFinishOpeningHandshake();
602 return ERR_INVALID_RESPONSE
;
605 if (rv
== ERR_EMPTY_RESPONSE
) {
607 "Connection closed before receiving a handshake response");
610 set_failure_message(std::string("Error during WebSocket handshake: ") +
612 OnFinishOpeningHandshake();
613 // Some error codes (for example ERR_CONNECTION_CLOSED) get changed to OK at
614 // higher levels. To prevent an unvalidated connection getting erroneously
615 // upgraded, don't pass through the status code unchanged if it is
616 // HTTP_SWITCHING_PROTOCOLS.
617 if (http_response_info_
->headers
&&
618 http_response_info_
->headers
->response_code() ==
619 HTTP_SWITCHING_PROTOCOLS
) {
620 http_response_info_
->headers
->ReplaceStatusLine(
621 kConnectionErrorStatusLine
);
627 int WebSocketBasicHandshakeStream::ValidateUpgradeResponse(
628 const HttpResponseHeaders
* headers
) {
629 extension_params_
.reset(new WebSocketExtensionParams
);
630 std::string failure_message
;
631 if (ValidateUpgrade(headers
, &failure_message
) &&
632 ValidateSecWebSocketAccept(
633 headers
, handshake_challenge_response_
, &failure_message
) &&
634 ValidateConnection(headers
, &failure_message
) &&
635 ValidateSubProtocol(headers
,
636 requested_sub_protocols_
,
639 ValidateExtensions(headers
,
642 extension_params_
.get())) {
645 set_failure_message("Error during WebSocket handshake: " + failure_message
);
646 return ERR_INVALID_RESPONSE
;
649 void WebSocketBasicHandshakeStream::set_failure_message(
650 const std::string
& failure_message
) {
651 *failure_message_
= failure_message
;