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_parameters.h"
39 #include "net/websockets/websocket_deflate_predictor.h"
40 #include "net/websockets/websocket_deflate_predictor_impl.h"
41 #include "net/websockets/websocket_deflate_stream.h"
42 #include "net/websockets/websocket_deflater.h"
43 #include "net/websockets/websocket_extension_parser.h"
44 #include "net/websockets/websocket_handshake_challenge.h"
45 #include "net/websockets/websocket_handshake_constants.h"
46 #include "net/websockets/websocket_handshake_request_info.h"
47 #include "net/websockets/websocket_handshake_response_info.h"
48 #include "net/websockets/websocket_stream.h"
54 const char kConnectionErrorStatusLine
[] = "HTTP/1.1 503 Connection Error";
58 // TODO(ricea): If more extensions are added, replace this with a more general
60 struct WebSocketExtensionParams
{
61 bool deflate_enabled
= false;
62 WebSocketDeflateParameters deflate_parameters
;
67 enum GetHeaderResult
{
73 std::string
MissingHeaderMessage(const std::string
& header_name
) {
74 return std::string("'") + header_name
+ "' header is missing";
77 std::string
MultipleHeaderValuesMessage(const std::string
& header_name
) {
81 "' header must not appear more than once in a response";
84 std::string
GenerateHandshakeChallenge() {
85 std::string
raw_challenge(websockets::kRawChallengeLength
, '\0');
86 crypto::RandBytes(string_as_array(&raw_challenge
), raw_challenge
.length());
87 std::string encoded_challenge
;
88 base::Base64Encode(raw_challenge
, &encoded_challenge
);
89 return encoded_challenge
;
92 void AddVectorHeaderIfNonEmpty(const char* name
,
93 const std::vector
<std::string
>& value
,
94 HttpRequestHeaders
* headers
) {
97 headers
->SetHeader(name
, base::JoinString(value
, ", "));
100 GetHeaderResult
GetSingleHeaderValue(const HttpResponseHeaders
* headers
,
101 const base::StringPiece
& name
,
102 std::string
* value
) {
103 void* state
= nullptr;
104 size_t num_values
= 0;
105 std::string temp_value
;
106 while (headers
->EnumerateHeader(&state
, name
, &temp_value
)) {
107 if (++num_values
> 1)
108 return GET_HEADER_MULTIPLE
;
111 return num_values
> 0 ? GET_HEADER_OK
: GET_HEADER_MISSING
;
114 bool ValidateHeaderHasSingleValue(GetHeaderResult result
,
115 const std::string
& header_name
,
116 std::string
* failure_message
) {
117 if (result
== GET_HEADER_MISSING
) {
118 *failure_message
= MissingHeaderMessage(header_name
);
121 if (result
== GET_HEADER_MULTIPLE
) {
122 *failure_message
= MultipleHeaderValuesMessage(header_name
);
125 DCHECK_EQ(result
, GET_HEADER_OK
);
129 bool ValidateUpgrade(const HttpResponseHeaders
* headers
,
130 std::string
* failure_message
) {
132 GetHeaderResult result
=
133 GetSingleHeaderValue(headers
, websockets::kUpgrade
, &value
);
134 if (!ValidateHeaderHasSingleValue(result
,
135 websockets::kUpgrade
,
140 if (!base::LowerCaseEqualsASCII(value
, websockets::kWebSocketLowercase
)) {
142 "'Upgrade' header value is not 'WebSocket': " + value
;
148 bool ValidateSecWebSocketAccept(const HttpResponseHeaders
* headers
,
149 const std::string
& expected
,
150 std::string
* failure_message
) {
152 GetHeaderResult result
=
153 GetSingleHeaderValue(headers
, websockets::kSecWebSocketAccept
, &actual
);
154 if (!ValidateHeaderHasSingleValue(result
,
155 websockets::kSecWebSocketAccept
,
160 if (expected
!= actual
) {
161 *failure_message
= "Incorrect 'Sec-WebSocket-Accept' header value";
167 bool ValidateConnection(const HttpResponseHeaders
* headers
,
168 std::string
* failure_message
) {
169 // Connection header is permitted to contain other tokens.
170 if (!headers
->HasHeader(HttpRequestHeaders::kConnection
)) {
171 *failure_message
= MissingHeaderMessage(HttpRequestHeaders::kConnection
);
174 if (!headers
->HasHeaderValue(HttpRequestHeaders::kConnection
,
175 websockets::kUpgrade
)) {
176 *failure_message
= "'Connection' header value must contain 'Upgrade'";
182 bool ValidateSubProtocol(
183 const HttpResponseHeaders
* headers
,
184 const std::vector
<std::string
>& requested_sub_protocols
,
185 std::string
* sub_protocol
,
186 std::string
* failure_message
) {
187 void* state
= nullptr;
189 base::hash_set
<std::string
> requested_set(requested_sub_protocols
.begin(),
190 requested_sub_protocols
.end());
192 bool has_multiple_protocols
= false;
193 bool has_invalid_protocol
= false;
195 while (!has_invalid_protocol
|| !has_multiple_protocols
) {
196 std::string temp_value
;
197 if (!headers
->EnumerateHeader(
198 &state
, websockets::kSecWebSocketProtocol
, &temp_value
))
201 if (requested_set
.count(value
) == 0)
202 has_invalid_protocol
= true;
204 has_multiple_protocols
= true;
207 if (has_multiple_protocols
) {
209 MultipleHeaderValuesMessage(websockets::kSecWebSocketProtocol
);
211 } else if (count
> 0 && requested_sub_protocols
.size() == 0) {
213 std::string("Response must not include 'Sec-WebSocket-Protocol' "
214 "header if not present in request: ")
217 } else if (has_invalid_protocol
) {
219 "'Sec-WebSocket-Protocol' header value '" +
221 "' in response does not match any of sent values";
223 } else if (requested_sub_protocols
.size() > 0 && count
== 0) {
225 "Sent non-empty 'Sec-WebSocket-Protocol' header "
226 "but no response was received";
229 *sub_protocol
= value
;
233 bool ValidateExtensions(const HttpResponseHeaders
* headers
,
234 std::string
* accepted_extensions_descriptor
,
235 std::string
* failure_message
,
236 WebSocketExtensionParams
* params
) {
237 void* state
= nullptr;
238 std::string header_value
;
239 std::vector
<std::string
> header_values
;
240 // TODO(ricea): If adding support for additional extensions, generalise this
242 bool seen_permessage_deflate
= false;
243 while (headers
->EnumerateHeader(&state
, websockets::kSecWebSocketExtensions
,
245 WebSocketExtensionParser parser
;
246 if (!parser
.Parse(header_value
)) {
247 // TODO(yhirano) Set appropriate failure message.
249 "'Sec-WebSocket-Extensions' header value is "
250 "rejected by the parser: " +
255 const std::vector
<WebSocketExtension
>& extensions
= parser
.extensions();
256 for (const auto& extension
: extensions
) {
257 if (extension
.name() == "permessage-deflate") {
258 if (seen_permessage_deflate
) {
259 *failure_message
= "Received duplicate permessage-deflate response";
262 seen_permessage_deflate
= true;
263 auto& deflate_parameters
= params
->deflate_parameters
;
264 if (!deflate_parameters
.Initialize(extension
, failure_message
) ||
265 !deflate_parameters
.IsValidAsResponse(failure_message
)) {
266 *failure_message
= "Error in permessage-deflate: " + *failure_message
;
269 // Note that we don't have to check the request-response compatibility
270 // here because we send a request compatible with any valid responses.
271 // TODO(yhirano): Place a DCHECK here.
273 header_values
.push_back(header_value
);
275 *failure_message
= "Found an unsupported extension '" +
277 "' in 'Sec-WebSocket-Extensions' header";
282 *accepted_extensions_descriptor
= base::JoinString(header_values
, ", ");
283 params
->deflate_enabled
= seen_permessage_deflate
;
289 WebSocketBasicHandshakeStream::WebSocketBasicHandshakeStream(
290 scoped_ptr
<ClientSocketHandle
> connection
,
291 WebSocketStream::ConnectDelegate
* connect_delegate
,
293 std::vector
<std::string
> requested_sub_protocols
,
294 std::vector
<std::string
> requested_extensions
,
295 std::string
* failure_message
)
296 : state_(connection
.release(), using_proxy
),
297 connect_delegate_(connect_delegate
),
298 http_response_info_(nullptr),
299 requested_sub_protocols_(requested_sub_protocols
),
300 requested_extensions_(requested_extensions
),
301 failure_message_(failure_message
) {
302 DCHECK(connect_delegate
);
303 DCHECK(failure_message
);
306 WebSocketBasicHandshakeStream::~WebSocketBasicHandshakeStream() {}
308 int WebSocketBasicHandshakeStream::InitializeStream(
309 const HttpRequestInfo
* request_info
,
310 RequestPriority priority
,
311 const BoundNetLog
& net_log
,
312 const CompletionCallback
& callback
) {
313 url_
= request_info
->url
;
314 state_
.Initialize(request_info
, priority
, net_log
, callback
);
318 int WebSocketBasicHandshakeStream::SendRequest(
319 const HttpRequestHeaders
& headers
,
320 HttpResponseInfo
* response
,
321 const CompletionCallback
& callback
) {
322 DCHECK(!headers
.HasHeader(websockets::kSecWebSocketKey
));
323 DCHECK(!headers
.HasHeader(websockets::kSecWebSocketProtocol
));
324 DCHECK(!headers
.HasHeader(websockets::kSecWebSocketExtensions
));
325 DCHECK(headers
.HasHeader(HttpRequestHeaders::kOrigin
));
326 DCHECK(headers
.HasHeader(websockets::kUpgrade
));
327 DCHECK(headers
.HasHeader(HttpRequestHeaders::kConnection
));
328 DCHECK(headers
.HasHeader(websockets::kSecWebSocketVersion
));
331 http_response_info_
= response
;
333 // Create a copy of the headers object, so that we can add the
334 // Sec-WebSockey-Key header.
335 HttpRequestHeaders enriched_headers
;
336 enriched_headers
.CopyFrom(headers
);
337 std::string handshake_challenge
;
338 if (handshake_challenge_for_testing_
) {
339 handshake_challenge
= *handshake_challenge_for_testing_
;
340 handshake_challenge_for_testing_
.reset();
342 handshake_challenge
= GenerateHandshakeChallenge();
344 enriched_headers
.SetHeader(websockets::kSecWebSocketKey
, handshake_challenge
);
346 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketExtensions
,
347 requested_extensions_
,
349 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketProtocol
,
350 requested_sub_protocols_
,
353 handshake_challenge_response_
=
354 ComputeSecWebSocketAccept(handshake_challenge
);
356 DCHECK(connect_delegate_
);
357 scoped_ptr
<WebSocketHandshakeRequestInfo
> request(
358 new WebSocketHandshakeRequestInfo(url_
, base::Time::Now()));
359 request
->headers
.CopyFrom(enriched_headers
);
360 connect_delegate_
->OnStartOpeningHandshake(request
.Pass());
362 return parser()->SendRequest(
363 state_
.GenerateRequestLine(), enriched_headers
, response
, callback
);
366 int WebSocketBasicHandshakeStream::ReadResponseHeaders(
367 const CompletionCallback
& callback
) {
368 // HttpStreamParser uses a weak pointer when reading from the
369 // socket, so it won't be called back after being destroyed. The
370 // HttpStreamParser is owned by HttpBasicState which is owned by this object,
371 // so this use of base::Unretained() is safe.
372 int rv
= parser()->ReadResponseHeaders(
373 base::Bind(&WebSocketBasicHandshakeStream::ReadResponseHeadersCallback
,
374 base::Unretained(this),
376 if (rv
== ERR_IO_PENDING
)
378 return ValidateResponse(rv
);
381 int WebSocketBasicHandshakeStream::ReadResponseBody(
384 const CompletionCallback
& callback
) {
385 return parser()->ReadResponseBody(buf
, buf_len
, callback
);
388 void WebSocketBasicHandshakeStream::Close(bool not_reusable
) {
389 // This class ignores the value of |not_reusable| and never lets the socket be
392 parser()->Close(true);
395 bool WebSocketBasicHandshakeStream::IsResponseBodyComplete() const {
396 return parser()->IsResponseBodyComplete();
399 bool WebSocketBasicHandshakeStream::IsConnectionReused() const {
400 return parser()->IsConnectionReused();
403 void WebSocketBasicHandshakeStream::SetConnectionReused() {
404 parser()->SetConnectionReused();
407 bool WebSocketBasicHandshakeStream::CanReuseConnection() const {
411 int64
WebSocketBasicHandshakeStream::GetTotalReceivedBytes() const {
415 int64_t WebSocketBasicHandshakeStream::GetTotalSentBytes() const {
419 bool WebSocketBasicHandshakeStream::GetLoadTimingInfo(
420 LoadTimingInfo
* load_timing_info
) const {
421 return state_
.connection()->GetLoadTimingInfo(IsConnectionReused(),
425 void WebSocketBasicHandshakeStream::GetSSLInfo(SSLInfo
* ssl_info
) {
426 parser()->GetSSLInfo(ssl_info
);
429 void WebSocketBasicHandshakeStream::GetSSLCertRequestInfo(
430 SSLCertRequestInfo
* cert_request_info
) {
431 parser()->GetSSLCertRequestInfo(cert_request_info
);
434 void WebSocketBasicHandshakeStream::Drain(HttpNetworkSession
* session
) {
435 HttpResponseBodyDrainer
* drainer
= new HttpResponseBodyDrainer(this);
436 drainer
->Start(session
);
437 // |drainer| will delete itself.
440 void WebSocketBasicHandshakeStream::SetPriority(RequestPriority priority
) {
441 // TODO(ricea): See TODO comment in HttpBasicStream::SetPriority(). If it is
442 // gone, then copy whatever has happened there over here.
445 UploadProgress
WebSocketBasicHandshakeStream::GetUploadProgress() const {
446 return UploadProgress();
449 HttpStream
* WebSocketBasicHandshakeStream::RenewStreamForAuth() {
450 // Return null because we don't support renewing the stream.
454 scoped_ptr
<WebSocketStream
> WebSocketBasicHandshakeStream::Upgrade() {
455 // The HttpStreamParser object has a pointer to our ClientSocketHandle. Make
456 // sure it does not touch it again before it is destroyed.
457 state_
.DeleteParser();
458 WebSocketTransportClientSocketPool::UnlockEndpoint(state_
.connection());
459 scoped_ptr
<WebSocketStream
> basic_stream(
460 new WebSocketBasicStream(state_
.ReleaseConnection(),
464 DCHECK(extension_params_
.get());
465 if (extension_params_
->deflate_enabled
) {
466 UMA_HISTOGRAM_ENUMERATION(
467 "Net.WebSocket.DeflateMode",
468 extension_params_
->deflate_parameters
.client_context_take_over_mode(),
469 WebSocketDeflater::NUM_CONTEXT_TAKEOVER_MODE_TYPES
);
471 return scoped_ptr
<WebSocketStream
>(new WebSocketDeflateStream(
472 basic_stream
.Pass(), extension_params_
->deflate_parameters
,
473 scoped_ptr
<WebSocketDeflatePredictor
>(
474 new WebSocketDeflatePredictorImpl
)));
476 return basic_stream
.Pass();
480 void WebSocketBasicHandshakeStream::SetWebSocketKeyForTesting(
481 const std::string
& key
) {
482 handshake_challenge_for_testing_
.reset(new std::string(key
));
485 void WebSocketBasicHandshakeStream::ReadResponseHeadersCallback(
486 const CompletionCallback
& callback
,
488 callback
.Run(ValidateResponse(result
));
491 void WebSocketBasicHandshakeStream::OnFinishOpeningHandshake() {
492 DCHECK(http_response_info_
);
493 WebSocketDispatchOnFinishOpeningHandshake(connect_delegate_
,
495 http_response_info_
->headers
,
496 http_response_info_
->response_time
);
499 int WebSocketBasicHandshakeStream::ValidateResponse(int rv
) {
500 DCHECK(http_response_info_
);
501 // Most net errors happen during connection, so they are not seen by this
502 // method. The histogram for error codes is created in
503 // Delegate::OnResponseStarted in websocket_stream.cc instead.
505 const HttpResponseHeaders
* headers
= http_response_info_
->headers
.get();
506 const int response_code
= headers
->response_code();
507 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.WebSocket.ResponseCode", response_code
);
508 switch (response_code
) {
509 case HTTP_SWITCHING_PROTOCOLS
:
510 OnFinishOpeningHandshake();
511 return ValidateUpgradeResponse(headers
);
513 // We need to pass these through for authentication to work.
514 case HTTP_UNAUTHORIZED
:
515 case HTTP_PROXY_AUTHENTICATION_REQUIRED
:
518 // Other status codes are potentially risky (see the warnings in the
519 // WHATWG WebSocket API spec) and so are dropped by default.
521 // A WebSocket server cannot be using HTTP/0.9, so if we see version
522 // 0.9, it means the response was garbage.
523 // Reporting "Unexpected response code: 200" in this case is not
524 // helpful, so use a different error message.
525 if (headers
->GetHttpVersion() == HttpVersion(0, 9)) {
527 "Error during WebSocket handshake: Invalid status line");
529 set_failure_message(base::StringPrintf(
530 "Error during WebSocket handshake: Unexpected response code: %d",
531 headers
->response_code()));
533 OnFinishOpeningHandshake();
534 return ERR_INVALID_RESPONSE
;
537 if (rv
== ERR_EMPTY_RESPONSE
) {
539 "Connection closed before receiving a handshake response");
542 set_failure_message(std::string("Error during WebSocket handshake: ") +
544 OnFinishOpeningHandshake();
545 // Some error codes (for example ERR_CONNECTION_CLOSED) get changed to OK at
546 // higher levels. To prevent an unvalidated connection getting erroneously
547 // upgraded, don't pass through the status code unchanged if it is
548 // HTTP_SWITCHING_PROTOCOLS.
549 if (http_response_info_
->headers
&&
550 http_response_info_
->headers
->response_code() ==
551 HTTP_SWITCHING_PROTOCOLS
) {
552 http_response_info_
->headers
->ReplaceStatusLine(
553 kConnectionErrorStatusLine
);
559 int WebSocketBasicHandshakeStream::ValidateUpgradeResponse(
560 const HttpResponseHeaders
* headers
) {
561 extension_params_
.reset(new WebSocketExtensionParams
);
562 std::string failure_message
;
563 if (ValidateUpgrade(headers
, &failure_message
) &&
564 ValidateSecWebSocketAccept(
565 headers
, handshake_challenge_response_
, &failure_message
) &&
566 ValidateConnection(headers
, &failure_message
) &&
567 ValidateSubProtocol(headers
,
568 requested_sub_protocols_
,
571 ValidateExtensions(headers
,
574 extension_params_
.get())) {
577 set_failure_message("Error during WebSocket handshake: " + failure_message
);
578 return ERR_INVALID_RESPONSE
;
581 void WebSocketBasicHandshakeStream::set_failure_message(
582 const std::string
& failure_message
) {
583 *failure_message_
= failure_message
;