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