blob: 65f63e06624291649a8f9900c5f678440acbab27 [file] [log] [blame]
[email protected]d51365e2013-11-27 10:46:521// 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.
4
5#include "net/websockets/websocket_basic_handshake_stream.h"
6
tfarinaea94afc232015-10-20 04:23:367#include <stddef.h>
[email protected]d51365e2013-11-27 10:46:528#include <algorithm>
9#include <iterator>
[email protected]0be93922014-01-29 00:42:4510#include <set>
dchengc7eeda422015-12-26 03:56:4811#include <utility>
[email protected]d51365e2013-11-27 10:46:5212
13#include "base/base64.h"
[email protected]d51365e2013-11-27 10:46:5214#include "base/bind.h"
yhirano27b2b572014-10-30 11:23:4415#include "base/compiler_specific.h"
[email protected]8aba0172014-07-03 12:09:5316#include "base/logging.h"
Ilya Sherman0eb39802017-12-08 20:58:1817#include "base/metrics/histogram_functions.h"
[email protected]d51365e2013-11-27 10:46:5218#include "base/stl_util.h"
[email protected]0be93922014-01-29 00:42:4519#include "base/strings/string_number_conversions.h"
[email protected]69d7a492014-02-19 08:36:3220#include "base/strings/string_piece.h"
[email protected]d51365e2013-11-27 10:46:5221#include "base/strings/string_util.h"
[email protected]96868202014-01-09 10:38:0422#include "base/strings/stringprintf.h"
[email protected]cd48ed12014-01-22 14:34:2223#include "base/time/time.h"
[email protected]d51365e2013-11-27 10:46:5224#include "crypto/random.h"
halton.huo299e2002014-12-02 04:39:2425#include "net/base/io_buffer.h"
Tsuyoshi Horo01faed62019-02-20 22:11:3726#include "net/base/ip_endpoint.h"
[email protected]d51365e2013-11-27 10:46:5227#include "net/http/http_request_headers.h"
28#include "net/http/http_request_info.h"
29#include "net/http/http_response_body_drainer.h"
30#include "net/http/http_response_headers.h"
31#include "net/http/http_status_code.h"
32#include "net/http/http_stream_parser.h"
33#include "net/socket/client_socket_handle.h"
Bence Béky3cb271d2018-03-29 22:00:4834#include "net/socket/ssl_client_socket.h"
Bence Békyda280c62018-04-12 15:08:3735#include "net/socket/websocket_endpoint_lock_manager.h"
[email protected]654866142014-06-24 22:53:3136#include "net/socket/websocket_transport_client_socket_pool.h"
Matt Menkef171ff8b2019-02-05 20:06:1337#include "net/ssl/ssl_cert_request_info.h"
38#include "net/ssl/ssl_info.h"
[email protected]d51365e2013-11-27 10:46:5239#include "net/websockets/websocket_basic_stream.h"
Bence Béky7294fc22018-02-08 14:26:1740#include "net/websockets/websocket_basic_stream_adapters.h"
yhirano8387aee2015-09-14 05:46:4941#include "net/websockets/websocket_deflate_parameters.h"
[email protected]0be93922014-01-29 00:42:4542#include "net/websockets/websocket_deflate_predictor.h"
43#include "net/websockets/websocket_deflate_predictor_impl.h"
44#include "net/websockets/websocket_deflate_stream.h"
45#include "net/websockets/websocket_deflater.h"
ricea11bdcd02014-11-20 09:57:0746#include "net/websockets/websocket_handshake_challenge.h"
[email protected]d51365e2013-11-27 10:46:5247#include "net/websockets/websocket_handshake_constants.h"
[email protected]cd48ed12014-01-22 14:34:2248#include "net/websockets/websocket_handshake_request_info.h"
49#include "net/websockets/websocket_handshake_response_info.h"
[email protected]d51365e2013-11-27 10:46:5250#include "net/websockets/websocket_stream.h"
51
52namespace net {
[email protected]0be93922014-01-29 00:42:4553
yhirano27b2b572014-10-30 11:23:4454namespace {
55
ricea23c3f942015-02-02 13:35:1356const char kConnectionErrorStatusLine[] = "HTTP/1.1 503 Connection Error";
57
yhirano27b2b572014-10-30 11:23:4458} // namespace
59
[email protected]d51365e2013-11-27 10:46:5260namespace {
61
[email protected]96868202014-01-09 10:38:0462enum GetHeaderResult {
63 GET_HEADER_OK,
64 GET_HEADER_MISSING,
65 GET_HEADER_MULTIPLE,
66};
67
68std::string MissingHeaderMessage(const std::string& header_name) {
69 return std::string("'") + header_name + "' header is missing";
70}
71
[email protected]d51365e2013-11-27 10:46:5272std::string GenerateHandshakeChallenge() {
73 std::string raw_challenge(websockets::kRawChallengeLength, '\0');
Ryan Sleevi972b2ff2018-05-14 15:45:1074 crypto::RandBytes(base::data(raw_challenge), raw_challenge.length());
[email protected]d51365e2013-11-27 10:46:5275 std::string encoded_challenge;
[email protected]33fca122013-12-11 01:48:5076 base::Base64Encode(raw_challenge, &encoded_challenge);
[email protected]d51365e2013-11-27 10:46:5277 return encoded_challenge;
78}
79
[email protected]96868202014-01-09 10:38:0480GetHeaderResult GetSingleHeaderValue(const HttpResponseHeaders* headers,
81 const base::StringPiece& name,
82 std::string* value) {
olli.raulaee489a52016-01-25 08:37:1083 size_t iter = 0;
[email protected]96868202014-01-09 10:38:0484 size_t num_values = 0;
85 std::string temp_value;
olli.raulaee489a52016-01-25 08:37:1086 while (headers->EnumerateHeader(&iter, name, &temp_value)) {
[email protected]96868202014-01-09 10:38:0487 if (++num_values > 1)
88 return GET_HEADER_MULTIPLE;
89 *value = temp_value;
[email protected]d51365e2013-11-27 10:46:5290 }
[email protected]96868202014-01-09 10:38:0491 return num_values > 0 ? GET_HEADER_OK : GET_HEADER_MISSING;
92}
93
94bool ValidateHeaderHasSingleValue(GetHeaderResult result,
95 const std::string& header_name,
96 std::string* failure_message) {
97 if (result == GET_HEADER_MISSING) {
98 *failure_message = MissingHeaderMessage(header_name);
99 return false;
100 }
101 if (result == GET_HEADER_MULTIPLE) {
Bence Békyb28709c22018-03-06 13:03:44102 *failure_message =
103 WebSocketHandshakeStreamBase::MultipleHeaderValuesMessage(header_name);
[email protected]96868202014-01-09 10:38:04104 return false;
105 }
106 DCHECK_EQ(result, GET_HEADER_OK);
107 return true;
108}
109
110bool ValidateUpgrade(const HttpResponseHeaders* headers,
111 std::string* failure_message) {
112 std::string value;
113 GetHeaderResult result =
114 GetSingleHeaderValue(headers, websockets::kUpgrade, &value);
115 if (!ValidateHeaderHasSingleValue(result,
116 websockets::kUpgrade,
117 failure_message)) {
118 return false;
119 }
120
brettwbc17d2c82015-06-09 22:39:08121 if (!base::LowerCaseEqualsASCII(value, websockets::kWebSocketLowercase)) {
[email protected]96868202014-01-09 10:38:04122 *failure_message =
123 "'Upgrade' header value is not 'WebSocket': " + value;
124 return false;
125 }
126 return true;
127}
128
129bool ValidateSecWebSocketAccept(const HttpResponseHeaders* headers,
130 const std::string& expected,
131 std::string* failure_message) {
132 std::string actual;
133 GetHeaderResult result =
134 GetSingleHeaderValue(headers, websockets::kSecWebSocketAccept, &actual);
135 if (!ValidateHeaderHasSingleValue(result,
136 websockets::kSecWebSocketAccept,
137 failure_message)) {
138 return false;
139 }
140
141 if (expected != actual) {
142 *failure_message = "Incorrect 'Sec-WebSocket-Accept' header value";
143 return false;
144 }
145 return true;
146}
147
148bool ValidateConnection(const HttpResponseHeaders* headers,
149 std::string* failure_message) {
150 // Connection header is permitted to contain other tokens.
151 if (!headers->HasHeader(HttpRequestHeaders::kConnection)) {
152 *failure_message = MissingHeaderMessage(HttpRequestHeaders::kConnection);
153 return false;
154 }
155 if (!headers->HasHeaderValue(HttpRequestHeaders::kConnection,
156 websockets::kUpgrade)) {
157 *failure_message = "'Connection' header value must contain 'Upgrade'";
158 return false;
159 }
160 return true;
[email protected]d51365e2013-11-27 10:46:52161}
162
[email protected]d51365e2013-11-27 10:46:52163} // namespace
164
165WebSocketBasicHandshakeStream::WebSocketBasicHandshakeStream(
danakj9c5cab52016-04-16 00:54:33166 std::unique_ptr<ClientSocketHandle> connection,
[email protected]cd48ed12014-01-22 14:34:22167 WebSocketStream::ConnectDelegate* connect_delegate,
[email protected]d51365e2013-11-27 10:46:52168 bool using_proxy,
169 std::vector<std::string> requested_sub_protocols,
[email protected]8aba0172014-07-03 12:09:53170 std::vector<std::string> requested_extensions,
Adam Rice6f75c0f2018-06-04 08:00:05171 WebSocketStreamRequestAPI* request,
Bence Békyda280c62018-04-12 15:08:37172 WebSocketEndpointLockManager* websocket_endpoint_lock_manager)
Bence Békyde0be312018-03-13 17:51:58173 : result_(HandshakeResult::INCOMPLETE),
174 state_(std::move(connection),
mmenkea7da6da2016-09-01 21:56:52175 using_proxy,
176 false /* http_09_on_non_default_ports_enabled */),
[email protected]cd48ed12014-01-22 14:34:22177 connect_delegate_(connect_delegate),
yhiranoa7e05bb2014-11-06 05:40:39178 http_response_info_(nullptr),
Adam Rice8b382c602018-06-04 12:36:39179 requested_sub_protocols_(std::move(requested_sub_protocols)),
180 requested_extensions_(std::move(requested_extensions)),
Bence Békyda280c62018-04-12 15:08:37181 stream_request_(request),
Bence Békyca0da432019-01-24 15:03:20182 websocket_endpoint_lock_manager_(websocket_endpoint_lock_manager),
183 weak_ptr_factory_(this) {
[email protected]8aba0172014-07-03 12:09:53184 DCHECK(connect_delegate);
tyoshinoccfcfde2016-07-21 14:06:55185 DCHECK(request);
[email protected]8aba0172014-07-03 12:09:53186}
[email protected]d51365e2013-11-27 10:46:52187
Bence Békyde0be312018-03-13 17:51:58188WebSocketBasicHandshakeStream::~WebSocketBasicHandshakeStream() {
Adam Rice8b382c602018-06-04 12:36:39189 // Some members are "stolen" by RenewStreamForAuth() and should not be touched
190 // here. Particularly |connect_delegate_|, |stream_request_|, and
191 // |websocket_endpoint_lock_manager_|.
192
193 // TODO(ricea): What's the right thing to do here if we renewed the stream for
194 // auth? Currently we record it as INCOMPLETE.
Bence Békyde0be312018-03-13 17:51:58195 RecordHandshakeResult(result_);
196}
[email protected]d51365e2013-11-27 10:46:52197
198int WebSocketBasicHandshakeStream::InitializeStream(
199 const HttpRequestInfo* request_info,
Steven Valdezb4ff0412018-01-18 22:39:27200 bool can_send_early,
[email protected]d51365e2013-11-27 10:46:52201 RequestPriority priority,
tfarina42834112016-09-22 13:38:20202 const NetLogWithSource& net_log,
Bence Békya25e3f72018-02-13 21:13:39203 CompletionOnceCallback callback) {
Ramin Halavati20e949f2018-02-14 20:14:32204 DCHECK(request_info->traffic_annotation.is_valid());
[email protected]cd48ed12014-01-22 14:34:22205 url_ = request_info->url;
Steven Valdez1c1859172019-04-10 15:33:28206 // The WebSocket may receive a socket in the early data state from
207 // HttpNetworkTransaction, which means it must call ConfirmHandshake() for
208 // requests that need replay protection. However, the first request on any
209 // WebSocket stream is a GET with an idempotent request
210 // (https://tools.ietf.org/html/rfc6455#section-1.3), so there is no need to
211 // call ConfirmHandshake().
212 //
213 // Data after the WebSockets handshake may not be replayable, but the
214 // handshake is guaranteed to be confirmed once the HTTP response is received.
215 DCHECK(can_send_early);
216 state_.Initialize(request_info, priority, net_log);
[email protected]d51365e2013-11-27 10:46:52217 return OK;
218}
219
220int WebSocketBasicHandshakeStream::SendRequest(
221 const HttpRequestHeaders& headers,
222 HttpResponseInfo* response,
Bence Békya25e3f72018-02-13 21:13:39223 CompletionOnceCallback callback) {
[email protected]d51365e2013-11-27 10:46:52224 DCHECK(!headers.HasHeader(websockets::kSecWebSocketKey));
225 DCHECK(!headers.HasHeader(websockets::kSecWebSocketProtocol));
226 DCHECK(!headers.HasHeader(websockets::kSecWebSocketExtensions));
227 DCHECK(headers.HasHeader(HttpRequestHeaders::kOrigin));
228 DCHECK(headers.HasHeader(websockets::kUpgrade));
229 DCHECK(headers.HasHeader(HttpRequestHeaders::kConnection));
230 DCHECK(headers.HasHeader(websockets::kSecWebSocketVersion));
231 DCHECK(parser());
232
233 http_response_info_ = response;
234
235 // Create a copy of the headers object, so that we can add the
236 // Sec-WebSockey-Key header.
237 HttpRequestHeaders enriched_headers;
238 enriched_headers.CopyFrom(headers);
[email protected]a31ecc02013-12-05 08:30:55239 std::string handshake_challenge;
Bence Béky7d0c74d2018-03-05 08:31:09240 if (handshake_challenge_for_testing_.has_value()) {
241 handshake_challenge = handshake_challenge_for_testing_.value();
[email protected]a31ecc02013-12-05 08:30:55242 handshake_challenge_for_testing_.reset();
243 } else {
244 handshake_challenge = GenerateHandshakeChallenge();
245 }
[email protected]d51365e2013-11-27 10:46:52246 enriched_headers.SetHeader(websockets::kSecWebSocketKey, handshake_challenge);
247
[email protected]d51365e2013-11-27 10:46:52248 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketExtensions,
249 requested_extensions_,
250 &enriched_headers);
[email protected]0be93922014-01-29 00:42:45251 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketProtocol,
252 requested_sub_protocols_,
253 &enriched_headers);
[email protected]d51365e2013-11-27 10:46:52254
ricea11bdcd02014-11-20 09:57:07255 handshake_challenge_response_ =
256 ComputeSecWebSocketAccept(handshake_challenge);
[email protected]d51365e2013-11-27 10:46:52257
[email protected]cd48ed12014-01-22 14:34:22258 DCHECK(connect_delegate_);
Bence Béky65623972018-03-05 15:31:56259 auto request =
260 std::make_unique<WebSocketHandshakeRequestInfo>(url_, base::Time::Now());
[email protected]cd48ed12014-01-22 14:34:22261 request->headers.CopyFrom(enriched_headers);
dchengc7eeda422015-12-26 03:56:48262 connect_delegate_->OnStartOpeningHandshake(std::move(request));
[email protected]cd48ed12014-01-22 14:34:22263
Ramin Halavati20e949f2018-02-14 20:14:32264 return parser()->SendRequest(
265 state_.GenerateRequestLine(), enriched_headers,
266 NetworkTrafficAnnotationTag(state_.traffic_annotation()), response,
267 std::move(callback));
[email protected]d51365e2013-11-27 10:46:52268}
269
270int WebSocketBasicHandshakeStream::ReadResponseHeaders(
Bence Békya25e3f72018-02-13 21:13:39271 CompletionOnceCallback callback) {
[email protected]d51365e2013-11-27 10:46:52272 // HttpStreamParser uses a weak pointer when reading from the
273 // socket, so it won't be called back after being destroyed. The
274 // HttpStreamParser is owned by HttpBasicState which is owned by this object,
275 // so this use of base::Unretained() is safe.
Bence Békya25e3f72018-02-13 21:13:39276 int rv = parser()->ReadResponseHeaders(base::BindOnce(
277 &WebSocketBasicHandshakeStream::ReadResponseHeadersCallback,
278 base::Unretained(this), std::move(callback)));
[email protected]cd48ed12014-01-22 14:34:22279 if (rv == ERR_IO_PENDING)
280 return rv;
ricea24c195f2015-02-26 12:18:55281 return ValidateResponse(rv);
[email protected]d51365e2013-11-27 10:46:52282}
283
[email protected]d51365e2013-11-27 10:46:52284int WebSocketBasicHandshakeStream::ReadResponseBody(
285 IOBuffer* buf,
286 int buf_len,
Bence Békya25e3f72018-02-13 21:13:39287 CompletionOnceCallback callback) {
288 return parser()->ReadResponseBody(buf, buf_len, std::move(callback));
[email protected]d51365e2013-11-27 10:46:52289}
290
291void WebSocketBasicHandshakeStream::Close(bool not_reusable) {
292 // This class ignores the value of |not_reusable| and never lets the socket be
293 // re-used.
Matt Menkef171ff8b2019-02-05 20:06:13294 if (!parser())
295 return;
296 StreamSocket* socket = state_.connection()->socket();
297 if (socket)
298 socket->Disconnect();
299 state_.connection()->Reset();
[email protected]d51365e2013-11-27 10:46:52300}
301
302bool WebSocketBasicHandshakeStream::IsResponseBodyComplete() const {
303 return parser()->IsResponseBodyComplete();
304}
305
[email protected]d51365e2013-11-27 10:46:52306bool WebSocketBasicHandshakeStream::IsConnectionReused() const {
Matt Menkef171ff8b2019-02-05 20:06:13307 return state_.IsConnectionReused();
[email protected]d51365e2013-11-27 10:46:52308}
309
310void WebSocketBasicHandshakeStream::SetConnectionReused() {
Matt Menkef171ff8b2019-02-05 20:06:13311 state_.connection()->set_reuse_type(ClientSocketHandle::REUSED_IDLE);
[email protected]d51365e2013-11-27 10:46:52312}
313
mmenkebd84c392015-09-02 14:12:34314bool WebSocketBasicHandshakeStream::CanReuseConnection() const {
Matt Menkef171ff8b2019-02-05 20:06:13315 return parser() && state_.connection()->socket() &&
316 parser()->CanReuseConnection();
[email protected]d51365e2013-11-27 10:46:52317}
318
sclittle4de1bab92015-09-22 21:28:24319int64_t WebSocketBasicHandshakeStream::GetTotalReceivedBytes() const {
[email protected]bc92bc972013-12-13 08:32:59320 return 0;
321}
322
sclittlebe1ccf62015-09-02 19:40:36323int64_t WebSocketBasicHandshakeStream::GetTotalSentBytes() const {
324 return 0;
325}
326
rchcd379012017-04-12 21:53:32327bool WebSocketBasicHandshakeStream::GetAlternativeService(
328 AlternativeService* alternative_service) const {
329 return false;
330}
331
[email protected]d51365e2013-11-27 10:46:52332bool WebSocketBasicHandshakeStream::GetLoadTimingInfo(
333 LoadTimingInfo* load_timing_info) const {
334 return state_.connection()->GetLoadTimingInfo(IsConnectionReused(),
335 load_timing_info);
336}
337
338void WebSocketBasicHandshakeStream::GetSSLInfo(SSLInfo* ssl_info) {
Matt Menkef171ff8b2019-02-05 20:06:13339 if (!state_.connection()->socket()) {
340 ssl_info->Reset();
341 return;
342 }
[email protected]d51365e2013-11-27 10:46:52343 parser()->GetSSLInfo(ssl_info);
344}
345
346void WebSocketBasicHandshakeStream::GetSSLCertRequestInfo(
347 SSLCertRequestInfo* cert_request_info) {
Matt Menkef171ff8b2019-02-05 20:06:13348 if (!state_.connection()->socket()) {
349 cert_request_info->Reset();
350 return;
351 }
[email protected]d51365e2013-11-27 10:46:52352 parser()->GetSSLCertRequestInfo(cert_request_info);
353}
354
ttuttled9dbc652015-09-29 20:00:59355bool WebSocketBasicHandshakeStream::GetRemoteEndpoint(IPEndPoint* endpoint) {
356 if (!state_.connection() || !state_.connection()->socket())
357 return false;
358
359 return state_.connection()->socket()->GetPeerAddress(endpoint) == OK;
360}
361
zhongyica364fbb2015-12-12 03:39:12362void WebSocketBasicHandshakeStream::PopulateNetErrorDetails(
363 NetErrorDetails* /*details*/) {
364 return;
365}
366
[email protected]d51365e2013-11-27 10:46:52367void WebSocketBasicHandshakeStream::Drain(HttpNetworkSession* session) {
368 HttpResponseBodyDrainer* drainer = new HttpResponseBodyDrainer(this);
369 drainer->Start(session);
370 // |drainer| will delete itself.
371}
372
373void WebSocketBasicHandshakeStream::SetPriority(RequestPriority priority) {
374 // TODO(ricea): See TODO comment in HttpBasicStream::SetPriority(). If it is
375 // gone, then copy whatever has happened there over here.
376}
377
yhiranoa7e05bb2014-11-06 05:40:39378HttpStream* WebSocketBasicHandshakeStream::RenewStreamForAuth() {
Adam Rice8b382c602018-06-04 12:36:39379 DCHECK(IsResponseBodyComplete());
380 DCHECK(!parser()->IsMoreDataBuffered());
381 // The HttpStreamParser object still has a pointer to the connection. Just to
382 // be extra-sure it doesn't touch the connection again, delete it here rather
383 // than leaving it until the destructor is called.
384 state_.DeleteParser();
385
386 auto handshake_stream = std::make_unique<WebSocketBasicHandshakeStream>(
387 state_.ReleaseConnection(), connect_delegate_, state_.using_proxy(),
388 std::move(requested_sub_protocols_), std::move(requested_extensions_),
389 stream_request_, websocket_endpoint_lock_manager_);
390
391 stream_request_->OnBasicHandshakeStreamCreated(handshake_stream.get());
392
393 return handshake_stream.release();
yhiranoa7e05bb2014-11-06 05:40:39394}
395
danakj9c5cab52016-04-16 00:54:33396std::unique_ptr<WebSocketStream> WebSocketBasicHandshakeStream::Upgrade() {
[email protected]d51365e2013-11-27 10:46:52397 // The HttpStreamParser object has a pointer to our ClientSocketHandle. Make
398 // sure it does not touch it again before it is destroyed.
399 state_.DeleteParser();
Bence Békyda280c62018-04-12 15:08:37400 WebSocketTransportClientSocketPool::UnlockEndpoint(
401 state_.connection(), websocket_endpoint_lock_manager_);
Bence Béky7294fc22018-02-08 14:26:17402 std::unique_ptr<WebSocketStream> basic_stream =
403 std::make_unique<WebSocketBasicStream>(
404 std::make_unique<WebSocketClientSocketHandleAdapter>(
405 state_.ReleaseConnection()),
406 state_.read_buf(), sub_protocol_, extensions_);
[email protected]0be93922014-01-29 00:42:45407 DCHECK(extension_params_.get());
408 if (extension_params_->deflate_enabled) {
Bence Békyde0be312018-03-13 17:51:58409 RecordDeflateMode(
410 extension_params_->deflate_parameters.client_context_take_over_mode());
[email protected]9c50b042014-04-28 06:40:15411
Bence Béky65623972018-03-05 15:31:56412 return std::make_unique<WebSocketDeflateStream>(
dchengc7eeda422015-12-26 03:56:48413 std::move(basic_stream), extension_params_->deflate_parameters,
Bence Béky65623972018-03-05 15:31:56414 std::make_unique<WebSocketDeflatePredictorImpl>());
[email protected]0be93922014-01-29 00:42:45415 } else {
dchengc7eeda422015-12-26 03:56:48416 return basic_stream;
[email protected]0be93922014-01-29 00:42:45417 }
[email protected]d51365e2013-11-27 10:46:52418}
419
Bence Békyca0da432019-01-24 15:03:20420base::WeakPtr<WebSocketHandshakeStreamBase>
421WebSocketBasicHandshakeStream::GetWeakPtr() {
422 return weak_ptr_factory_.GetWeakPtr();
423}
424
[email protected]a31ecc02013-12-05 08:30:55425void WebSocketBasicHandshakeStream::SetWebSocketKeyForTesting(
426 const std::string& key) {
Bence Béky7d0c74d2018-03-05 08:31:09427 handshake_challenge_for_testing_ = key;
[email protected]a31ecc02013-12-05 08:30:55428}
429
[email protected]d51365e2013-11-27 10:46:52430void WebSocketBasicHandshakeStream::ReadResponseHeadersCallback(
Bence Békya25e3f72018-02-13 21:13:39431 CompletionOnceCallback callback,
[email protected]d51365e2013-11-27 10:46:52432 int result) {
Bence Békya25e3f72018-02-13 21:13:39433 std::move(callback).Run(ValidateResponse(result));
[email protected]d51365e2013-11-27 10:46:52434}
435
[email protected]cd48ed12014-01-22 14:34:22436void WebSocketBasicHandshakeStream::OnFinishOpeningHandshake() {
[email protected]cd48ed12014-01-22 14:34:22437 DCHECK(http_response_info_);
Yutaka Hirano36c94952018-05-30 21:33:33438 WebSocketDispatchOnFinishOpeningHandshake(
439 connect_delegate_, url_, http_response_info_->headers,
Tsuyoshi Horo01faed62019-02-20 22:11:37440 http_response_info_->remote_endpoint, http_response_info_->response_time);
[email protected]cd48ed12014-01-22 14:34:22441}
442
ricea24c195f2015-02-26 12:18:55443int WebSocketBasicHandshakeStream::ValidateResponse(int rv) {
[email protected]d51365e2013-11-27 10:46:52444 DCHECK(http_response_info_);
[email protected]f7e98ca2014-06-19 12:05:43445 // Most net errors happen during connection, so they are not seen by this
446 // method. The histogram for error codes is created in
447 // Delegate::OnResponseStarted in websocket_stream.cc instead.
[email protected]e5760f522014-02-05 12:28:50448 if (rv >= 0) {
[email protected]f7e98ca2014-06-19 12:05:43449 const HttpResponseHeaders* headers = http_response_info_->headers.get();
450 const int response_code = headers->response_code();
Ilya Sherman0eb39802017-12-08 20:58:18451 base::UmaHistogramSparse("Net.WebSocket.ResponseCode", response_code);
[email protected]f7e98ca2014-06-19 12:05:43452 switch (response_code) {
[email protected]e5760f522014-02-05 12:28:50453 case HTTP_SWITCHING_PROTOCOLS:
454 OnFinishOpeningHandshake();
455 return ValidateUpgradeResponse(headers);
[email protected]d51365e2013-11-27 10:46:52456
[email protected]e5760f522014-02-05 12:28:50457 // We need to pass these through for authentication to work.
458 case HTTP_UNAUTHORIZED:
459 case HTTP_PROXY_AUTHENTICATION_REQUIRED:
460 return OK;
[email protected]d51365e2013-11-27 10:46:52461
[email protected]e5760f522014-02-05 12:28:50462 // Other status codes are potentially risky (see the warnings in the
463 // WHATWG WebSocket API spec) and so are dropped by default.
464 default:
[email protected]aeb640d2014-02-21 11:03:18465 // A WebSocket server cannot be using HTTP/0.9, so if we see version
466 // 0.9, it means the response was garbage.
467 // Reporting "Unexpected response code: 200" in this case is not
468 // helpful, so use a different error message.
469 if (headers->GetHttpVersion() == HttpVersion(0, 9)) {
tyoshinoccfcfde2016-07-21 14:06:55470 OnFailure("Error during WebSocket handshake: Invalid status line");
[email protected]aeb640d2014-02-21 11:03:18471 } else {
tyoshinoccfcfde2016-07-21 14:06:55472 OnFailure(base::StringPrintf(
[email protected]aeb640d2014-02-21 11:03:18473 "Error during WebSocket handshake: Unexpected response code: %d",
[email protected]8aba0172014-07-03 12:09:53474 headers->response_code()));
[email protected]aeb640d2014-02-21 11:03:18475 }
[email protected]e5760f522014-02-05 12:28:50476 OnFinishOpeningHandshake();
Bence Békyde0be312018-03-13 17:51:58477 result_ = HandshakeResult::INVALID_STATUS;
[email protected]e5760f522014-02-05 12:28:50478 return ERR_INVALID_RESPONSE;
479 }
480 } else {
[email protected]3efc08f2014-02-07 09:33:34481 if (rv == ERR_EMPTY_RESPONSE) {
tyoshinoccfcfde2016-07-21 14:06:55482 OnFailure("Connection closed before receiving a handshake response");
Bence Békyde0be312018-03-13 17:51:58483 result_ = HandshakeResult::EMPTY_RESPONSE;
[email protected]3efc08f2014-02-07 09:33:34484 return rv;
485 }
tyoshinoccfcfde2016-07-21 14:06:55486 OnFailure(std::string("Error during WebSocket handshake: ") +
487 ErrorToString(rv));
[email protected]e5760f522014-02-05 12:28:50488 OnFinishOpeningHandshake();
ricea23c3f942015-02-02 13:35:13489 // Some error codes (for example ERR_CONNECTION_CLOSED) get changed to OK at
490 // higher levels. To prevent an unvalidated connection getting erroneously
491 // upgraded, don't pass through the status code unchanged if it is
492 // HTTP_SWITCHING_PROTOCOLS.
493 if (http_response_info_->headers &&
494 http_response_info_->headers->response_code() ==
495 HTTP_SWITCHING_PROTOCOLS) {
496 http_response_info_->headers->ReplaceStatusLine(
497 kConnectionErrorStatusLine);
Bence Békyde0be312018-03-13 17:51:58498 result_ = HandshakeResult::FAILED_SWITCHING_PROTOCOLS;
499 return rv;
ricea23c3f942015-02-02 13:35:13500 }
Bence Békyde0be312018-03-13 17:51:58501 result_ = HandshakeResult::FAILED;
[email protected]e5760f522014-02-05 12:28:50502 return rv;
[email protected]d51365e2013-11-27 10:46:52503 }
504}
505
506int WebSocketBasicHandshakeStream::ValidateUpgradeResponse(
[email protected]e5760f522014-02-05 12:28:50507 const HttpResponseHeaders* headers) {
Bence Béky65623972018-03-05 15:31:56508 extension_params_ = std::make_unique<WebSocketExtensionParams>();
[email protected]8aba0172014-07-03 12:09:53509 std::string failure_message;
Bence Békyde0be312018-03-13 17:51:58510 if (!ValidateUpgrade(headers, &failure_message)) {
511 result_ = HandshakeResult::FAILED_UPGRADE;
512 } else if (!ValidateSecWebSocketAccept(headers, handshake_challenge_response_,
513 &failure_message)) {
514 result_ = HandshakeResult::FAILED_ACCEPT;
515 } else if (!ValidateConnection(headers, &failure_message)) {
516 result_ = HandshakeResult::FAILED_CONNECTION;
517 } else if (!ValidateSubProtocol(headers, requested_sub_protocols_,
518 &sub_protocol_, &failure_message)) {
519 result_ = HandshakeResult::FAILED_SUBPROTO;
520 } else if (!ValidateExtensions(headers, &extensions_, &failure_message,
521 extension_params_.get())) {
522 result_ = HandshakeResult::FAILED_EXTENSIONS;
523 } else {
524 result_ = HandshakeResult::CONNECTED;
[email protected]d51365e2013-11-27 10:46:52525 return OK;
526 }
tyoshinoccfcfde2016-07-21 14:06:55527 OnFailure("Error during WebSocket handshake: " + failure_message);
[email protected]d51365e2013-11-27 10:46:52528 return ERR_INVALID_RESPONSE;
529}
530
tyoshinoccfcfde2016-07-21 14:06:55531void WebSocketBasicHandshakeStream::OnFailure(const std::string& message) {
Adam Riced4596a8e2018-07-13 08:06:17532 // Avoid connection reuse if auth did not happen.
533 state_.connection()->socket()->Disconnect();
tyoshinoccfcfde2016-07-21 14:06:55534 stream_request_->OnFailure(message);
[email protected]8aba0172014-07-03 12:09:53535}
536
[email protected]d51365e2013-11-27 10:46:52537} // namespace net