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