blob: ab5b44d21739a52e2a50a73f4ba430b752ffd9d5 [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"
Hans Wennborg0924470b2020-04-27 21:08:0515#include "base/check_op.h"
yhirano27b2b572014-10-30 11:23:4416#include "base/compiler_specific.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),
Matt Menkea31ed582019-09-19 20:14:11174 state_(std::move(connection), using_proxy),
[email protected]cd48ed12014-01-22 14:34:22175 connect_delegate_(connect_delegate),
yhiranoa7e05bb2014-11-06 05:40:39176 http_response_info_(nullptr),
Adam Rice8b382c602018-06-04 12:36:39177 requested_sub_protocols_(std::move(requested_sub_protocols)),
178 requested_extensions_(std::move(requested_extensions)),
Bence Békyda280c62018-04-12 15:08:37179 stream_request_(request),
Jeremy Romand54000b22019-07-08 18:40:16180 websocket_endpoint_lock_manager_(websocket_endpoint_lock_manager) {
[email protected]8aba0172014-07-03 12:09:53181 DCHECK(connect_delegate);
tyoshinoccfcfde2016-07-21 14:06:55182 DCHECK(request);
[email protected]8aba0172014-07-03 12:09:53183}
[email protected]d51365e2013-11-27 10:46:52184
Bence Békyde0be312018-03-13 17:51:58185WebSocketBasicHandshakeStream::~WebSocketBasicHandshakeStream() {
Adam Rice8b382c602018-06-04 12:36:39186 // Some members are "stolen" by RenewStreamForAuth() and should not be touched
187 // here. Particularly |connect_delegate_|, |stream_request_|, and
188 // |websocket_endpoint_lock_manager_|.
189
190 // TODO(ricea): What's the right thing to do here if we renewed the stream for
191 // auth? Currently we record it as INCOMPLETE.
Bence Békyde0be312018-03-13 17:51:58192 RecordHandshakeResult(result_);
193}
[email protected]d51365e2013-11-27 10:46:52194
195int WebSocketBasicHandshakeStream::InitializeStream(
196 const HttpRequestInfo* request_info,
Steven Valdezb4ff0412018-01-18 22:39:27197 bool can_send_early,
[email protected]d51365e2013-11-27 10:46:52198 RequestPriority priority,
tfarina42834112016-09-22 13:38:20199 const NetLogWithSource& net_log,
Bence Békya25e3f72018-02-13 21:13:39200 CompletionOnceCallback callback) {
Ramin Halavati20e949f2018-02-14 20:14:32201 DCHECK(request_info->traffic_annotation.is_valid());
[email protected]cd48ed12014-01-22 14:34:22202 url_ = request_info->url;
Steven Valdez1c1859172019-04-10 15:33:28203 // The WebSocket may receive a socket in the early data state from
204 // HttpNetworkTransaction, which means it must call ConfirmHandshake() for
205 // requests that need replay protection. However, the first request on any
206 // WebSocket stream is a GET with an idempotent request
207 // (https://tools.ietf.org/html/rfc6455#section-1.3), so there is no need to
208 // call ConfirmHandshake().
209 //
210 // Data after the WebSockets handshake may not be replayable, but the
211 // handshake is guaranteed to be confirmed once the HTTP response is received.
212 DCHECK(can_send_early);
213 state_.Initialize(request_info, priority, net_log);
[email protected]d51365e2013-11-27 10:46:52214 return OK;
215}
216
217int WebSocketBasicHandshakeStream::SendRequest(
218 const HttpRequestHeaders& headers,
219 HttpResponseInfo* response,
Bence Békya25e3f72018-02-13 21:13:39220 CompletionOnceCallback callback) {
[email protected]d51365e2013-11-27 10:46:52221 DCHECK(!headers.HasHeader(websockets::kSecWebSocketKey));
222 DCHECK(!headers.HasHeader(websockets::kSecWebSocketProtocol));
223 DCHECK(!headers.HasHeader(websockets::kSecWebSocketExtensions));
224 DCHECK(headers.HasHeader(HttpRequestHeaders::kOrigin));
225 DCHECK(headers.HasHeader(websockets::kUpgrade));
226 DCHECK(headers.HasHeader(HttpRequestHeaders::kConnection));
227 DCHECK(headers.HasHeader(websockets::kSecWebSocketVersion));
228 DCHECK(parser());
229
230 http_response_info_ = response;
231
232 // Create a copy of the headers object, so that we can add the
233 // Sec-WebSockey-Key header.
234 HttpRequestHeaders enriched_headers;
235 enriched_headers.CopyFrom(headers);
[email protected]a31ecc02013-12-05 08:30:55236 std::string handshake_challenge;
Bence Béky7d0c74d2018-03-05 08:31:09237 if (handshake_challenge_for_testing_.has_value()) {
238 handshake_challenge = handshake_challenge_for_testing_.value();
[email protected]a31ecc02013-12-05 08:30:55239 handshake_challenge_for_testing_.reset();
240 } else {
241 handshake_challenge = GenerateHandshakeChallenge();
242 }
[email protected]d51365e2013-11-27 10:46:52243 enriched_headers.SetHeader(websockets::kSecWebSocketKey, handshake_challenge);
244
[email protected]d51365e2013-11-27 10:46:52245 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketExtensions,
246 requested_extensions_,
247 &enriched_headers);
[email protected]0be93922014-01-29 00:42:45248 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketProtocol,
249 requested_sub_protocols_,
250 &enriched_headers);
[email protected]d51365e2013-11-27 10:46:52251
ricea11bdcd02014-11-20 09:57:07252 handshake_challenge_response_ =
253 ComputeSecWebSocketAccept(handshake_challenge);
[email protected]d51365e2013-11-27 10:46:52254
[email protected]cd48ed12014-01-22 14:34:22255 DCHECK(connect_delegate_);
Bence Béky65623972018-03-05 15:31:56256 auto request =
257 std::make_unique<WebSocketHandshakeRequestInfo>(url_, base::Time::Now());
[email protected]cd48ed12014-01-22 14:34:22258 request->headers.CopyFrom(enriched_headers);
dchengc7eeda422015-12-26 03:56:48259 connect_delegate_->OnStartOpeningHandshake(std::move(request));
[email protected]cd48ed12014-01-22 14:34:22260
Ramin Halavati20e949f2018-02-14 20:14:32261 return parser()->SendRequest(
262 state_.GenerateRequestLine(), enriched_headers,
263 NetworkTrafficAnnotationTag(state_.traffic_annotation()), response,
264 std::move(callback));
[email protected]d51365e2013-11-27 10:46:52265}
266
267int WebSocketBasicHandshakeStream::ReadResponseHeaders(
Bence Békya25e3f72018-02-13 21:13:39268 CompletionOnceCallback callback) {
[email protected]d51365e2013-11-27 10:46:52269 // HttpStreamParser uses a weak pointer when reading from the
270 // socket, so it won't be called back after being destroyed. The
271 // HttpStreamParser is owned by HttpBasicState which is owned by this object,
272 // so this use of base::Unretained() is safe.
Bence Békya25e3f72018-02-13 21:13:39273 int rv = parser()->ReadResponseHeaders(base::BindOnce(
274 &WebSocketBasicHandshakeStream::ReadResponseHeadersCallback,
275 base::Unretained(this), std::move(callback)));
[email protected]cd48ed12014-01-22 14:34:22276 if (rv == ERR_IO_PENDING)
277 return rv;
ricea24c195f2015-02-26 12:18:55278 return ValidateResponse(rv);
[email protected]d51365e2013-11-27 10:46:52279}
280
[email protected]d51365e2013-11-27 10:46:52281int WebSocketBasicHandshakeStream::ReadResponseBody(
282 IOBuffer* buf,
283 int buf_len,
Bence Békya25e3f72018-02-13 21:13:39284 CompletionOnceCallback callback) {
285 return parser()->ReadResponseBody(buf, buf_len, std::move(callback));
[email protected]d51365e2013-11-27 10:46:52286}
287
288void WebSocketBasicHandshakeStream::Close(bool not_reusable) {
289 // This class ignores the value of |not_reusable| and never lets the socket be
290 // re-used.
Matt Menkef171ff8b2019-02-05 20:06:13291 if (!parser())
292 return;
293 StreamSocket* socket = state_.connection()->socket();
294 if (socket)
295 socket->Disconnect();
296 state_.connection()->Reset();
[email protected]d51365e2013-11-27 10:46:52297}
298
299bool WebSocketBasicHandshakeStream::IsResponseBodyComplete() const {
300 return parser()->IsResponseBodyComplete();
301}
302
[email protected]d51365e2013-11-27 10:46:52303bool WebSocketBasicHandshakeStream::IsConnectionReused() const {
Matt Menkef171ff8b2019-02-05 20:06:13304 return state_.IsConnectionReused();
[email protected]d51365e2013-11-27 10:46:52305}
306
307void WebSocketBasicHandshakeStream::SetConnectionReused() {
Matt Menkef171ff8b2019-02-05 20:06:13308 state_.connection()->set_reuse_type(ClientSocketHandle::REUSED_IDLE);
[email protected]d51365e2013-11-27 10:46:52309}
310
mmenkebd84c392015-09-02 14:12:34311bool WebSocketBasicHandshakeStream::CanReuseConnection() const {
Matt Menkef171ff8b2019-02-05 20:06:13312 return parser() && state_.connection()->socket() &&
313 parser()->CanReuseConnection();
[email protected]d51365e2013-11-27 10:46:52314}
315
sclittle4de1bab92015-09-22 21:28:24316int64_t WebSocketBasicHandshakeStream::GetTotalReceivedBytes() const {
[email protected]bc92bc972013-12-13 08:32:59317 return 0;
318}
319
sclittlebe1ccf62015-09-02 19:40:36320int64_t WebSocketBasicHandshakeStream::GetTotalSentBytes() const {
321 return 0;
322}
323
rchcd379012017-04-12 21:53:32324bool WebSocketBasicHandshakeStream::GetAlternativeService(
325 AlternativeService* alternative_service) const {
326 return false;
327}
328
[email protected]d51365e2013-11-27 10:46:52329bool WebSocketBasicHandshakeStream::GetLoadTimingInfo(
330 LoadTimingInfo* load_timing_info) const {
331 return state_.connection()->GetLoadTimingInfo(IsConnectionReused(),
332 load_timing_info);
333}
334
335void WebSocketBasicHandshakeStream::GetSSLInfo(SSLInfo* ssl_info) {
Matt Menkef171ff8b2019-02-05 20:06:13336 if (!state_.connection()->socket()) {
337 ssl_info->Reset();
338 return;
339 }
[email protected]d51365e2013-11-27 10:46:52340 parser()->GetSSLInfo(ssl_info);
341}
342
343void WebSocketBasicHandshakeStream::GetSSLCertRequestInfo(
344 SSLCertRequestInfo* cert_request_info) {
Matt Menkef171ff8b2019-02-05 20:06:13345 if (!state_.connection()->socket()) {
346 cert_request_info->Reset();
347 return;
348 }
[email protected]d51365e2013-11-27 10:46:52349 parser()->GetSSLCertRequestInfo(cert_request_info);
350}
351
ttuttled9dbc652015-09-29 20:00:59352bool WebSocketBasicHandshakeStream::GetRemoteEndpoint(IPEndPoint* endpoint) {
353 if (!state_.connection() || !state_.connection()->socket())
354 return false;
355
356 return state_.connection()->socket()->GetPeerAddress(endpoint) == OK;
357}
358
zhongyica364fbb2015-12-12 03:39:12359void WebSocketBasicHandshakeStream::PopulateNetErrorDetails(
360 NetErrorDetails* /*details*/) {
361 return;
362}
363
[email protected]d51365e2013-11-27 10:46:52364void WebSocketBasicHandshakeStream::Drain(HttpNetworkSession* session) {
365 HttpResponseBodyDrainer* drainer = new HttpResponseBodyDrainer(this);
366 drainer->Start(session);
367 // |drainer| will delete itself.
368}
369
370void WebSocketBasicHandshakeStream::SetPriority(RequestPriority priority) {
371 // TODO(ricea): See TODO comment in HttpBasicStream::SetPriority(). If it is
372 // gone, then copy whatever has happened there over here.
373}
374
yhiranoa7e05bb2014-11-06 05:40:39375HttpStream* WebSocketBasicHandshakeStream::RenewStreamForAuth() {
Adam Rice8b382c602018-06-04 12:36:39376 DCHECK(IsResponseBodyComplete());
377 DCHECK(!parser()->IsMoreDataBuffered());
378 // The HttpStreamParser object still has a pointer to the connection. Just to
379 // be extra-sure it doesn't touch the connection again, delete it here rather
380 // than leaving it until the destructor is called.
381 state_.DeleteParser();
382
383 auto handshake_stream = std::make_unique<WebSocketBasicHandshakeStream>(
384 state_.ReleaseConnection(), connect_delegate_, state_.using_proxy(),
385 std::move(requested_sub_protocols_), std::move(requested_extensions_),
386 stream_request_, websocket_endpoint_lock_manager_);
387
388 stream_request_->OnBasicHandshakeStreamCreated(handshake_stream.get());
389
390 return handshake_stream.release();
yhiranoa7e05bb2014-11-06 05:40:39391}
392
Cammie Smith Barnes4a5d72f2020-12-17 21:47:04393const std::vector<std::string>& WebSocketBasicHandshakeStream::GetDnsAliases()
394 const {
395 return state_.GetDnsAliases();
396}
397
Bence Béky334ddfc22021-03-12 15:18:13398base::StringPiece WebSocketBasicHandshakeStream::GetAcceptChViaAlps() const {
399 return {};
400}
401
danakj9c5cab52016-04-16 00:54:33402std::unique_ptr<WebSocketStream> WebSocketBasicHandshakeStream::Upgrade() {
[email protected]d51365e2013-11-27 10:46:52403 // The HttpStreamParser object has a pointer to our ClientSocketHandle. Make
404 // sure it does not touch it again before it is destroyed.
405 state_.DeleteParser();
Bence Békyda280c62018-04-12 15:08:37406 WebSocketTransportClientSocketPool::UnlockEndpoint(
407 state_.connection(), websocket_endpoint_lock_manager_);
Bence Béky7294fc22018-02-08 14:26:17408 std::unique_ptr<WebSocketStream> basic_stream =
409 std::make_unique<WebSocketBasicStream>(
410 std::make_unique<WebSocketClientSocketHandleAdapter>(
411 state_.ReleaseConnection()),
412 state_.read_buf(), sub_protocol_, extensions_);
[email protected]0be93922014-01-29 00:42:45413 DCHECK(extension_params_.get());
414 if (extension_params_->deflate_enabled) {
Bence Béky65623972018-03-05 15:31:56415 return std::make_unique<WebSocketDeflateStream>(
dchengc7eeda422015-12-26 03:56:48416 std::move(basic_stream), extension_params_->deflate_parameters,
Bence Béky65623972018-03-05 15:31:56417 std::make_unique<WebSocketDeflatePredictorImpl>());
[email protected]0be93922014-01-29 00:42:45418 }
Adam Riceb0237282019-06-20 14:14:02419
420 return basic_stream;
[email protected]d51365e2013-11-27 10:46:52421}
422
Bence Békyca0da432019-01-24 15:03:20423base::WeakPtr<WebSocketHandshakeStreamBase>
424WebSocketBasicHandshakeStream::GetWeakPtr() {
425 return weak_ptr_factory_.GetWeakPtr();
426}
427
[email protected]a31ecc02013-12-05 08:30:55428void WebSocketBasicHandshakeStream::SetWebSocketKeyForTesting(
429 const std::string& key) {
Bence Béky7d0c74d2018-03-05 08:31:09430 handshake_challenge_for_testing_ = key;
[email protected]a31ecc02013-12-05 08:30:55431}
432
[email protected]d51365e2013-11-27 10:46:52433void WebSocketBasicHandshakeStream::ReadResponseHeadersCallback(
Bence Békya25e3f72018-02-13 21:13:39434 CompletionOnceCallback callback,
[email protected]d51365e2013-11-27 10:46:52435 int result) {
Bence Békya25e3f72018-02-13 21:13:39436 std::move(callback).Run(ValidateResponse(result));
[email protected]d51365e2013-11-27 10:46:52437}
438
ricea24c195f2015-02-26 12:18:55439int WebSocketBasicHandshakeStream::ValidateResponse(int rv) {
[email protected]d51365e2013-11-27 10:46:52440 DCHECK(http_response_info_);
[email protected]f7e98ca2014-06-19 12:05:43441 // Most net errors happen during connection, so they are not seen by this
442 // method. The histogram for error codes is created in
443 // Delegate::OnResponseStarted in websocket_stream.cc instead.
[email protected]e5760f522014-02-05 12:28:50444 if (rv >= 0) {
[email protected]f7e98ca2014-06-19 12:05:43445 const HttpResponseHeaders* headers = http_response_info_->headers.get();
446 const int response_code = headers->response_code();
Ilya Sherman0eb39802017-12-08 20:58:18447 base::UmaHistogramSparse("Net.WebSocket.ResponseCode", response_code);
[email protected]f7e98ca2014-06-19 12:05:43448 switch (response_code) {
[email protected]e5760f522014-02-05 12:28:50449 case HTTP_SWITCHING_PROTOCOLS:
[email protected]e5760f522014-02-05 12:28:50450 return ValidateUpgradeResponse(headers);
[email protected]d51365e2013-11-27 10:46:52451
[email protected]e5760f522014-02-05 12:28:50452 // We need to pass these through for authentication to work.
453 case HTTP_UNAUTHORIZED:
454 case HTTP_PROXY_AUTHENTICATION_REQUIRED:
455 return OK;
[email protected]d51365e2013-11-27 10:46:52456
[email protected]e5760f522014-02-05 12:28:50457 // Other status codes are potentially risky (see the warnings in the
458 // WHATWG WebSocket API spec) and so are dropped by default.
459 default:
[email protected]aeb640d2014-02-21 11:03:18460 // A WebSocket server cannot be using HTTP/0.9, so if we see version
461 // 0.9, it means the response was garbage.
462 // Reporting "Unexpected response code: 200" in this case is not
463 // helpful, so use a different error message.
464 if (headers->GetHttpVersion() == HttpVersion(0, 9)) {
Adam Langleya48b636a2020-11-12 23:42:52465 OnFailure("Error during WebSocket handshake: Invalid status line",
Anton Bikineev068d2912021-05-15 20:43:52466 ERR_FAILED, absl::nullopt);
[email protected]aeb640d2014-02-21 11:03:18467 } else {
Adam Langleya48b636a2020-11-12 23:42:52468 OnFailure(base::StringPrintf("Error during WebSocket handshake: "
469 "Unexpected response code: %d",
470 headers->response_code()),
471 ERR_FAILED, headers->response_code());
[email protected]aeb640d2014-02-21 11:03:18472 }
Bence Békyde0be312018-03-13 17:51:58473 result_ = HandshakeResult::INVALID_STATUS;
[email protected]e5760f522014-02-05 12:28:50474 return ERR_INVALID_RESPONSE;
475 }
476 } else {
[email protected]3efc08f2014-02-07 09:33:34477 if (rv == ERR_EMPTY_RESPONSE) {
Adam Langleya48b636a2020-11-12 23:42:52478 OnFailure("Connection closed before receiving a handshake response", rv,
Anton Bikineev068d2912021-05-15 20:43:52479 absl::nullopt);
Bence Békyde0be312018-03-13 17:51:58480 result_ = HandshakeResult::EMPTY_RESPONSE;
[email protected]3efc08f2014-02-07 09:33:34481 return rv;
482 }
Adam Langleya48b636a2020-11-12 23:42:52483 OnFailure(
484 std::string("Error during WebSocket handshake: ") + ErrorToString(rv),
Anton Bikineev068d2912021-05-15 20:43:52485 rv, absl::nullopt);
ricea23c3f942015-02-02 13:35:13486 // Some error codes (for example ERR_CONNECTION_CLOSED) get changed to OK at
487 // higher levels. To prevent an unvalidated connection getting erroneously
488 // upgraded, don't pass through the status code unchanged if it is
489 // HTTP_SWITCHING_PROTOCOLS.
490 if (http_response_info_->headers &&
491 http_response_info_->headers->response_code() ==
492 HTTP_SWITCHING_PROTOCOLS) {
493 http_response_info_->headers->ReplaceStatusLine(
494 kConnectionErrorStatusLine);
Bence Békyde0be312018-03-13 17:51:58495 result_ = HandshakeResult::FAILED_SWITCHING_PROTOCOLS;
496 return rv;
ricea23c3f942015-02-02 13:35:13497 }
Bence Békyde0be312018-03-13 17:51:58498 result_ = HandshakeResult::FAILED;
[email protected]e5760f522014-02-05 12:28:50499 return rv;
[email protected]d51365e2013-11-27 10:46:52500 }
501}
502
503int WebSocketBasicHandshakeStream::ValidateUpgradeResponse(
[email protected]e5760f522014-02-05 12:28:50504 const HttpResponseHeaders* headers) {
Bence Béky65623972018-03-05 15:31:56505 extension_params_ = std::make_unique<WebSocketExtensionParams>();
[email protected]8aba0172014-07-03 12:09:53506 std::string failure_message;
Bence Békyde0be312018-03-13 17:51:58507 if (!ValidateUpgrade(headers, &failure_message)) {
508 result_ = HandshakeResult::FAILED_UPGRADE;
509 } else if (!ValidateSecWebSocketAccept(headers, handshake_challenge_response_,
510 &failure_message)) {
511 result_ = HandshakeResult::FAILED_ACCEPT;
512 } else if (!ValidateConnection(headers, &failure_message)) {
513 result_ = HandshakeResult::FAILED_CONNECTION;
514 } else if (!ValidateSubProtocol(headers, requested_sub_protocols_,
515 &sub_protocol_, &failure_message)) {
516 result_ = HandshakeResult::FAILED_SUBPROTO;
517 } else if (!ValidateExtensions(headers, &extensions_, &failure_message,
518 extension_params_.get())) {
519 result_ = HandshakeResult::FAILED_EXTENSIONS;
520 } else {
521 result_ = HandshakeResult::CONNECTED;
[email protected]d51365e2013-11-27 10:46:52522 return OK;
523 }
Adam Langleya48b636a2020-11-12 23:42:52524 OnFailure("Error during WebSocket handshake: " + failure_message, ERR_FAILED,
Anton Bikineev068d2912021-05-15 20:43:52525 absl::nullopt);
[email protected]d51365e2013-11-27 10:46:52526 return ERR_INVALID_RESPONSE;
527}
528
Adam Langleya48b636a2020-11-12 23:42:52529void WebSocketBasicHandshakeStream::OnFailure(
530 const std::string& message,
531 int net_error,
Anton Bikineev068d2912021-05-15 20:43:52532 absl::optional<int> response_code) {
Adam Riced4596a8e2018-07-13 08:06:17533 // Avoid connection reuse if auth did not happen.
534 state_.connection()->socket()->Disconnect();
Adam Langleya48b636a2020-11-12 23:42:52535 stream_request_->OnFailure(message, net_error, response_code);
[email protected]8aba0172014-07-03 12:09:53536}
537
[email protected]d51365e2013-11-27 10:46:52538} // namespace net