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 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
= 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::CanFindEndOfResponse() const {
466 return parser() && parser()->CanFindEndOfResponse();
469 bool WebSocketBasicHandshakeStream::IsConnectionReused() const {
470 return parser()->IsConnectionReused();
473 void WebSocketBasicHandshakeStream::SetConnectionReused() {
474 parser()->SetConnectionReused();
477 bool WebSocketBasicHandshakeStream::IsConnectionReusable() const {
481 int64
WebSocketBasicHandshakeStream::GetTotalReceivedBytes() 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 bool WebSocketBasicHandshakeStream::IsSpdyHttpStream() const { return false; }
502 void WebSocketBasicHandshakeStream::Drain(HttpNetworkSession
* session
) {
503 HttpResponseBodyDrainer
* drainer
= new HttpResponseBodyDrainer(this);
504 drainer
->Start(session
);
505 // |drainer| will delete itself.
508 void WebSocketBasicHandshakeStream::SetPriority(RequestPriority priority
) {
509 // TODO(ricea): See TODO comment in HttpBasicStream::SetPriority(). If it is
510 // gone, then copy whatever has happened there over here.
513 UploadProgress
WebSocketBasicHandshakeStream::GetUploadProgress() const {
514 return UploadProgress();
517 HttpStream
* WebSocketBasicHandshakeStream::RenewStreamForAuth() {
518 // Return null because we don't support renewing the stream.
522 scoped_ptr
<WebSocketStream
> WebSocketBasicHandshakeStream::Upgrade() {
523 // The HttpStreamParser object has a pointer to our ClientSocketHandle. Make
524 // sure it does not touch it again before it is destroyed.
525 state_
.DeleteParser();
526 WebSocketTransportClientSocketPool::UnlockEndpoint(state_
.connection());
527 scoped_ptr
<WebSocketStream
> basic_stream(
528 new WebSocketBasicStream(state_
.ReleaseConnection(),
532 DCHECK(extension_params_
.get());
533 if (extension_params_
->deflate_enabled
) {
534 UMA_HISTOGRAM_ENUMERATION(
535 "Net.WebSocket.DeflateMode",
536 extension_params_
->deflate_mode
,
537 WebSocketDeflater::NUM_CONTEXT_TAKEOVER_MODE_TYPES
);
539 return scoped_ptr
<WebSocketStream
>(
540 new WebSocketDeflateStream(basic_stream
.Pass(),
541 extension_params_
->deflate_mode
,
542 extension_params_
->client_window_bits
,
543 scoped_ptr
<WebSocketDeflatePredictor
>(
544 new WebSocketDeflatePredictorImpl
)));
546 return basic_stream
.Pass();
550 void WebSocketBasicHandshakeStream::SetWebSocketKeyForTesting(
551 const std::string
& key
) {
552 handshake_challenge_for_testing_
.reset(new std::string(key
));
555 void WebSocketBasicHandshakeStream::ReadResponseHeadersCallback(
556 const CompletionCallback
& callback
,
558 callback
.Run(ValidateResponse(result
));
561 void WebSocketBasicHandshakeStream::OnFinishOpeningHandshake() {
562 DCHECK(http_response_info_
);
563 WebSocketDispatchOnFinishOpeningHandshake(connect_delegate_
,
565 http_response_info_
->headers
,
566 http_response_info_
->response_time
);
569 int WebSocketBasicHandshakeStream::ValidateResponse(int rv
) {
570 DCHECK(http_response_info_
);
571 // Most net errors happen during connection, so they are not seen by this
572 // method. The histogram for error codes is created in
573 // Delegate::OnResponseStarted in websocket_stream.cc instead.
575 const HttpResponseHeaders
* headers
= http_response_info_
->headers
.get();
576 const int response_code
= headers
->response_code();
577 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.WebSocket.ResponseCode", response_code
);
578 switch (response_code
) {
579 case HTTP_SWITCHING_PROTOCOLS
:
580 OnFinishOpeningHandshake();
581 return ValidateUpgradeResponse(headers
);
583 // We need to pass these through for authentication to work.
584 case HTTP_UNAUTHORIZED
:
585 case HTTP_PROXY_AUTHENTICATION_REQUIRED
:
588 // Other status codes are potentially risky (see the warnings in the
589 // WHATWG WebSocket API spec) and so are dropped by default.
591 // A WebSocket server cannot be using HTTP/0.9, so if we see version
592 // 0.9, it means the response was garbage.
593 // Reporting "Unexpected response code: 200" in this case is not
594 // helpful, so use a different error message.
595 if (headers
->GetHttpVersion() == HttpVersion(0, 9)) {
597 "Error during WebSocket handshake: Invalid status line");
599 set_failure_message(base::StringPrintf(
600 "Error during WebSocket handshake: Unexpected response code: %d",
601 headers
->response_code()));
603 OnFinishOpeningHandshake();
604 return ERR_INVALID_RESPONSE
;
607 if (rv
== ERR_EMPTY_RESPONSE
) {
609 "Connection closed before receiving a handshake response");
612 set_failure_message(std::string("Error during WebSocket handshake: ") +
614 OnFinishOpeningHandshake();
615 // Some error codes (for example ERR_CONNECTION_CLOSED) get changed to OK at
616 // higher levels. To prevent an unvalidated connection getting erroneously
617 // upgraded, don't pass through the status code unchanged if it is
618 // HTTP_SWITCHING_PROTOCOLS.
619 if (http_response_info_
->headers
&&
620 http_response_info_
->headers
->response_code() ==
621 HTTP_SWITCHING_PROTOCOLS
) {
622 http_response_info_
->headers
->ReplaceStatusLine(
623 kConnectionErrorStatusLine
);
629 int WebSocketBasicHandshakeStream::ValidateUpgradeResponse(
630 const HttpResponseHeaders
* headers
) {
631 extension_params_
.reset(new WebSocketExtensionParams
);
632 std::string failure_message
;
633 if (ValidateUpgrade(headers
, &failure_message
) &&
634 ValidateSecWebSocketAccept(
635 headers
, handshake_challenge_response_
, &failure_message
) &&
636 ValidateConnection(headers
, &failure_message
) &&
637 ValidateSubProtocol(headers
,
638 requested_sub_protocols_
,
641 ValidateExtensions(headers
,
644 extension_params_
.get())) {
647 set_failure_message("Error during WebSocket handshake: " + failure_message
);
648 return ERR_INVALID_RESPONSE
;
651 void WebSocketBasicHandshakeStream::set_failure_message(
652 const std::string
& failure_message
) {
653 *failure_message_
= failure_message
;