xref: /aosp_15_r20/external/cronet/net/websockets/websocket_basic_handshake_stream.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2013 The Chromium Authors
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 
7 #include <stddef.h>
8 
9 #include <array>
10 #include <set>
11 #include <string_view>
12 #include <type_traits>
13 #include <utility>
14 
15 #include "base/base64.h"
16 #include "base/check.h"
17 #include "base/check_op.h"
18 #include "base/functional/bind.h"
19 #include "base/functional/callback.h"
20 #include "base/memory/scoped_refptr.h"
21 #include "base/metrics/histogram_functions.h"
22 #include "base/strings/strcat.h"
23 #include "base/strings/string_util.h"
24 #include "base/strings/stringprintf.h"
25 #include "base/time/time.h"
26 #include "base/values.h"
27 #include "crypto/random.h"
28 #include "net/base/net_errors.h"
29 #include "net/http/http_network_session.h"
30 #include "net/http/http_request_headers.h"
31 #include "net/http/http_request_info.h"
32 #include "net/http/http_response_body_drainer.h"
33 #include "net/http/http_response_headers.h"
34 #include "net/http/http_response_info.h"
35 #include "net/http/http_status_code.h"
36 #include "net/http/http_stream_parser.h"
37 #include "net/http/http_version.h"
38 #include "net/log/net_log_event_type.h"
39 #include "net/socket/client_socket_handle.h"
40 #include "net/socket/stream_socket.h"
41 #include "net/socket/websocket_transport_client_socket_pool.h"
42 #include "net/ssl/ssl_cert_request_info.h"
43 #include "net/ssl/ssl_info.h"
44 #include "net/traffic_annotation/network_traffic_annotation.h"
45 #include "net/websockets/websocket_basic_stream.h"
46 #include "net/websockets/websocket_basic_stream_adapters.h"
47 #include "net/websockets/websocket_deflate_predictor_impl.h"
48 #include "net/websockets/websocket_deflate_stream.h"
49 #include "net/websockets/websocket_handshake_challenge.h"
50 #include "net/websockets/websocket_handshake_constants.h"
51 #include "net/websockets/websocket_handshake_request_info.h"
52 #include "net/websockets/websocket_stream.h"
53 
54 namespace net {
55 class HttpStream;
56 class IOBuffer;
57 class IPEndPoint;
58 struct AlternativeService;
59 struct LoadTimingInfo;
60 struct NetErrorDetails;
61 
62 namespace {
63 
64 constexpr char kConnectionErrorStatusLine[] = "HTTP/1.1 503 Connection Error";
65 
66 }  // namespace
67 
68 namespace {
69 
70 enum GetHeaderResult {
71   GET_HEADER_OK,
72   GET_HEADER_MISSING,
73   GET_HEADER_MULTIPLE,
74 };
75 
MissingHeaderMessage(const std::string & header_name)76 std::string MissingHeaderMessage(const std::string& header_name) {
77   return base::StrCat({"'", header_name, "' header is missing"});
78 }
79 
GenerateHandshakeChallenge()80 std::string GenerateHandshakeChallenge() {
81   std::array<uint8_t, websockets::kRawChallengeLength> raw_challenge = {};
82   crypto::RandBytes(raw_challenge);
83   return base::Base64Encode(raw_challenge);
84 }
85 
GetSingleHeaderValue(const HttpResponseHeaders * headers,std::string_view name,std::string * value)86 GetHeaderResult GetSingleHeaderValue(const HttpResponseHeaders* headers,
87                                      std::string_view name,
88                                      std::string* value) {
89   size_t iter = 0;
90   size_t num_values = 0;
91   std::string temp_value;
92   while (headers->EnumerateHeader(&iter, name, &temp_value)) {
93     if (++num_values > 1)
94       return GET_HEADER_MULTIPLE;
95     *value = temp_value;
96   }
97   return num_values > 0 ? GET_HEADER_OK : GET_HEADER_MISSING;
98 }
99 
ValidateHeaderHasSingleValue(GetHeaderResult result,const std::string & header_name,std::string * failure_message)100 bool ValidateHeaderHasSingleValue(GetHeaderResult result,
101                                   const std::string& header_name,
102                                   std::string* failure_message) {
103   if (result == GET_HEADER_MISSING) {
104     *failure_message = MissingHeaderMessage(header_name);
105     return false;
106   }
107   if (result == GET_HEADER_MULTIPLE) {
108     *failure_message =
109         WebSocketHandshakeStreamBase::MultipleHeaderValuesMessage(header_name);
110     return false;
111   }
112   DCHECK_EQ(result, GET_HEADER_OK);
113   return true;
114 }
115 
ValidateUpgrade(const HttpResponseHeaders * headers,std::string * failure_message)116 bool ValidateUpgrade(const HttpResponseHeaders* headers,
117                      std::string* failure_message) {
118   std::string value;
119   GetHeaderResult result =
120       GetSingleHeaderValue(headers, websockets::kUpgrade, &value);
121   if (!ValidateHeaderHasSingleValue(result,
122                                     websockets::kUpgrade,
123                                     failure_message)) {
124     return false;
125   }
126 
127   if (!base::EqualsCaseInsensitiveASCII(value,
128                                         websockets::kWebSocketLowercase)) {
129     *failure_message =
130         "'Upgrade' header value is not 'WebSocket': " + value;
131     return false;
132   }
133   return true;
134 }
135 
ValidateSecWebSocketAccept(const HttpResponseHeaders * headers,const std::string & expected,std::string * failure_message)136 bool ValidateSecWebSocketAccept(const HttpResponseHeaders* headers,
137                                 const std::string& expected,
138                                 std::string* failure_message) {
139   std::string actual;
140   GetHeaderResult result =
141       GetSingleHeaderValue(headers, websockets::kSecWebSocketAccept, &actual);
142   if (!ValidateHeaderHasSingleValue(result,
143                                     websockets::kSecWebSocketAccept,
144                                     failure_message)) {
145     return false;
146   }
147 
148   if (expected != actual) {
149     *failure_message = "Incorrect 'Sec-WebSocket-Accept' header value";
150     return false;
151   }
152   return true;
153 }
154 
ValidateConnection(const HttpResponseHeaders * headers,std::string * failure_message)155 bool ValidateConnection(const HttpResponseHeaders* headers,
156                         std::string* failure_message) {
157   // Connection header is permitted to contain other tokens.
158   if (!headers->HasHeader(HttpRequestHeaders::kConnection)) {
159     *failure_message = MissingHeaderMessage(HttpRequestHeaders::kConnection);
160     return false;
161   }
162   if (!headers->HasHeaderValue(HttpRequestHeaders::kConnection,
163                                websockets::kUpgrade)) {
164     *failure_message = "'Connection' header value must contain 'Upgrade'";
165     return false;
166   }
167   return true;
168 }
169 
NetLogFailureParam(int net_error,const std::string & message)170 base::Value::Dict NetLogFailureParam(int net_error,
171                                      const std::string& message) {
172   base::Value::Dict dict;
173   dict.Set("net_error", net_error);
174   dict.Set("message", message);
175   return dict;
176 }
177 
178 }  // namespace
179 
WebSocketBasicHandshakeStream(std::unique_ptr<ClientSocketHandle> connection,WebSocketStream::ConnectDelegate * connect_delegate,bool is_for_get_to_http_proxy,std::vector<std::string> requested_sub_protocols,std::vector<std::string> requested_extensions,WebSocketStreamRequestAPI * request,WebSocketEndpointLockManager * websocket_endpoint_lock_manager)180 WebSocketBasicHandshakeStream::WebSocketBasicHandshakeStream(
181     std::unique_ptr<ClientSocketHandle> connection,
182     WebSocketStream::ConnectDelegate* connect_delegate,
183     bool is_for_get_to_http_proxy,
184     std::vector<std::string> requested_sub_protocols,
185     std::vector<std::string> requested_extensions,
186     WebSocketStreamRequestAPI* request,
187     WebSocketEndpointLockManager* websocket_endpoint_lock_manager)
188     : state_(std::move(connection), is_for_get_to_http_proxy),
189       connect_delegate_(connect_delegate),
190       requested_sub_protocols_(std::move(requested_sub_protocols)),
191       requested_extensions_(std::move(requested_extensions)),
192       stream_request_(request),
193       websocket_endpoint_lock_manager_(websocket_endpoint_lock_manager) {
194   DCHECK(connect_delegate);
195   DCHECK(request);
196 }
197 
~WebSocketBasicHandshakeStream()198 WebSocketBasicHandshakeStream::~WebSocketBasicHandshakeStream() {
199   // Some members are "stolen" by RenewStreamForAuth() and should not be touched
200   // here. Particularly |connect_delegate_|, |stream_request_|, and
201   // |websocket_endpoint_lock_manager_|.
202 
203   // TODO(ricea): What's the right thing to do here if we renewed the stream for
204   // auth? Currently we record it as INCOMPLETE.
205   RecordHandshakeResult(result_);
206 }
207 
RegisterRequest(const HttpRequestInfo * request_info)208 void WebSocketBasicHandshakeStream::RegisterRequest(
209     const HttpRequestInfo* request_info) {
210   DCHECK(request_info);
211   DCHECK(request_info->traffic_annotation.is_valid());
212   request_info_ = request_info;
213 }
214 
InitializeStream(bool can_send_early,RequestPriority priority,const NetLogWithSource & net_log,CompletionOnceCallback callback)215 int WebSocketBasicHandshakeStream::InitializeStream(
216     bool can_send_early,
217     RequestPriority priority,
218     const NetLogWithSource& net_log,
219     CompletionOnceCallback callback) {
220   url_ = request_info_->url;
221   net_log_ = net_log;
222   // The WebSocket may receive a socket in the early data state from
223   // HttpNetworkTransaction, which means it must call ConfirmHandshake() for
224   // requests that need replay protection. However, the first request on any
225   // WebSocket stream is a GET with an idempotent request
226   // (https://tools.ietf.org/html/rfc6455#section-1.3), so there is no need to
227   // call ConfirmHandshake().
228   //
229   // Data after the WebSockets handshake may not be replayable, but the
230   // handshake is guaranteed to be confirmed once the HTTP response is received.
231   DCHECK(can_send_early);
232   state_.Initialize(request_info_, priority, net_log);
233   // RequestInfo is no longer needed after this point.
234   request_info_ = nullptr;
235   return OK;
236 }
237 
SendRequest(const HttpRequestHeaders & headers,HttpResponseInfo * response,CompletionOnceCallback callback)238 int WebSocketBasicHandshakeStream::SendRequest(
239     const HttpRequestHeaders& headers,
240     HttpResponseInfo* response,
241     CompletionOnceCallback callback) {
242   DCHECK(!headers.HasHeader(websockets::kSecWebSocketKey));
243   DCHECK(!headers.HasHeader(websockets::kSecWebSocketProtocol));
244   DCHECK(!headers.HasHeader(websockets::kSecWebSocketExtensions));
245   DCHECK(headers.HasHeader(HttpRequestHeaders::kOrigin));
246   DCHECK(headers.HasHeader(websockets::kUpgrade));
247   DCHECK(headers.HasHeader(HttpRequestHeaders::kConnection));
248   DCHECK(headers.HasHeader(websockets::kSecWebSocketVersion));
249   DCHECK(parser());
250 
251   http_response_info_ = response;
252 
253   // Create a copy of the headers object, so that we can add the
254   // Sec-WebSocket-Key header.
255   HttpRequestHeaders enriched_headers = headers;
256   std::string handshake_challenge;
257   if (handshake_challenge_for_testing_.has_value()) {
258     handshake_challenge = handshake_challenge_for_testing_.value();
259     handshake_challenge_for_testing_.reset();
260   } else {
261     handshake_challenge = GenerateHandshakeChallenge();
262   }
263   enriched_headers.SetHeader(websockets::kSecWebSocketKey, handshake_challenge);
264 
265   AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketExtensions,
266                             requested_extensions_,
267                             &enriched_headers);
268   AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketProtocol,
269                             requested_sub_protocols_,
270                             &enriched_headers);
271 
272   handshake_challenge_response_ =
273       ComputeSecWebSocketAccept(handshake_challenge);
274 
275   DCHECK(connect_delegate_);
276   auto request =
277       std::make_unique<WebSocketHandshakeRequestInfo>(url_, base::Time::Now());
278   request->headers = enriched_headers;
279   connect_delegate_->OnStartOpeningHandshake(std::move(request));
280 
281   return parser()->SendRequest(
282       state_.GenerateRequestLine(), enriched_headers,
283       NetworkTrafficAnnotationTag(state_.traffic_annotation()), response,
284       std::move(callback));
285 }
286 
ReadResponseHeaders(CompletionOnceCallback callback)287 int WebSocketBasicHandshakeStream::ReadResponseHeaders(
288     CompletionOnceCallback callback) {
289   // HttpStreamParser uses a weak pointer when reading from the
290   // socket, so it won't be called back after being destroyed. The
291   // HttpStreamParser is owned by HttpBasicState which is owned by this object,
292   // so this use of base::Unretained() is safe.
293   int rv = parser()->ReadResponseHeaders(base::BindOnce(
294       &WebSocketBasicHandshakeStream::ReadResponseHeadersCallback,
295       base::Unretained(this), std::move(callback)));
296   if (rv == ERR_IO_PENDING)
297     return rv;
298   return ValidateResponse(rv);
299 }
300 
ReadResponseBody(IOBuffer * buf,int buf_len,CompletionOnceCallback callback)301 int WebSocketBasicHandshakeStream::ReadResponseBody(
302     IOBuffer* buf,
303     int buf_len,
304     CompletionOnceCallback callback) {
305   return parser()->ReadResponseBody(buf, buf_len, std::move(callback));
306 }
307 
Close(bool not_reusable)308 void WebSocketBasicHandshakeStream::Close(bool not_reusable) {
309   // This class ignores the value of |not_reusable| and never lets the socket be
310   // re-used.
311   if (!parser())
312     return;
313   StreamSocket* socket = state_.connection()->socket();
314   if (socket)
315     socket->Disconnect();
316   parser()->OnConnectionClose();
317   state_.connection()->Reset();
318 }
319 
IsResponseBodyComplete() const320 bool WebSocketBasicHandshakeStream::IsResponseBodyComplete() const {
321   return parser()->IsResponseBodyComplete();
322 }
323 
IsConnectionReused() const324 bool WebSocketBasicHandshakeStream::IsConnectionReused() const {
325   return state_.IsConnectionReused();
326 }
327 
SetConnectionReused()328 void WebSocketBasicHandshakeStream::SetConnectionReused() {
329   state_.connection()->set_reuse_type(ClientSocketHandle::REUSED_IDLE);
330 }
331 
CanReuseConnection() const332 bool WebSocketBasicHandshakeStream::CanReuseConnection() const {
333   return parser() && state_.connection()->socket() &&
334          parser()->CanReuseConnection();
335 }
336 
GetTotalReceivedBytes() const337 int64_t WebSocketBasicHandshakeStream::GetTotalReceivedBytes() const {
338   return 0;
339 }
340 
GetTotalSentBytes() const341 int64_t WebSocketBasicHandshakeStream::GetTotalSentBytes() const {
342   return 0;
343 }
344 
GetAlternativeService(AlternativeService * alternative_service) const345 bool WebSocketBasicHandshakeStream::GetAlternativeService(
346     AlternativeService* alternative_service) const {
347   return false;
348 }
349 
GetLoadTimingInfo(LoadTimingInfo * load_timing_info) const350 bool WebSocketBasicHandshakeStream::GetLoadTimingInfo(
351     LoadTimingInfo* load_timing_info) const {
352   return state_.connection()->GetLoadTimingInfo(IsConnectionReused(),
353                                                 load_timing_info);
354 }
355 
GetSSLInfo(SSLInfo * ssl_info)356 void WebSocketBasicHandshakeStream::GetSSLInfo(SSLInfo* ssl_info) {
357   if (!state_.connection()->socket() ||
358       !state_.connection()->socket()->GetSSLInfo(ssl_info)) {
359     ssl_info->Reset();
360   }
361 }
362 
GetRemoteEndpoint(IPEndPoint * endpoint)363 int WebSocketBasicHandshakeStream::GetRemoteEndpoint(IPEndPoint* endpoint) {
364   if (!state_.connection() || !state_.connection()->socket())
365     return ERR_SOCKET_NOT_CONNECTED;
366 
367   return state_.connection()->socket()->GetPeerAddress(endpoint);
368 }
369 
PopulateNetErrorDetails(NetErrorDetails *)370 void WebSocketBasicHandshakeStream::PopulateNetErrorDetails(
371     NetErrorDetails* /*details*/) {
372   return;
373 }
374 
Drain(HttpNetworkSession * session)375 void WebSocketBasicHandshakeStream::Drain(HttpNetworkSession* session) {
376   session->StartResponseDrainer(
377       std::make_unique<HttpResponseBodyDrainer>(this));
378   // |drainer| will delete itself.
379 }
380 
SetPriority(RequestPriority priority)381 void WebSocketBasicHandshakeStream::SetPriority(RequestPriority priority) {
382   // TODO(ricea): See TODO comment in HttpBasicStream::SetPriority(). If it is
383   // gone, then copy whatever has happened there over here.
384 }
385 
386 std::unique_ptr<HttpStream>
RenewStreamForAuth()387 WebSocketBasicHandshakeStream::RenewStreamForAuth() {
388   DCHECK(IsResponseBodyComplete());
389   DCHECK(!parser()->IsMoreDataBuffered());
390   // The HttpStreamParser object still has a pointer to the connection. Just to
391   // be extra-sure it doesn't touch the connection again, delete it here rather
392   // than leaving it until the destructor is called.
393   state_.DeleteParser();
394 
395   auto handshake_stream = std::make_unique<WebSocketBasicHandshakeStream>(
396       state_.ReleaseConnection(), connect_delegate_,
397       state_.is_for_get_to_http_proxy(), std::move(requested_sub_protocols_),
398       std::move(requested_extensions_), stream_request_,
399       websocket_endpoint_lock_manager_);
400 
401   stream_request_->OnBasicHandshakeStreamCreated(handshake_stream.get());
402 
403   return handshake_stream;
404 }
405 
GetDnsAliases() const406 const std::set<std::string>& WebSocketBasicHandshakeStream::GetDnsAliases()
407     const {
408   return state_.GetDnsAliases();
409 }
410 
GetAcceptChViaAlps() const411 std::string_view WebSocketBasicHandshakeStream::GetAcceptChViaAlps() const {
412   return {};
413 }
414 
Upgrade()415 std::unique_ptr<WebSocketStream> WebSocketBasicHandshakeStream::Upgrade() {
416   // The HttpStreamParser object has a pointer to our ClientSocketHandle. Make
417   // sure it does not touch it again before it is destroyed.
418   state_.DeleteParser();
419   WebSocketTransportClientSocketPool::UnlockEndpoint(
420       state_.connection(), websocket_endpoint_lock_manager_);
421   std::unique_ptr<WebSocketStream> basic_stream =
422       std::make_unique<WebSocketBasicStream>(
423           std::make_unique<WebSocketClientSocketHandleAdapter>(
424               state_.ReleaseConnection()),
425           state_.read_buf(), sub_protocol_, extensions_, net_log_);
426   DCHECK(extension_params_.get());
427   if (extension_params_->deflate_enabled) {
428     return std::make_unique<WebSocketDeflateStream>(
429         std::move(basic_stream), extension_params_->deflate_parameters,
430         std::make_unique<WebSocketDeflatePredictorImpl>());
431   }
432 
433   return basic_stream;
434 }
435 
CanReadFromStream() const436 bool WebSocketBasicHandshakeStream::CanReadFromStream() const {
437   auto* connection = state_.connection();
438   if (!connection) {
439     return false;
440   }
441   return connection->socket();
442 }
443 
444 base::WeakPtr<WebSocketHandshakeStreamBase>
GetWeakPtr()445 WebSocketBasicHandshakeStream::GetWeakPtr() {
446   return weak_ptr_factory_.GetWeakPtr();
447 }
448 
SetWebSocketKeyForTesting(const std::string & key)449 void WebSocketBasicHandshakeStream::SetWebSocketKeyForTesting(
450     const std::string& key) {
451   handshake_challenge_for_testing_ = key;
452 }
453 
ReadResponseHeadersCallback(CompletionOnceCallback callback,int result)454 void WebSocketBasicHandshakeStream::ReadResponseHeadersCallback(
455     CompletionOnceCallback callback,
456     int result) {
457   std::move(callback).Run(ValidateResponse(result));
458 }
459 
ValidateResponse(int rv)460 int WebSocketBasicHandshakeStream::ValidateResponse(int rv) {
461   DCHECK(http_response_info_);
462   // Most net errors happen during connection, so they are not seen by this
463   // method. The histogram for error codes is created in
464   // Delegate::OnResponseStarted in websocket_stream.cc instead.
465   if (rv >= 0) {
466     const HttpResponseHeaders* headers = http_response_info_->headers.get();
467     const int response_code = headers->response_code();
468     base::UmaHistogramSparse("Net.WebSocket.ResponseCode", response_code);
469     switch (response_code) {
470       case HTTP_SWITCHING_PROTOCOLS:
471         return ValidateUpgradeResponse(headers);
472 
473       // We need to pass these through for authentication to work.
474       case HTTP_UNAUTHORIZED:
475       case HTTP_PROXY_AUTHENTICATION_REQUIRED:
476         return OK;
477 
478       // Other status codes are potentially risky (see the warnings in the
479       // WHATWG WebSocket API spec) and so are dropped by default.
480       default:
481         // A WebSocket server cannot be using HTTP/0.9, so if we see version
482         // 0.9, it means the response was garbage.
483         // Reporting "Unexpected response code: 200" in this case is not
484         // helpful, so use a different error message.
485         if (headers->GetHttpVersion() == HttpVersion(0, 9)) {
486           OnFailure("Error during WebSocket handshake: Invalid status line",
487                     ERR_FAILED, std::nullopt);
488         } else {
489           OnFailure(base::StringPrintf("Error during WebSocket handshake: "
490                                        "Unexpected response code: %d",
491                                        headers->response_code()),
492                     ERR_FAILED, headers->response_code());
493         }
494         result_ = HandshakeResult::INVALID_STATUS;
495         return ERR_INVALID_RESPONSE;
496     }
497   } else {
498     if (rv == ERR_EMPTY_RESPONSE) {
499       OnFailure("Connection closed before receiving a handshake response", rv,
500                 std::nullopt);
501       result_ = HandshakeResult::EMPTY_RESPONSE;
502       return rv;
503     }
504     OnFailure(
505         base::StrCat({"Error during WebSocket handshake: ", ErrorToString(rv)}),
506         rv, std::nullopt);
507     // Some error codes (for example ERR_CONNECTION_CLOSED) get changed to OK at
508     // higher levels. To prevent an unvalidated connection getting erroneously
509     // upgraded, don't pass through the status code unchanged if it is
510     // HTTP_SWITCHING_PROTOCOLS.
511     if (http_response_info_->headers &&
512         http_response_info_->headers->response_code() ==
513             HTTP_SWITCHING_PROTOCOLS) {
514       http_response_info_->headers->ReplaceStatusLine(
515           kConnectionErrorStatusLine);
516       result_ = HandshakeResult::FAILED_SWITCHING_PROTOCOLS;
517       return rv;
518     }
519     result_ = HandshakeResult::FAILED;
520     return rv;
521   }
522 }
523 
ValidateUpgradeResponse(const HttpResponseHeaders * headers)524 int WebSocketBasicHandshakeStream::ValidateUpgradeResponse(
525     const HttpResponseHeaders* headers) {
526   extension_params_ = std::make_unique<WebSocketExtensionParams>();
527   std::string failure_message;
528   if (!ValidateUpgrade(headers, &failure_message)) {
529     result_ = HandshakeResult::FAILED_UPGRADE;
530   } else if (!ValidateSecWebSocketAccept(headers, handshake_challenge_response_,
531                                          &failure_message)) {
532     result_ = HandshakeResult::FAILED_ACCEPT;
533   } else if (!ValidateConnection(headers, &failure_message)) {
534     result_ = HandshakeResult::FAILED_CONNECTION;
535   } else if (!ValidateSubProtocol(headers, requested_sub_protocols_,
536                                   &sub_protocol_, &failure_message)) {
537     result_ = HandshakeResult::FAILED_SUBPROTO;
538   } else if (!ValidateExtensions(headers, &extensions_, &failure_message,
539                                  extension_params_.get())) {
540     result_ = HandshakeResult::FAILED_EXTENSIONS;
541   } else {
542     result_ = HandshakeResult::CONNECTED;
543     return OK;
544   }
545   OnFailure("Error during WebSocket handshake: " + failure_message, ERR_FAILED,
546             std::nullopt);
547   return ERR_INVALID_RESPONSE;
548 }
549 
OnFailure(const std::string & message,int net_error,std::optional<int> response_code)550 void WebSocketBasicHandshakeStream::OnFailure(
551     const std::string& message,
552     int net_error,
553     std::optional<int> response_code) {
554   net_log_.AddEvent(net::NetLogEventType::WEBSOCKET_UPGRADE_FAILURE,
555                     [&] { return NetLogFailureParam(net_error, message); });
556   // Avoid connection reuse if auth did not happen.
557   state_.connection()->socket()->Disconnect();
558   stream_request_->OnFailure(message, net_error, response_code);
559 }
560 
561 }  // namespace net
562