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.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
, 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 (!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 parser
.Parse(header_value
);
319 if (parser
.has_error()) {
320 // TODO(yhirano) Set appropriate failure message.
322 "'Sec-WebSocket-Extensions' header value is "
323 "rejected by the parser: " +
328 const std::vector
<WebSocketExtension
>& extensions
= parser
.extensions();
329 for (const auto& extension
: extensions
) {
330 if (extension
.name() == "permessage-deflate") {
331 if (seen_permessage_deflate
) {
332 *failure_message
= "Received duplicate permessage-deflate response";
335 seen_permessage_deflate
= true;
337 if (!ValidatePerMessageDeflateExtension(extension
, failure_message
,
341 header_values
.push_back(header_value
);
343 *failure_message
= "Found an unsupported extension '" +
345 "' in 'Sec-WebSocket-Extensions' header";
350 *accepted_extensions_descriptor
= JoinString(header_values
, ", ");
356 WebSocketBasicHandshakeStream::WebSocketBasicHandshakeStream(
357 scoped_ptr
<ClientSocketHandle
> connection
,
358 WebSocketStream::ConnectDelegate
* connect_delegate
,
360 std::vector
<std::string
> requested_sub_protocols
,
361 std::vector
<std::string
> requested_extensions
,
362 std::string
* failure_message
)
363 : state_(connection
.release(), using_proxy
),
364 connect_delegate_(connect_delegate
),
365 http_response_info_(nullptr),
366 requested_sub_protocols_(requested_sub_protocols
),
367 requested_extensions_(requested_extensions
),
368 failure_message_(failure_message
) {
369 DCHECK(connect_delegate
);
370 DCHECK(failure_message
);
373 WebSocketBasicHandshakeStream::~WebSocketBasicHandshakeStream() {}
375 int WebSocketBasicHandshakeStream::InitializeStream(
376 const HttpRequestInfo
* request_info
,
377 RequestPriority priority
,
378 const BoundNetLog
& net_log
,
379 const CompletionCallback
& callback
) {
380 url_
= request_info
->url
;
381 state_
.Initialize(request_info
, priority
, net_log
, callback
);
385 int WebSocketBasicHandshakeStream::SendRequest(
386 const HttpRequestHeaders
& headers
,
387 HttpResponseInfo
* response
,
388 const CompletionCallback
& callback
) {
389 DCHECK(!headers
.HasHeader(websockets::kSecWebSocketKey
));
390 DCHECK(!headers
.HasHeader(websockets::kSecWebSocketProtocol
));
391 DCHECK(!headers
.HasHeader(websockets::kSecWebSocketExtensions
));
392 DCHECK(headers
.HasHeader(HttpRequestHeaders::kOrigin
));
393 DCHECK(headers
.HasHeader(websockets::kUpgrade
));
394 DCHECK(headers
.HasHeader(HttpRequestHeaders::kConnection
));
395 DCHECK(headers
.HasHeader(websockets::kSecWebSocketVersion
));
398 http_response_info_
= response
;
400 // Create a copy of the headers object, so that we can add the
401 // Sec-WebSockey-Key header.
402 HttpRequestHeaders enriched_headers
;
403 enriched_headers
.CopyFrom(headers
);
404 std::string handshake_challenge
;
405 if (handshake_challenge_for_testing_
) {
406 handshake_challenge
= *handshake_challenge_for_testing_
;
407 handshake_challenge_for_testing_
.reset();
409 handshake_challenge
= GenerateHandshakeChallenge();
411 enriched_headers
.SetHeader(websockets::kSecWebSocketKey
, handshake_challenge
);
413 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketExtensions
,
414 requested_extensions_
,
416 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketProtocol
,
417 requested_sub_protocols_
,
420 handshake_challenge_response_
=
421 ComputeSecWebSocketAccept(handshake_challenge
);
423 DCHECK(connect_delegate_
);
424 scoped_ptr
<WebSocketHandshakeRequestInfo
> request(
425 new WebSocketHandshakeRequestInfo(url_
, base::Time::Now()));
426 request
->headers
.CopyFrom(enriched_headers
);
427 connect_delegate_
->OnStartOpeningHandshake(request
.Pass());
429 return parser()->SendRequest(
430 state_
.GenerateRequestLine(), enriched_headers
, response
, callback
);
433 int WebSocketBasicHandshakeStream::ReadResponseHeaders(
434 const CompletionCallback
& callback
) {
435 // HttpStreamParser uses a weak pointer when reading from the
436 // socket, so it won't be called back after being destroyed. The
437 // HttpStreamParser is owned by HttpBasicState which is owned by this object,
438 // so this use of base::Unretained() is safe.
439 int rv
= parser()->ReadResponseHeaders(
440 base::Bind(&WebSocketBasicHandshakeStream::ReadResponseHeadersCallback
,
441 base::Unretained(this),
443 if (rv
== ERR_IO_PENDING
)
445 return ValidateResponse(rv
);
448 int WebSocketBasicHandshakeStream::ReadResponseBody(
451 const CompletionCallback
& callback
) {
452 return parser()->ReadResponseBody(buf
, buf_len
, callback
);
455 void WebSocketBasicHandshakeStream::Close(bool not_reusable
) {
456 // This class ignores the value of |not_reusable| and never lets the socket be
459 parser()->Close(true);
462 bool WebSocketBasicHandshakeStream::IsResponseBodyComplete() const {
463 return parser()->IsResponseBodyComplete();
466 bool WebSocketBasicHandshakeStream::CanFindEndOfResponse() const {
467 return parser() && parser()->CanFindEndOfResponse();
470 bool WebSocketBasicHandshakeStream::IsConnectionReused() const {
471 return parser()->IsConnectionReused();
474 void WebSocketBasicHandshakeStream::SetConnectionReused() {
475 parser()->SetConnectionReused();
478 bool WebSocketBasicHandshakeStream::IsConnectionReusable() const {
482 int64
WebSocketBasicHandshakeStream::GetTotalReceivedBytes() const {
486 bool WebSocketBasicHandshakeStream::GetLoadTimingInfo(
487 LoadTimingInfo
* load_timing_info
) const {
488 return state_
.connection()->GetLoadTimingInfo(IsConnectionReused(),
492 void WebSocketBasicHandshakeStream::GetSSLInfo(SSLInfo
* ssl_info
) {
493 parser()->GetSSLInfo(ssl_info
);
496 void WebSocketBasicHandshakeStream::GetSSLCertRequestInfo(
497 SSLCertRequestInfo
* cert_request_info
) {
498 parser()->GetSSLCertRequestInfo(cert_request_info
);
501 bool WebSocketBasicHandshakeStream::IsSpdyHttpStream() const { return false; }
503 void WebSocketBasicHandshakeStream::Drain(HttpNetworkSession
* session
) {
504 HttpResponseBodyDrainer
* drainer
= new HttpResponseBodyDrainer(this);
505 drainer
->Start(session
);
506 // |drainer| will delete itself.
509 void WebSocketBasicHandshakeStream::SetPriority(RequestPriority priority
) {
510 // TODO(ricea): See TODO comment in HttpBasicStream::SetPriority(). If it is
511 // gone, then copy whatever has happened there over here.
514 UploadProgress
WebSocketBasicHandshakeStream::GetUploadProgress() const {
515 return UploadProgress();
518 HttpStream
* WebSocketBasicHandshakeStream::RenewStreamForAuth() {
519 // Return null because we don't support renewing the stream.
523 scoped_ptr
<WebSocketStream
> WebSocketBasicHandshakeStream::Upgrade() {
524 // The HttpStreamParser object has a pointer to our ClientSocketHandle. Make
525 // sure it does not touch it again before it is destroyed.
526 state_
.DeleteParser();
527 WebSocketTransportClientSocketPool::UnlockEndpoint(state_
.connection());
528 scoped_ptr
<WebSocketStream
> basic_stream(
529 new WebSocketBasicStream(state_
.ReleaseConnection(),
533 DCHECK(extension_params_
.get());
534 if (extension_params_
->deflate_enabled
) {
535 UMA_HISTOGRAM_ENUMERATION(
536 "Net.WebSocket.DeflateMode",
537 extension_params_
->deflate_mode
,
538 WebSocketDeflater::NUM_CONTEXT_TAKEOVER_MODE_TYPES
);
540 return scoped_ptr
<WebSocketStream
>(
541 new WebSocketDeflateStream(basic_stream
.Pass(),
542 extension_params_
->deflate_mode
,
543 extension_params_
->client_window_bits
,
544 scoped_ptr
<WebSocketDeflatePredictor
>(
545 new WebSocketDeflatePredictorImpl
)));
547 return basic_stream
.Pass();
551 void WebSocketBasicHandshakeStream::SetWebSocketKeyForTesting(
552 const std::string
& key
) {
553 handshake_challenge_for_testing_
.reset(new std::string(key
));
556 void WebSocketBasicHandshakeStream::ReadResponseHeadersCallback(
557 const CompletionCallback
& callback
,
559 callback
.Run(ValidateResponse(result
));
562 void WebSocketBasicHandshakeStream::OnFinishOpeningHandshake() {
563 DCHECK(http_response_info_
);
564 WebSocketDispatchOnFinishOpeningHandshake(connect_delegate_
,
566 http_response_info_
->headers
,
567 http_response_info_
->response_time
);
570 int WebSocketBasicHandshakeStream::ValidateResponse(int rv
) {
571 DCHECK(http_response_info_
);
572 // Most net errors happen during connection, so they are not seen by this
573 // method. The histogram for error codes is created in
574 // Delegate::OnResponseStarted in websocket_stream.cc instead.
576 const HttpResponseHeaders
* headers
= http_response_info_
->headers
.get();
577 const int response_code
= headers
->response_code();
578 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.WebSocket.ResponseCode", response_code
);
579 switch (response_code
) {
580 case HTTP_SWITCHING_PROTOCOLS
:
581 OnFinishOpeningHandshake();
582 return ValidateUpgradeResponse(headers
);
584 // We need to pass these through for authentication to work.
585 case HTTP_UNAUTHORIZED
:
586 case HTTP_PROXY_AUTHENTICATION_REQUIRED
:
589 // Other status codes are potentially risky (see the warnings in the
590 // WHATWG WebSocket API spec) and so are dropped by default.
592 // A WebSocket server cannot be using HTTP/0.9, so if we see version
593 // 0.9, it means the response was garbage.
594 // Reporting "Unexpected response code: 200" in this case is not
595 // helpful, so use a different error message.
596 if (headers
->GetHttpVersion() == HttpVersion(0, 9)) {
598 "Error during WebSocket handshake: Invalid status line");
600 set_failure_message(base::StringPrintf(
601 "Error during WebSocket handshake: Unexpected response code: %d",
602 headers
->response_code()));
604 OnFinishOpeningHandshake();
605 return ERR_INVALID_RESPONSE
;
608 if (rv
== ERR_EMPTY_RESPONSE
) {
610 "Connection closed before receiving a handshake response");
613 set_failure_message(std::string("Error during WebSocket handshake: ") +
615 OnFinishOpeningHandshake();
616 // Some error codes (for example ERR_CONNECTION_CLOSED) get changed to OK at
617 // higher levels. To prevent an unvalidated connection getting erroneously
618 // upgraded, don't pass through the status code unchanged if it is
619 // HTTP_SWITCHING_PROTOCOLS.
620 if (http_response_info_
->headers
&&
621 http_response_info_
->headers
->response_code() ==
622 HTTP_SWITCHING_PROTOCOLS
) {
623 http_response_info_
->headers
->ReplaceStatusLine(
624 kConnectionErrorStatusLine
);
630 int WebSocketBasicHandshakeStream::ValidateUpgradeResponse(
631 const HttpResponseHeaders
* headers
) {
632 extension_params_
.reset(new WebSocketExtensionParams
);
633 std::string failure_message
;
634 if (ValidateUpgrade(headers
, &failure_message
) &&
635 ValidateSecWebSocketAccept(
636 headers
, handshake_challenge_response_
, &failure_message
) &&
637 ValidateConnection(headers
, &failure_message
) &&
638 ValidateSubProtocol(headers
,
639 requested_sub_protocols_
,
642 ValidateExtensions(headers
,
645 extension_params_
.get())) {
648 set_failure_message("Error during WebSocket handshake: " + failure_message
);
649 return ERR_INVALID_RESPONSE
;
652 void WebSocketBasicHandshakeStream::set_failure_message(
653 const std::string
& failure_message
) {
654 *failure_message_
= failure_message
;