Rename InputLatency::ScrollUpdate to Latency::ScrollUpdate
[chromium-blink-merge.git] / net / websockets / websocket_basic_handshake_stream.cc
blob7bb34a335c75898f6b6de9e8e9e373542bb4c068
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"
7 #include <algorithm>
8 #include <iterator>
9 #include <set>
10 #include <string>
11 #include <vector>
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"
49 namespace net {
51 namespace {
53 const char kConnectionErrorStatusLine[] = "HTTP/1.1 503 Connection Error";
55 } // namespace
57 // TODO(ricea): If more extensions are added, replace this with a more general
58 // mechanism.
59 struct WebSocketExtensionParams {
60 WebSocketExtensionParams()
61 : deflate_enabled(false),
62 client_window_bits(15),
63 deflate_mode(WebSocketDeflater::TAKE_OVER_CONTEXT) {}
65 bool deflate_enabled;
66 int client_window_bits;
67 WebSocketDeflater::ContextTakeOverMode deflate_mode;
70 namespace {
72 enum GetHeaderResult {
73 GET_HEADER_OK,
74 GET_HEADER_MISSING,
75 GET_HEADER_MULTIPLE,
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) {
83 return
84 std::string("'") +
85 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) {
100 if (value.empty())
101 return;
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;
114 *value = temp_value;
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);
124 return false;
126 if (result == GET_HEADER_MULTIPLE) {
127 *failure_message = MultipleHeaderValuesMessage(header_name);
128 return false;
130 DCHECK_EQ(result, GET_HEADER_OK);
131 return true;
134 bool ValidateUpgrade(const HttpResponseHeaders* headers,
135 std::string* failure_message) {
136 std::string value;
137 GetHeaderResult result =
138 GetSingleHeaderValue(headers, websockets::kUpgrade, &value);
139 if (!ValidateHeaderHasSingleValue(result,
140 websockets::kUpgrade,
141 failure_message)) {
142 return false;
145 if (!LowerCaseEqualsASCII(value, websockets::kWebSocketLowercase)) {
146 *failure_message =
147 "'Upgrade' header value is not 'WebSocket': " + value;
148 return false;
150 return true;
153 bool ValidateSecWebSocketAccept(const HttpResponseHeaders* headers,
154 const std::string& expected,
155 std::string* failure_message) {
156 std::string actual;
157 GetHeaderResult result =
158 GetSingleHeaderValue(headers, websockets::kSecWebSocketAccept, &actual);
159 if (!ValidateHeaderHasSingleValue(result,
160 websockets::kSecWebSocketAccept,
161 failure_message)) {
162 return false;
165 if (expected != actual) {
166 *failure_message = "Incorrect 'Sec-WebSocket-Accept' header value";
167 return false;
169 return true;
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);
177 return false;
179 if (!headers->HasHeaderValue(HttpRequestHeaders::kConnection,
180 websockets::kUpgrade)) {
181 *failure_message = "'Connection' header value must contain 'Upgrade'";
182 return false;
184 return true;
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;
193 std::string value;
194 base::hash_set<std::string> requested_set(requested_sub_protocols.begin(),
195 requested_sub_protocols.end());
196 int count = 0;
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))
204 break;
205 value = temp_value;
206 if (requested_set.count(value) == 0)
207 has_invalid_protocol = true;
208 if (++count > 1)
209 has_multiple_protocols = true;
212 if (has_multiple_protocols) {
213 *failure_message =
214 MultipleHeaderValuesMessage(websockets::kSecWebSocketProtocol);
215 return false;
216 } else if (count > 0 && requested_sub_protocols.size() == 0) {
217 *failure_message =
218 std::string("Response must not include 'Sec-WebSocket-Protocol' "
219 "header if not present in request: ")
220 + value;
221 return false;
222 } else if (has_invalid_protocol) {
223 *failure_message =
224 "'Sec-WebSocket-Protocol' header value '" +
225 value +
226 "' in response does not match any of sent values";
227 return false;
228 } else if (requested_sub_protocols.size() > 0 && count == 0) {
229 *failure_message =
230 "Sent non-empty 'Sec-WebSocket-Protocol' header "
231 "but no response was received";
232 return false;
234 *sub_protocol = value;
235 return true;
238 bool DeflateError(std::string* message, const base::StringPiece& piece) {
239 *message = "Error in permessage-deflate: ";
240 piece.AppendToString(message);
241 return false;
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) {
263 return DeflateError(
264 failure_message,
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) {
271 return DeflateError(
272 failure_message,
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");
281 if (is_client)
282 params->deflate_mode = WebSocketDeflater::DO_NOT_TAKE_OVER_CONTEXT;
283 } else if (rest == kMaxWindowBits) {
284 if (!it->HasValue())
285 return DeflateError(failure_message, name + " must have value");
286 int bits = 0;
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");
293 if (is_client)
294 params->client_window_bits = bits;
295 } else {
296 return DeflateError(
297 failure_message,
298 "Received an unexpected permessage-deflate extension parameter");
301 params->deflate_enabled = true;
302 return 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
313 // code.
314 bool seen_permessage_deflate = false;
315 while (headers->EnumerateHeader(&state, websockets::kSecWebSocketExtensions,
316 &header_value)) {
317 WebSocketExtensionParser parser;
318 if (!parser.Parse(header_value)) {
319 // TODO(yhirano) Set appropriate failure message.
320 *failure_message =
321 "'Sec-WebSocket-Extensions' header value is "
322 "rejected by the parser: " +
323 header_value;
324 return false;
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";
332 return false;
334 seen_permessage_deflate = true;
336 if (!ValidatePerMessageDeflateExtension(extension, failure_message,
337 params)) {
338 return false;
340 header_values.push_back(header_value);
341 } else {
342 *failure_message = "Found an unsupported extension '" +
343 extension.name() +
344 "' in 'Sec-WebSocket-Extensions' header";
345 return false;
349 *accepted_extensions_descriptor = JoinString(header_values, ", ");
350 return true;
353 } // namespace
355 WebSocketBasicHandshakeStream::WebSocketBasicHandshakeStream(
356 scoped_ptr<ClientSocketHandle> connection,
357 WebSocketStream::ConnectDelegate* connect_delegate,
358 bool using_proxy,
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);
381 return OK;
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));
395 DCHECK(parser());
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();
407 } else {
408 handshake_challenge = GenerateHandshakeChallenge();
410 enriched_headers.SetHeader(websockets::kSecWebSocketKey, handshake_challenge);
412 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketExtensions,
413 requested_extensions_,
414 &enriched_headers);
415 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketProtocol,
416 requested_sub_protocols_,
417 &enriched_headers);
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),
441 callback));
442 if (rv == ERR_IO_PENDING)
443 return rv;
444 return ValidateResponse(rv);
447 int WebSocketBasicHandshakeStream::ReadResponseBody(
448 IOBuffer* buf,
449 int buf_len,
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
456 // re-used.
457 if (parser())
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 {
478 return false;
481 int64 WebSocketBasicHandshakeStream::GetTotalReceivedBytes() const {
482 return 0;
485 bool WebSocketBasicHandshakeStream::GetLoadTimingInfo(
486 LoadTimingInfo* load_timing_info) const {
487 return state_.connection()->GetLoadTimingInfo(IsConnectionReused(),
488 load_timing_info);
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.
519 return nullptr;
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(),
529 state_.read_buf(),
530 sub_protocol_,
531 extensions_));
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)));
545 } else {
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,
557 int result) {
558 callback.Run(ValidateResponse(result));
561 void WebSocketBasicHandshakeStream::OnFinishOpeningHandshake() {
562 DCHECK(http_response_info_);
563 WebSocketDispatchOnFinishOpeningHandshake(connect_delegate_,
564 url_,
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.
574 if (rv >= 0) {
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:
586 return OK;
588 // Other status codes are potentially risky (see the warnings in the
589 // WHATWG WebSocket API spec) and so are dropped by default.
590 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)) {
596 set_failure_message(
597 "Error during WebSocket handshake: Invalid status line");
598 } else {
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;
606 } else {
607 if (rv == ERR_EMPTY_RESPONSE) {
608 set_failure_message(
609 "Connection closed before receiving a handshake response");
610 return rv;
612 set_failure_message(std::string("Error during WebSocket handshake: ") +
613 ErrorToString(rv));
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);
625 return rv;
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_,
639 &sub_protocol_,
640 &failure_message) &&
641 ValidateExtensions(headers,
642 &extensions_,
643 &failure_message,
644 extension_params_.get())) {
645 return OK;
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;
656 } // namespace net