blob: 5ad9818333c45dcf41e9228a47246f66b17f9c82 [file] [log] [blame]
Avi Drissman64595482022-09-14 20:52:291// Copyright 2013 The Chromium Authors
[email protected]d51365e2013-11-27 10:46:522// 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]0be93922014-01-29 00:42:4518#include "base/strings/string_number_conversions.h"
[email protected]69d7a492014-02-19 08:36:3219#include "base/strings/string_piece.h"
[email protected]d51365e2013-11-27 10:46:5220#include "base/strings/string_util.h"
[email protected]96868202014-01-09 10:38:0421#include "base/strings/stringprintf.h"
[email protected]cd48ed12014-01-22 14:34:2222#include "base/time/time.h"
[email protected]d51365e2013-11-27 10:46:5223#include "crypto/random.h"
halton.huo299e2002014-12-02 04:39:2424#include "net/base/io_buffer.h"
Tsuyoshi Horo01faed62019-02-20 22:11:3725#include "net/base/ip_endpoint.h"
Tsuyoshi Horob074f8762022-07-22 23:25:1426#include "net/http/http_network_session.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');
Daniel Cheng5feb16f2022-02-28 06:52:0774 crypto::RandBytes(std::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,
David Benjaminb6c2dd162022-10-24 10:46:0681 base::StringPiece name,
[email protected]96868202014-01-09 10:38:0482 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
Dan McArdle80e9dc82022-05-23 01:43:12121 if (!base::EqualsCaseInsensitiveASCII(value,
122 websockets::kWebSocketLowercase)) {
[email protected]96868202014-01-09 10:38:04123 *failure_message =
124 "'Upgrade' header value is not 'WebSocket': " + value;
125 return false;
126 }
127 return true;
128}
129
130bool ValidateSecWebSocketAccept(const HttpResponseHeaders* headers,
131 const std::string& expected,
132 std::string* failure_message) {
133 std::string actual;
134 GetHeaderResult result =
135 GetSingleHeaderValue(headers, websockets::kSecWebSocketAccept, &actual);
136 if (!ValidateHeaderHasSingleValue(result,
137 websockets::kSecWebSocketAccept,
138 failure_message)) {
139 return false;
140 }
141
142 if (expected != actual) {
143 *failure_message = "Incorrect 'Sec-WebSocket-Accept' header value";
144 return false;
145 }
146 return true;
147}
148
149bool ValidateConnection(const HttpResponseHeaders* headers,
150 std::string* failure_message) {
151 // Connection header is permitted to contain other tokens.
152 if (!headers->HasHeader(HttpRequestHeaders::kConnection)) {
153 *failure_message = MissingHeaderMessage(HttpRequestHeaders::kConnection);
154 return false;
155 }
156 if (!headers->HasHeaderValue(HttpRequestHeaders::kConnection,
157 websockets::kUpgrade)) {
158 *failure_message = "'Connection' header value must contain 'Upgrade'";
159 return false;
160 }
161 return true;
[email protected]d51365e2013-11-27 10:46:52162}
163
Nanami Mikiyaca3588c2022-01-31 03:22:25164base::Value NetLogFailureParam(int net_error, const std::string& message) {
Travis Skareadae7ff2022-07-27 16:23:33165 base::Value::Dict dict;
166 dict.Set("net_error", net_error);
167 dict.Set("message", message);
168 return base::Value(std::move(dict));
Nanami Mikiyaca3588c2022-01-31 03:22:25169}
170
[email protected]d51365e2013-11-27 10:46:52171} // namespace
172
173WebSocketBasicHandshakeStream::WebSocketBasicHandshakeStream(
danakj9c5cab52016-04-16 00:54:33174 std::unique_ptr<ClientSocketHandle> connection,
[email protected]cd48ed12014-01-22 14:34:22175 WebSocketStream::ConnectDelegate* connect_delegate,
[email protected]d51365e2013-11-27 10:46:52176 bool using_proxy,
177 std::vector<std::string> requested_sub_protocols,
[email protected]8aba0172014-07-03 12:09:53178 std::vector<std::string> requested_extensions,
Adam Rice6f75c0f2018-06-04 08:00:05179 WebSocketStreamRequestAPI* request,
Bence Békyda280c62018-04-12 15:08:37180 WebSocketEndpointLockManager* websocket_endpoint_lock_manager)
Tsuyoshi Horoa0b9c0f2022-06-09 01:41:51181 : state_(std::move(connection), using_proxy),
[email protected]cd48ed12014-01-22 14:34:22182 connect_delegate_(connect_delegate),
Adam Rice8b382c602018-06-04 12:36:39183 requested_sub_protocols_(std::move(requested_sub_protocols)),
184 requested_extensions_(std::move(requested_extensions)),
Bence Békyda280c62018-04-12 15:08:37185 stream_request_(request),
Jeremy Romand54000b22019-07-08 18:40:16186 websocket_endpoint_lock_manager_(websocket_endpoint_lock_manager) {
[email protected]8aba0172014-07-03 12:09:53187 DCHECK(connect_delegate);
tyoshinoccfcfde2016-07-21 14:06:55188 DCHECK(request);
[email protected]8aba0172014-07-03 12:09:53189}
[email protected]d51365e2013-11-27 10:46:52190
Bence Békyde0be312018-03-13 17:51:58191WebSocketBasicHandshakeStream::~WebSocketBasicHandshakeStream() {
Adam Rice8b382c602018-06-04 12:36:39192 // Some members are "stolen" by RenewStreamForAuth() and should not be touched
193 // here. Particularly |connect_delegate_|, |stream_request_|, and
194 // |websocket_endpoint_lock_manager_|.
195
196 // TODO(ricea): What's the right thing to do here if we renewed the stream for
197 // auth? Currently we record it as INCOMPLETE.
Bence Békyde0be312018-03-13 17:51:58198 RecordHandshakeResult(result_);
199}
[email protected]d51365e2013-11-27 10:46:52200
Ali Beyada0b1a1c2022-04-08 20:08:14201void WebSocketBasicHandshakeStream::RegisterRequest(
202 const HttpRequestInfo* request_info) {
203 DCHECK(request_info);
204 DCHECK(request_info->traffic_annotation.is_valid());
205 request_info_ = request_info;
206}
207
[email protected]d51365e2013-11-27 10:46:52208int WebSocketBasicHandshakeStream::InitializeStream(
Steven Valdezb4ff0412018-01-18 22:39:27209 bool can_send_early,
[email protected]d51365e2013-11-27 10:46:52210 RequestPriority priority,
tfarina42834112016-09-22 13:38:20211 const NetLogWithSource& net_log,
Bence Békya25e3f72018-02-13 21:13:39212 CompletionOnceCallback callback) {
Ali Beyada0b1a1c2022-04-08 20:08:14213 url_ = request_info_->url;
Nanami Mikiyaca3588c2022-01-31 03:22:25214 net_log_ = net_log;
Steven Valdez1c1859172019-04-10 15:33:28215 // The WebSocket may receive a socket in the early data state from
216 // HttpNetworkTransaction, which means it must call ConfirmHandshake() for
217 // requests that need replay protection. However, the first request on any
218 // WebSocket stream is a GET with an idempotent request
219 // (https://tools.ietf.org/html/rfc6455#section-1.3), so there is no need to
220 // call ConfirmHandshake().
221 //
222 // Data after the WebSockets handshake may not be replayable, but the
223 // handshake is guaranteed to be confirmed once the HTTP response is received.
224 DCHECK(can_send_early);
Ali Beyada0b1a1c2022-04-08 20:08:14225 state_.Initialize(request_info_, priority, net_log);
226 // RequestInfo is no longer needed after this point.
227 request_info_ = nullptr;
[email protected]d51365e2013-11-27 10:46:52228 return OK;
229}
230
231int WebSocketBasicHandshakeStream::SendRequest(
232 const HttpRequestHeaders& headers,
233 HttpResponseInfo* response,
Bence Békya25e3f72018-02-13 21:13:39234 CompletionOnceCallback callback) {
[email protected]d51365e2013-11-27 10:46:52235 DCHECK(!headers.HasHeader(websockets::kSecWebSocketKey));
236 DCHECK(!headers.HasHeader(websockets::kSecWebSocketProtocol));
237 DCHECK(!headers.HasHeader(websockets::kSecWebSocketExtensions));
238 DCHECK(headers.HasHeader(HttpRequestHeaders::kOrigin));
239 DCHECK(headers.HasHeader(websockets::kUpgrade));
240 DCHECK(headers.HasHeader(HttpRequestHeaders::kConnection));
241 DCHECK(headers.HasHeader(websockets::kSecWebSocketVersion));
242 DCHECK(parser());
243
244 http_response_info_ = response;
245
246 // Create a copy of the headers object, so that we can add the
247 // Sec-WebSockey-Key header.
248 HttpRequestHeaders enriched_headers;
249 enriched_headers.CopyFrom(headers);
[email protected]a31ecc02013-12-05 08:30:55250 std::string handshake_challenge;
Bence Béky7d0c74d2018-03-05 08:31:09251 if (handshake_challenge_for_testing_.has_value()) {
252 handshake_challenge = handshake_challenge_for_testing_.value();
[email protected]a31ecc02013-12-05 08:30:55253 handshake_challenge_for_testing_.reset();
254 } else {
255 handshake_challenge = GenerateHandshakeChallenge();
256 }
[email protected]d51365e2013-11-27 10:46:52257 enriched_headers.SetHeader(websockets::kSecWebSocketKey, handshake_challenge);
258
[email protected]d51365e2013-11-27 10:46:52259 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketExtensions,
260 requested_extensions_,
261 &enriched_headers);
[email protected]0be93922014-01-29 00:42:45262 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketProtocol,
263 requested_sub_protocols_,
264 &enriched_headers);
[email protected]d51365e2013-11-27 10:46:52265
ricea11bdcd02014-11-20 09:57:07266 handshake_challenge_response_ =
267 ComputeSecWebSocketAccept(handshake_challenge);
[email protected]d51365e2013-11-27 10:46:52268
[email protected]cd48ed12014-01-22 14:34:22269 DCHECK(connect_delegate_);
Bence Béky65623972018-03-05 15:31:56270 auto request =
271 std::make_unique<WebSocketHandshakeRequestInfo>(url_, base::Time::Now());
[email protected]cd48ed12014-01-22 14:34:22272 request->headers.CopyFrom(enriched_headers);
dchengc7eeda422015-12-26 03:56:48273 connect_delegate_->OnStartOpeningHandshake(std::move(request));
[email protected]cd48ed12014-01-22 14:34:22274
Ramin Halavati20e949f2018-02-14 20:14:32275 return parser()->SendRequest(
276 state_.GenerateRequestLine(), enriched_headers,
277 NetworkTrafficAnnotationTag(state_.traffic_annotation()), response,
278 std::move(callback));
[email protected]d51365e2013-11-27 10:46:52279}
280
281int WebSocketBasicHandshakeStream::ReadResponseHeaders(
Bence Békya25e3f72018-02-13 21:13:39282 CompletionOnceCallback callback) {
[email protected]d51365e2013-11-27 10:46:52283 // HttpStreamParser uses a weak pointer when reading from the
284 // socket, so it won't be called back after being destroyed. The
285 // HttpStreamParser is owned by HttpBasicState which is owned by this object,
286 // so this use of base::Unretained() is safe.
Bence Békya25e3f72018-02-13 21:13:39287 int rv = parser()->ReadResponseHeaders(base::BindOnce(
288 &WebSocketBasicHandshakeStream::ReadResponseHeadersCallback,
289 base::Unretained(this), std::move(callback)));
[email protected]cd48ed12014-01-22 14:34:22290 if (rv == ERR_IO_PENDING)
291 return rv;
ricea24c195f2015-02-26 12:18:55292 return ValidateResponse(rv);
[email protected]d51365e2013-11-27 10:46:52293}
294
[email protected]d51365e2013-11-27 10:46:52295int WebSocketBasicHandshakeStream::ReadResponseBody(
296 IOBuffer* buf,
297 int buf_len,
Bence Békya25e3f72018-02-13 21:13:39298 CompletionOnceCallback callback) {
299 return parser()->ReadResponseBody(buf, buf_len, std::move(callback));
[email protected]d51365e2013-11-27 10:46:52300}
301
302void WebSocketBasicHandshakeStream::Close(bool not_reusable) {
303 // This class ignores the value of |not_reusable| and never lets the socket be
304 // re-used.
Matt Menkef171ff8b2019-02-05 20:06:13305 if (!parser())
306 return;
307 StreamSocket* socket = state_.connection()->socket();
308 if (socket)
309 socket->Disconnect();
310 state_.connection()->Reset();
[email protected]d51365e2013-11-27 10:46:52311}
312
313bool WebSocketBasicHandshakeStream::IsResponseBodyComplete() const {
314 return parser()->IsResponseBodyComplete();
315}
316
[email protected]d51365e2013-11-27 10:46:52317bool WebSocketBasicHandshakeStream::IsConnectionReused() const {
Matt Menkef171ff8b2019-02-05 20:06:13318 return state_.IsConnectionReused();
[email protected]d51365e2013-11-27 10:46:52319}
320
321void WebSocketBasicHandshakeStream::SetConnectionReused() {
Matt Menkef171ff8b2019-02-05 20:06:13322 state_.connection()->set_reuse_type(ClientSocketHandle::REUSED_IDLE);
[email protected]d51365e2013-11-27 10:46:52323}
324
mmenkebd84c392015-09-02 14:12:34325bool WebSocketBasicHandshakeStream::CanReuseConnection() const {
Matt Menkef171ff8b2019-02-05 20:06:13326 return parser() && state_.connection()->socket() &&
327 parser()->CanReuseConnection();
[email protected]d51365e2013-11-27 10:46:52328}
329
sclittle4de1bab92015-09-22 21:28:24330int64_t WebSocketBasicHandshakeStream::GetTotalReceivedBytes() const {
[email protected]bc92bc972013-12-13 08:32:59331 return 0;
332}
333
sclittlebe1ccf62015-09-02 19:40:36334int64_t WebSocketBasicHandshakeStream::GetTotalSentBytes() const {
335 return 0;
336}
337
rchcd379012017-04-12 21:53:32338bool WebSocketBasicHandshakeStream::GetAlternativeService(
339 AlternativeService* alternative_service) const {
340 return false;
341}
342
[email protected]d51365e2013-11-27 10:46:52343bool WebSocketBasicHandshakeStream::GetLoadTimingInfo(
344 LoadTimingInfo* load_timing_info) const {
345 return state_.connection()->GetLoadTimingInfo(IsConnectionReused(),
346 load_timing_info);
347}
348
349void WebSocketBasicHandshakeStream::GetSSLInfo(SSLInfo* ssl_info) {
Matt Menkef171ff8b2019-02-05 20:06:13350 if (!state_.connection()->socket()) {
351 ssl_info->Reset();
352 return;
353 }
[email protected]d51365e2013-11-27 10:46:52354 parser()->GetSSLInfo(ssl_info);
355}
356
357void WebSocketBasicHandshakeStream::GetSSLCertRequestInfo(
358 SSLCertRequestInfo* cert_request_info) {
Matt Menkef171ff8b2019-02-05 20:06:13359 if (!state_.connection()->socket()) {
360 cert_request_info->Reset();
361 return;
362 }
[email protected]d51365e2013-11-27 10:46:52363 parser()->GetSSLCertRequestInfo(cert_request_info);
364}
365
Titouan Rigoudy5cf08f12022-05-20 15:49:22366int WebSocketBasicHandshakeStream::GetRemoteEndpoint(IPEndPoint* endpoint) {
ttuttled9dbc652015-09-29 20:00:59367 if (!state_.connection() || !state_.connection()->socket())
Titouan Rigoudy5cf08f12022-05-20 15:49:22368 return ERR_SOCKET_NOT_CONNECTED;
ttuttled9dbc652015-09-29 20:00:59369
Titouan Rigoudy5cf08f12022-05-20 15:49:22370 return state_.connection()->socket()->GetPeerAddress(endpoint);
ttuttled9dbc652015-09-29 20:00:59371}
372
zhongyica364fbb2015-12-12 03:39:12373void WebSocketBasicHandshakeStream::PopulateNetErrorDetails(
374 NetErrorDetails* /*details*/) {
375 return;
376}
377
[email protected]d51365e2013-11-27 10:46:52378void WebSocketBasicHandshakeStream::Drain(HttpNetworkSession* session) {
Tsuyoshi Horob074f8762022-07-22 23:25:14379 session->StartResponseDrainer(
380 std::make_unique<HttpResponseBodyDrainer>(this));
[email protected]d51365e2013-11-27 10:46:52381 // |drainer| will delete itself.
382}
383
384void WebSocketBasicHandshakeStream::SetPriority(RequestPriority priority) {
385 // TODO(ricea): See TODO comment in HttpBasicStream::SetPriority(). If it is
386 // gone, then copy whatever has happened there over here.
387}
388
Tsuyoshi Horo34e23cc2022-07-11 02:04:05389std::unique_ptr<HttpStream>
390WebSocketBasicHandshakeStream::RenewStreamForAuth() {
Adam Rice8b382c602018-06-04 12:36:39391 DCHECK(IsResponseBodyComplete());
392 DCHECK(!parser()->IsMoreDataBuffered());
393 // The HttpStreamParser object still has a pointer to the connection. Just to
394 // be extra-sure it doesn't touch the connection again, delete it here rather
395 // than leaving it until the destructor is called.
396 state_.DeleteParser();
397
398 auto handshake_stream = std::make_unique<WebSocketBasicHandshakeStream>(
399 state_.ReleaseConnection(), connect_delegate_, state_.using_proxy(),
400 std::move(requested_sub_protocols_), std::move(requested_extensions_),
401 stream_request_, websocket_endpoint_lock_manager_);
402
403 stream_request_->OnBasicHandshakeStreamCreated(handshake_stream.get());
404
Tsuyoshi Horo34e23cc2022-07-11 02:04:05405 return handshake_stream;
yhiranoa7e05bb2014-11-06 05:40:39406}
407
Eric Orthac661912022-01-10 21:44:17408const std::set<std::string>& WebSocketBasicHandshakeStream::GetDnsAliases()
Cammie Smith Barnes4a5d72f2020-12-17 21:47:04409 const {
410 return state_.GetDnsAliases();
411}
412
Bence Béky334ddfc22021-03-12 15:18:13413base::StringPiece WebSocketBasicHandshakeStream::GetAcceptChViaAlps() const {
414 return {};
415}
416
danakj9c5cab52016-04-16 00:54:33417std::unique_ptr<WebSocketStream> WebSocketBasicHandshakeStream::Upgrade() {
[email protected]d51365e2013-11-27 10:46:52418 // The HttpStreamParser object has a pointer to our ClientSocketHandle. Make
419 // sure it does not touch it again before it is destroyed.
420 state_.DeleteParser();
Bence Békyda280c62018-04-12 15:08:37421 WebSocketTransportClientSocketPool::UnlockEndpoint(
422 state_.connection(), websocket_endpoint_lock_manager_);
Bence Béky7294fc22018-02-08 14:26:17423 std::unique_ptr<WebSocketStream> basic_stream =
424 std::make_unique<WebSocketBasicStream>(
425 std::make_unique<WebSocketClientSocketHandleAdapter>(
426 state_.ReleaseConnection()),
Nanami Mikiyad6b837e2022-02-01 05:58:57427 state_.read_buf(), sub_protocol_, extensions_, net_log_);
[email protected]0be93922014-01-29 00:42:45428 DCHECK(extension_params_.get());
429 if (extension_params_->deflate_enabled) {
Bence Béky65623972018-03-05 15:31:56430 return std::make_unique<WebSocketDeflateStream>(
dchengc7eeda422015-12-26 03:56:48431 std::move(basic_stream), extension_params_->deflate_parameters,
Bence Béky65623972018-03-05 15:31:56432 std::make_unique<WebSocketDeflatePredictorImpl>());
[email protected]0be93922014-01-29 00:42:45433 }
Adam Riceb0237282019-06-20 14:14:02434
435 return basic_stream;
[email protected]d51365e2013-11-27 10:46:52436}
437
Bence Békyca0da432019-01-24 15:03:20438base::WeakPtr<WebSocketHandshakeStreamBase>
439WebSocketBasicHandshakeStream::GetWeakPtr() {
440 return weak_ptr_factory_.GetWeakPtr();
441}
442
[email protected]a31ecc02013-12-05 08:30:55443void WebSocketBasicHandshakeStream::SetWebSocketKeyForTesting(
444 const std::string& key) {
Bence Béky7d0c74d2018-03-05 08:31:09445 handshake_challenge_for_testing_ = key;
[email protected]a31ecc02013-12-05 08:30:55446}
447
[email protected]d51365e2013-11-27 10:46:52448void WebSocketBasicHandshakeStream::ReadResponseHeadersCallback(
Bence Békya25e3f72018-02-13 21:13:39449 CompletionOnceCallback callback,
[email protected]d51365e2013-11-27 10:46:52450 int result) {
Bence Békya25e3f72018-02-13 21:13:39451 std::move(callback).Run(ValidateResponse(result));
[email protected]d51365e2013-11-27 10:46:52452}
453
ricea24c195f2015-02-26 12:18:55454int WebSocketBasicHandshakeStream::ValidateResponse(int rv) {
[email protected]d51365e2013-11-27 10:46:52455 DCHECK(http_response_info_);
[email protected]f7e98ca2014-06-19 12:05:43456 // Most net errors happen during connection, so they are not seen by this
457 // method. The histogram for error codes is created in
458 // Delegate::OnResponseStarted in websocket_stream.cc instead.
[email protected]e5760f522014-02-05 12:28:50459 if (rv >= 0) {
[email protected]f7e98ca2014-06-19 12:05:43460 const HttpResponseHeaders* headers = http_response_info_->headers.get();
461 const int response_code = headers->response_code();
Ilya Sherman0eb39802017-12-08 20:58:18462 base::UmaHistogramSparse("Net.WebSocket.ResponseCode", response_code);
[email protected]f7e98ca2014-06-19 12:05:43463 switch (response_code) {
[email protected]e5760f522014-02-05 12:28:50464 case HTTP_SWITCHING_PROTOCOLS:
[email protected]e5760f522014-02-05 12:28:50465 return ValidateUpgradeResponse(headers);
[email protected]d51365e2013-11-27 10:46:52466
[email protected]e5760f522014-02-05 12:28:50467 // We need to pass these through for authentication to work.
468 case HTTP_UNAUTHORIZED:
469 case HTTP_PROXY_AUTHENTICATION_REQUIRED:
470 return OK;
[email protected]d51365e2013-11-27 10:46:52471
[email protected]e5760f522014-02-05 12:28:50472 // Other status codes are potentially risky (see the warnings in the
473 // WHATWG WebSocket API spec) and so are dropped by default.
474 default:
[email protected]aeb640d2014-02-21 11:03:18475 // A WebSocket server cannot be using HTTP/0.9, so if we see version
476 // 0.9, it means the response was garbage.
477 // Reporting "Unexpected response code: 200" in this case is not
478 // helpful, so use a different error message.
479 if (headers->GetHttpVersion() == HttpVersion(0, 9)) {
Adam Langleya48b636a2020-11-12 23:42:52480 OnFailure("Error during WebSocket handshake: Invalid status line",
Anton Bikineev068d2912021-05-15 20:43:52481 ERR_FAILED, absl::nullopt);
[email protected]aeb640d2014-02-21 11:03:18482 } else {
Adam Langleya48b636a2020-11-12 23:42:52483 OnFailure(base::StringPrintf("Error during WebSocket handshake: "
484 "Unexpected response code: %d",
485 headers->response_code()),
486 ERR_FAILED, headers->response_code());
[email protected]aeb640d2014-02-21 11:03:18487 }
Bence Békyde0be312018-03-13 17:51:58488 result_ = HandshakeResult::INVALID_STATUS;
[email protected]e5760f522014-02-05 12:28:50489 return ERR_INVALID_RESPONSE;
490 }
491 } else {
[email protected]3efc08f2014-02-07 09:33:34492 if (rv == ERR_EMPTY_RESPONSE) {
Adam Langleya48b636a2020-11-12 23:42:52493 OnFailure("Connection closed before receiving a handshake response", rv,
Anton Bikineev068d2912021-05-15 20:43:52494 absl::nullopt);
Bence Békyde0be312018-03-13 17:51:58495 result_ = HandshakeResult::EMPTY_RESPONSE;
[email protected]3efc08f2014-02-07 09:33:34496 return rv;
497 }
Adam Langleya48b636a2020-11-12 23:42:52498 OnFailure(
499 std::string("Error during WebSocket handshake: ") + ErrorToString(rv),
Anton Bikineev068d2912021-05-15 20:43:52500 rv, absl::nullopt);
ricea23c3f942015-02-02 13:35:13501 // Some error codes (for example ERR_CONNECTION_CLOSED) get changed to OK at
502 // higher levels. To prevent an unvalidated connection getting erroneously
503 // upgraded, don't pass through the status code unchanged if it is
504 // HTTP_SWITCHING_PROTOCOLS.
505 if (http_response_info_->headers &&
506 http_response_info_->headers->response_code() ==
507 HTTP_SWITCHING_PROTOCOLS) {
508 http_response_info_->headers->ReplaceStatusLine(
509 kConnectionErrorStatusLine);
Bence Békyde0be312018-03-13 17:51:58510 result_ = HandshakeResult::FAILED_SWITCHING_PROTOCOLS;
511 return rv;
ricea23c3f942015-02-02 13:35:13512 }
Bence Békyde0be312018-03-13 17:51:58513 result_ = HandshakeResult::FAILED;
[email protected]e5760f522014-02-05 12:28:50514 return rv;
[email protected]d51365e2013-11-27 10:46:52515 }
516}
517
518int WebSocketBasicHandshakeStream::ValidateUpgradeResponse(
[email protected]e5760f522014-02-05 12:28:50519 const HttpResponseHeaders* headers) {
Bence Béky65623972018-03-05 15:31:56520 extension_params_ = std::make_unique<WebSocketExtensionParams>();
[email protected]8aba0172014-07-03 12:09:53521 std::string failure_message;
Bence Békyde0be312018-03-13 17:51:58522 if (!ValidateUpgrade(headers, &failure_message)) {
523 result_ = HandshakeResult::FAILED_UPGRADE;
524 } else if (!ValidateSecWebSocketAccept(headers, handshake_challenge_response_,
525 &failure_message)) {
526 result_ = HandshakeResult::FAILED_ACCEPT;
527 } else if (!ValidateConnection(headers, &failure_message)) {
528 result_ = HandshakeResult::FAILED_CONNECTION;
529 } else if (!ValidateSubProtocol(headers, requested_sub_protocols_,
530 &sub_protocol_, &failure_message)) {
531 result_ = HandshakeResult::FAILED_SUBPROTO;
532 } else if (!ValidateExtensions(headers, &extensions_, &failure_message,
533 extension_params_.get())) {
534 result_ = HandshakeResult::FAILED_EXTENSIONS;
535 } else {
536 result_ = HandshakeResult::CONNECTED;
[email protected]d51365e2013-11-27 10:46:52537 return OK;
538 }
Adam Langleya48b636a2020-11-12 23:42:52539 OnFailure("Error during WebSocket handshake: " + failure_message, ERR_FAILED,
Anton Bikineev068d2912021-05-15 20:43:52540 absl::nullopt);
[email protected]d51365e2013-11-27 10:46:52541 return ERR_INVALID_RESPONSE;
542}
543
Adam Langleya48b636a2020-11-12 23:42:52544void WebSocketBasicHandshakeStream::OnFailure(
545 const std::string& message,
546 int net_error,
Anton Bikineev068d2912021-05-15 20:43:52547 absl::optional<int> response_code) {
Nanami Mikiyaca3588c2022-01-31 03:22:25548 net_log_.AddEvent(net::NetLogEventType::WEBSOCKET_UPGRADE_FAILURE,
549 [&] { return NetLogFailureParam(net_error, message); });
Adam Riced4596a8e2018-07-13 08:06:17550 // Avoid connection reuse if auth did not happen.
551 state_.connection()->socket()->Disconnect();
Adam Langleya48b636a2020-11-12 23:42:52552 stream_request_->OnFailure(message, net_error, response_code);
[email protected]8aba0172014-07-03 12:09:53553}
554
[email protected]d51365e2013-11-27 10:46:52555} // namespace net