blob: 2b208208a45e713edfcf0ba8055cea48b07fdedc [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]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"
[email protected]d51365e2013-11-27 10:46:5226#include "net/http/http_request_headers.h"
27#include "net/http/http_request_info.h"
28#include "net/http/http_response_body_drainer.h"
29#include "net/http/http_response_headers.h"
30#include "net/http/http_status_code.h"
31#include "net/http/http_stream_parser.h"
32#include "net/socket/client_socket_handle.h"
Bence Béky3cb271d2018-03-29 22:00:4833#include "net/socket/ssl_client_socket.h"
Bence Békyda280c62018-04-12 15:08:3734#include "net/socket/websocket_endpoint_lock_manager.h"
[email protected]654866142014-06-24 22:53:3135#include "net/socket/websocket_transport_client_socket_pool.h"
Matt Menkef171ff8b2019-02-05 20:06:1336#include "net/ssl/ssl_cert_request_info.h"
37#include "net/ssl/ssl_info.h"
[email protected]d51365e2013-11-27 10:46:5238#include "net/websockets/websocket_basic_stream.h"
Bence Béky7294fc22018-02-08 14:26:1739#include "net/websockets/websocket_basic_stream_adapters.h"
yhirano8387aee2015-09-14 05:46:4940#include "net/websockets/websocket_deflate_parameters.h"
[email protected]0be93922014-01-29 00:42:4541#include "net/websockets/websocket_deflate_predictor.h"
42#include "net/websockets/websocket_deflate_predictor_impl.h"
43#include "net/websockets/websocket_deflate_stream.h"
44#include "net/websockets/websocket_deflater.h"
ricea11bdcd02014-11-20 09:57:0745#include "net/websockets/websocket_handshake_challenge.h"
[email protected]d51365e2013-11-27 10:46:5246#include "net/websockets/websocket_handshake_constants.h"
[email protected]cd48ed12014-01-22 14:34:2247#include "net/websockets/websocket_handshake_request_info.h"
48#include "net/websockets/websocket_handshake_response_info.h"
[email protected]d51365e2013-11-27 10:46:5249#include "net/websockets/websocket_stream.h"
50
51namespace net {
[email protected]0be93922014-01-29 00:42:4552
yhirano27b2b572014-10-30 11:23:4453namespace {
54
ricea23c3f942015-02-02 13:35:1355const char kConnectionErrorStatusLine[] = "HTTP/1.1 503 Connection Error";
56
yhirano27b2b572014-10-30 11:23:4457} // namespace
58
[email protected]d51365e2013-11-27 10:46:5259namespace {
60
[email protected]96868202014-01-09 10:38:0461enum GetHeaderResult {
62 GET_HEADER_OK,
63 GET_HEADER_MISSING,
64 GET_HEADER_MULTIPLE,
65};
66
67std::string MissingHeaderMessage(const std::string& header_name) {
68 return std::string("'") + header_name + "' header is missing";
69}
70
[email protected]d51365e2013-11-27 10:46:5271std::string GenerateHandshakeChallenge() {
72 std::string raw_challenge(websockets::kRawChallengeLength, '\0');
Daniel Cheng5feb16f2022-02-28 06:52:0773 crypto::RandBytes(std::data(raw_challenge), raw_challenge.length());
[email protected]d51365e2013-11-27 10:46:5274 std::string encoded_challenge;
[email protected]33fca122013-12-11 01:48:5075 base::Base64Encode(raw_challenge, &encoded_challenge);
[email protected]d51365e2013-11-27 10:46:5276 return encoded_challenge;
77}
78
[email protected]96868202014-01-09 10:38:0479GetHeaderResult GetSingleHeaderValue(const HttpResponseHeaders* headers,
80 const base::StringPiece& name,
81 std::string* value) {
olli.raulaee489a52016-01-25 08:37:1082 size_t iter = 0;
[email protected]96868202014-01-09 10:38:0483 size_t num_values = 0;
84 std::string temp_value;
olli.raulaee489a52016-01-25 08:37:1085 while (headers->EnumerateHeader(&iter, name, &temp_value)) {
[email protected]96868202014-01-09 10:38:0486 if (++num_values > 1)
87 return GET_HEADER_MULTIPLE;
88 *value = temp_value;
[email protected]d51365e2013-11-27 10:46:5289 }
[email protected]96868202014-01-09 10:38:0490 return num_values > 0 ? GET_HEADER_OK : GET_HEADER_MISSING;
91}
92
93bool ValidateHeaderHasSingleValue(GetHeaderResult result,
94 const std::string& header_name,
95 std::string* failure_message) {
96 if (result == GET_HEADER_MISSING) {
97 *failure_message = MissingHeaderMessage(header_name);
98 return false;
99 }
100 if (result == GET_HEADER_MULTIPLE) {
Bence Békyb28709c22018-03-06 13:03:44101 *failure_message =
102 WebSocketHandshakeStreamBase::MultipleHeaderValuesMessage(header_name);
[email protected]96868202014-01-09 10:38:04103 return false;
104 }
105 DCHECK_EQ(result, GET_HEADER_OK);
106 return true;
107}
108
109bool ValidateUpgrade(const HttpResponseHeaders* headers,
110 std::string* failure_message) {
111 std::string value;
112 GetHeaderResult result =
113 GetSingleHeaderValue(headers, websockets::kUpgrade, &value);
114 if (!ValidateHeaderHasSingleValue(result,
115 websockets::kUpgrade,
116 failure_message)) {
117 return false;
118 }
119
brettwbc17d2c82015-06-09 22:39:08120 if (!base::LowerCaseEqualsASCII(value, websockets::kWebSocketLowercase)) {
[email protected]96868202014-01-09 10:38:04121 *failure_message =
122 "'Upgrade' header value is not 'WebSocket': " + value;
123 return false;
124 }
125 return true;
126}
127
128bool ValidateSecWebSocketAccept(const HttpResponseHeaders* headers,
129 const std::string& expected,
130 std::string* failure_message) {
131 std::string actual;
132 GetHeaderResult result =
133 GetSingleHeaderValue(headers, websockets::kSecWebSocketAccept, &actual);
134 if (!ValidateHeaderHasSingleValue(result,
135 websockets::kSecWebSocketAccept,
136 failure_message)) {
137 return false;
138 }
139
140 if (expected != actual) {
141 *failure_message = "Incorrect 'Sec-WebSocket-Accept' header value";
142 return false;
143 }
144 return true;
145}
146
147bool ValidateConnection(const HttpResponseHeaders* headers,
148 std::string* failure_message) {
149 // Connection header is permitted to contain other tokens.
150 if (!headers->HasHeader(HttpRequestHeaders::kConnection)) {
151 *failure_message = MissingHeaderMessage(HttpRequestHeaders::kConnection);
152 return false;
153 }
154 if (!headers->HasHeaderValue(HttpRequestHeaders::kConnection,
155 websockets::kUpgrade)) {
156 *failure_message = "'Connection' header value must contain 'Upgrade'";
157 return false;
158 }
159 return true;
[email protected]d51365e2013-11-27 10:46:52160}
161
Nanami Mikiyaca3588c2022-01-31 03:22:25162base::Value NetLogFailureParam(int net_error, const std::string& message) {
163 base::Value dict(base::Value::Type::DICTIONARY);
164 dict.SetIntKey("net_error", net_error);
165 dict.SetStringKey("message", message);
166 return dict;
167}
168
[email protected]d51365e2013-11-27 10:46:52169} // namespace
170
171WebSocketBasicHandshakeStream::WebSocketBasicHandshakeStream(
danakj9c5cab52016-04-16 00:54:33172 std::unique_ptr<ClientSocketHandle> connection,
[email protected]cd48ed12014-01-22 14:34:22173 WebSocketStream::ConnectDelegate* connect_delegate,
[email protected]d51365e2013-11-27 10:46:52174 bool using_proxy,
175 std::vector<std::string> requested_sub_protocols,
[email protected]8aba0172014-07-03 12:09:53176 std::vector<std::string> requested_extensions,
Adam Rice6f75c0f2018-06-04 08:00:05177 WebSocketStreamRequestAPI* request,
Bence Békyda280c62018-04-12 15:08:37178 WebSocketEndpointLockManager* websocket_endpoint_lock_manager)
Bence Békyde0be312018-03-13 17:51:58179 : result_(HandshakeResult::INCOMPLETE),
Matt Menkea31ed582019-09-19 20:14:11180 state_(std::move(connection), using_proxy),
[email protected]cd48ed12014-01-22 14:34:22181 connect_delegate_(connect_delegate),
yhiranoa7e05bb2014-11-06 05:40:39182 http_response_info_(nullptr),
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) {
379 HttpResponseBodyDrainer* drainer = new HttpResponseBodyDrainer(this);
380 drainer->Start(session);
381 // |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
yhiranoa7e05bb2014-11-06 05:40:39389HttpStream* WebSocketBasicHandshakeStream::RenewStreamForAuth() {
Adam Rice8b382c602018-06-04 12:36:39390 DCHECK(IsResponseBodyComplete());
391 DCHECK(!parser()->IsMoreDataBuffered());
392 // The HttpStreamParser object still has a pointer to the connection. Just to
393 // be extra-sure it doesn't touch the connection again, delete it here rather
394 // than leaving it until the destructor is called.
395 state_.DeleteParser();
396
397 auto handshake_stream = std::make_unique<WebSocketBasicHandshakeStream>(
398 state_.ReleaseConnection(), connect_delegate_, state_.using_proxy(),
399 std::move(requested_sub_protocols_), std::move(requested_extensions_),
400 stream_request_, websocket_endpoint_lock_manager_);
401
402 stream_request_->OnBasicHandshakeStreamCreated(handshake_stream.get());
403
404 return handshake_stream.release();
yhiranoa7e05bb2014-11-06 05:40:39405}
406
Eric Orthac661912022-01-10 21:44:17407const std::set<std::string>& WebSocketBasicHandshakeStream::GetDnsAliases()
Cammie Smith Barnes4a5d72f2020-12-17 21:47:04408 const {
409 return state_.GetDnsAliases();
410}
411
Bence Béky334ddfc22021-03-12 15:18:13412base::StringPiece WebSocketBasicHandshakeStream::GetAcceptChViaAlps() const {
413 return {};
414}
415
danakj9c5cab52016-04-16 00:54:33416std::unique_ptr<WebSocketStream> WebSocketBasicHandshakeStream::Upgrade() {
[email protected]d51365e2013-11-27 10:46:52417 // The HttpStreamParser object has a pointer to our ClientSocketHandle. Make
418 // sure it does not touch it again before it is destroyed.
419 state_.DeleteParser();
Bence Békyda280c62018-04-12 15:08:37420 WebSocketTransportClientSocketPool::UnlockEndpoint(
421 state_.connection(), websocket_endpoint_lock_manager_);
Bence Béky7294fc22018-02-08 14:26:17422 std::unique_ptr<WebSocketStream> basic_stream =
423 std::make_unique<WebSocketBasicStream>(
424 std::make_unique<WebSocketClientSocketHandleAdapter>(
425 state_.ReleaseConnection()),
Nanami Mikiyad6b837e2022-02-01 05:58:57426 state_.read_buf(), sub_protocol_, extensions_, net_log_);
[email protected]0be93922014-01-29 00:42:45427 DCHECK(extension_params_.get());
428 if (extension_params_->deflate_enabled) {
Bence Béky65623972018-03-05 15:31:56429 return std::make_unique<WebSocketDeflateStream>(
dchengc7eeda422015-12-26 03:56:48430 std::move(basic_stream), extension_params_->deflate_parameters,
Bence Béky65623972018-03-05 15:31:56431 std::make_unique<WebSocketDeflatePredictorImpl>());
[email protected]0be93922014-01-29 00:42:45432 }
Adam Riceb0237282019-06-20 14:14:02433
434 return basic_stream;
[email protected]d51365e2013-11-27 10:46:52435}
436
Bence Békyca0da432019-01-24 15:03:20437base::WeakPtr<WebSocketHandshakeStreamBase>
438WebSocketBasicHandshakeStream::GetWeakPtr() {
439 return weak_ptr_factory_.GetWeakPtr();
440}
441
[email protected]a31ecc02013-12-05 08:30:55442void WebSocketBasicHandshakeStream::SetWebSocketKeyForTesting(
443 const std::string& key) {
Bence Béky7d0c74d2018-03-05 08:31:09444 handshake_challenge_for_testing_ = key;
[email protected]a31ecc02013-12-05 08:30:55445}
446
[email protected]d51365e2013-11-27 10:46:52447void WebSocketBasicHandshakeStream::ReadResponseHeadersCallback(
Bence Békya25e3f72018-02-13 21:13:39448 CompletionOnceCallback callback,
[email protected]d51365e2013-11-27 10:46:52449 int result) {
Bence Békya25e3f72018-02-13 21:13:39450 std::move(callback).Run(ValidateResponse(result));
[email protected]d51365e2013-11-27 10:46:52451}
452
ricea24c195f2015-02-26 12:18:55453int WebSocketBasicHandshakeStream::ValidateResponse(int rv) {
[email protected]d51365e2013-11-27 10:46:52454 DCHECK(http_response_info_);
[email protected]f7e98ca2014-06-19 12:05:43455 // Most net errors happen during connection, so they are not seen by this
456 // method. The histogram for error codes is created in
457 // Delegate::OnResponseStarted in websocket_stream.cc instead.
[email protected]e5760f522014-02-05 12:28:50458 if (rv >= 0) {
[email protected]f7e98ca2014-06-19 12:05:43459 const HttpResponseHeaders* headers = http_response_info_->headers.get();
460 const int response_code = headers->response_code();
Ilya Sherman0eb39802017-12-08 20:58:18461 base::UmaHistogramSparse("Net.WebSocket.ResponseCode", response_code);
[email protected]f7e98ca2014-06-19 12:05:43462 switch (response_code) {
[email protected]e5760f522014-02-05 12:28:50463 case HTTP_SWITCHING_PROTOCOLS:
[email protected]e5760f522014-02-05 12:28:50464 return ValidateUpgradeResponse(headers);
[email protected]d51365e2013-11-27 10:46:52465
[email protected]e5760f522014-02-05 12:28:50466 // We need to pass these through for authentication to work.
467 case HTTP_UNAUTHORIZED:
468 case HTTP_PROXY_AUTHENTICATION_REQUIRED:
469 return OK;
[email protected]d51365e2013-11-27 10:46:52470
[email protected]e5760f522014-02-05 12:28:50471 // Other status codes are potentially risky (see the warnings in the
472 // WHATWG WebSocket API spec) and so are dropped by default.
473 default:
[email protected]aeb640d2014-02-21 11:03:18474 // A WebSocket server cannot be using HTTP/0.9, so if we see version
475 // 0.9, it means the response was garbage.
476 // Reporting "Unexpected response code: 200" in this case is not
477 // helpful, so use a different error message.
478 if (headers->GetHttpVersion() == HttpVersion(0, 9)) {
Adam Langleya48b636a2020-11-12 23:42:52479 OnFailure("Error during WebSocket handshake: Invalid status line",
Anton Bikineev068d2912021-05-15 20:43:52480 ERR_FAILED, absl::nullopt);
[email protected]aeb640d2014-02-21 11:03:18481 } else {
Adam Langleya48b636a2020-11-12 23:42:52482 OnFailure(base::StringPrintf("Error during WebSocket handshake: "
483 "Unexpected response code: %d",
484 headers->response_code()),
485 ERR_FAILED, headers->response_code());
[email protected]aeb640d2014-02-21 11:03:18486 }
Bence Békyde0be312018-03-13 17:51:58487 result_ = HandshakeResult::INVALID_STATUS;
[email protected]e5760f522014-02-05 12:28:50488 return ERR_INVALID_RESPONSE;
489 }
490 } else {
[email protected]3efc08f2014-02-07 09:33:34491 if (rv == ERR_EMPTY_RESPONSE) {
Adam Langleya48b636a2020-11-12 23:42:52492 OnFailure("Connection closed before receiving a handshake response", rv,
Anton Bikineev068d2912021-05-15 20:43:52493 absl::nullopt);
Bence Békyde0be312018-03-13 17:51:58494 result_ = HandshakeResult::EMPTY_RESPONSE;
[email protected]3efc08f2014-02-07 09:33:34495 return rv;
496 }
Adam Langleya48b636a2020-11-12 23:42:52497 OnFailure(
498 std::string("Error during WebSocket handshake: ") + ErrorToString(rv),
Anton Bikineev068d2912021-05-15 20:43:52499 rv, absl::nullopt);
ricea23c3f942015-02-02 13:35:13500 // Some error codes (for example ERR_CONNECTION_CLOSED) get changed to OK at
501 // higher levels. To prevent an unvalidated connection getting erroneously
502 // upgraded, don't pass through the status code unchanged if it is
503 // HTTP_SWITCHING_PROTOCOLS.
504 if (http_response_info_->headers &&
505 http_response_info_->headers->response_code() ==
506 HTTP_SWITCHING_PROTOCOLS) {
507 http_response_info_->headers->ReplaceStatusLine(
508 kConnectionErrorStatusLine);
Bence Békyde0be312018-03-13 17:51:58509 result_ = HandshakeResult::FAILED_SWITCHING_PROTOCOLS;
510 return rv;
ricea23c3f942015-02-02 13:35:13511 }
Bence Békyde0be312018-03-13 17:51:58512 result_ = HandshakeResult::FAILED;
[email protected]e5760f522014-02-05 12:28:50513 return rv;
[email protected]d51365e2013-11-27 10:46:52514 }
515}
516
517int WebSocketBasicHandshakeStream::ValidateUpgradeResponse(
[email protected]e5760f522014-02-05 12:28:50518 const HttpResponseHeaders* headers) {
Bence Béky65623972018-03-05 15:31:56519 extension_params_ = std::make_unique<WebSocketExtensionParams>();
[email protected]8aba0172014-07-03 12:09:53520 std::string failure_message;
Bence Békyde0be312018-03-13 17:51:58521 if (!ValidateUpgrade(headers, &failure_message)) {
522 result_ = HandshakeResult::FAILED_UPGRADE;
523 } else if (!ValidateSecWebSocketAccept(headers, handshake_challenge_response_,
524 &failure_message)) {
525 result_ = HandshakeResult::FAILED_ACCEPT;
526 } else if (!ValidateConnection(headers, &failure_message)) {
527 result_ = HandshakeResult::FAILED_CONNECTION;
528 } else if (!ValidateSubProtocol(headers, requested_sub_protocols_,
529 &sub_protocol_, &failure_message)) {
530 result_ = HandshakeResult::FAILED_SUBPROTO;
531 } else if (!ValidateExtensions(headers, &extensions_, &failure_message,
532 extension_params_.get())) {
533 result_ = HandshakeResult::FAILED_EXTENSIONS;
534 } else {
535 result_ = HandshakeResult::CONNECTED;
[email protected]d51365e2013-11-27 10:46:52536 return OK;
537 }
Adam Langleya48b636a2020-11-12 23:42:52538 OnFailure("Error during WebSocket handshake: " + failure_message, ERR_FAILED,
Anton Bikineev068d2912021-05-15 20:43:52539 absl::nullopt);
[email protected]d51365e2013-11-27 10:46:52540 return ERR_INVALID_RESPONSE;
541}
542
Adam Langleya48b636a2020-11-12 23:42:52543void WebSocketBasicHandshakeStream::OnFailure(
544 const std::string& message,
545 int net_error,
Anton Bikineev068d2912021-05-15 20:43:52546 absl::optional<int> response_code) {
Nanami Mikiyaca3588c2022-01-31 03:22:25547 net_log_.AddEvent(net::NetLogEventType::WEBSOCKET_UPGRADE_FAILURE,
548 [&] { return NetLogFailureParam(net_error, message); });
Adam Riced4596a8e2018-07-13 08:06:17549 // Avoid connection reuse if auth did not happen.
550 state_.connection()->socket()->Disconnect();
Adam Langleya48b636a2020-11-12 23:42:52551 stream_request_->OnFailure(message, net_error, response_code);
[email protected]8aba0172014-07-03 12:09:53552}
553
[email protected]d51365e2013-11-27 10:46:52554} // namespace net