blob: 9ec81a645a3b2d72f90e3ce85fe8604226648ecb [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"
yhirano27b2b572014-10-30 11:23:4415#include "base/compiler_specific.h"
[email protected]8aba0172014-07-03 12:09:5316#include "base/logging.h"
Ilya Sherman0eb39802017-12-08 20:58:1817#include "base/metrics/histogram_functions.h"
[email protected]d51365e2013-11-27 10:46:5218#include "base/stl_util.h"
[email protected]0be93922014-01-29 00:42:4519#include "base/strings/string_number_conversions.h"
[email protected]69d7a492014-02-19 08:36:3220#include "base/strings/string_piece.h"
[email protected]d51365e2013-11-27 10:46:5221#include "base/strings/string_util.h"
[email protected]96868202014-01-09 10:38:0422#include "base/strings/stringprintf.h"
[email protected]cd48ed12014-01-22 14:34:2223#include "base/time/time.h"
[email protected]d51365e2013-11-27 10:46:5224#include "crypto/random.h"
halton.huo299e2002014-12-02 04:39:2425#include "net/base/io_buffer.h"
Tsuyoshi Horo01faed62019-02-20 22:11:3726#include "net/base/ip_endpoint.h"
[email protected]d51365e2013-11-27 10:46:5227#include "net/http/http_request_headers.h"
28#include "net/http/http_request_info.h"
29#include "net/http/http_response_body_drainer.h"
30#include "net/http/http_response_headers.h"
31#include "net/http/http_status_code.h"
32#include "net/http/http_stream_parser.h"
33#include "net/socket/client_socket_handle.h"
Bence Béky3cb271d2018-03-29 22:00:4834#include "net/socket/ssl_client_socket.h"
Bence Békyda280c62018-04-12 15:08:3735#include "net/socket/websocket_endpoint_lock_manager.h"
[email protected]654866142014-06-24 22:53:3136#include "net/socket/websocket_transport_client_socket_pool.h"
Matt Menkef171ff8b2019-02-05 20:06:1337#include "net/ssl/ssl_cert_request_info.h"
38#include "net/ssl/ssl_info.h"
[email protected]d51365e2013-11-27 10:46:5239#include "net/websockets/websocket_basic_stream.h"
Bence Béky7294fc22018-02-08 14:26:1740#include "net/websockets/websocket_basic_stream_adapters.h"
yhirano8387aee2015-09-14 05:46:4941#include "net/websockets/websocket_deflate_parameters.h"
[email protected]0be93922014-01-29 00:42:4542#include "net/websockets/websocket_deflate_predictor.h"
43#include "net/websockets/websocket_deflate_predictor_impl.h"
44#include "net/websockets/websocket_deflate_stream.h"
45#include "net/websockets/websocket_deflater.h"
ricea11bdcd02014-11-20 09:57:0746#include "net/websockets/websocket_handshake_challenge.h"
[email protected]d51365e2013-11-27 10:46:5247#include "net/websockets/websocket_handshake_constants.h"
[email protected]cd48ed12014-01-22 14:34:2248#include "net/websockets/websocket_handshake_request_info.h"
49#include "net/websockets/websocket_handshake_response_info.h"
[email protected]d51365e2013-11-27 10:46:5250#include "net/websockets/websocket_stream.h"
51
52namespace net {
[email protected]0be93922014-01-29 00:42:4553
yhirano27b2b572014-10-30 11:23:4454namespace {
55
ricea23c3f942015-02-02 13:35:1356const char kConnectionErrorStatusLine[] = "HTTP/1.1 503 Connection Error";
57
yhirano27b2b572014-10-30 11:23:4458} // namespace
59
[email protected]d51365e2013-11-27 10:46:5260namespace {
61
[email protected]96868202014-01-09 10:38:0462enum GetHeaderResult {
63 GET_HEADER_OK,
64 GET_HEADER_MISSING,
65 GET_HEADER_MULTIPLE,
66};
67
68std::string MissingHeaderMessage(const std::string& header_name) {
69 return std::string("'") + header_name + "' header is missing";
70}
71
[email protected]d51365e2013-11-27 10:46:5272std::string GenerateHandshakeChallenge() {
73 std::string raw_challenge(websockets::kRawChallengeLength, '\0');
Ryan Sleevi972b2ff2018-05-14 15:45:1074 crypto::RandBytes(base::data(raw_challenge), raw_challenge.length());
[email protected]d51365e2013-11-27 10:46:5275 std::string encoded_challenge;
[email protected]33fca122013-12-11 01:48:5076 base::Base64Encode(raw_challenge, &encoded_challenge);
[email protected]d51365e2013-11-27 10:46:5277 return encoded_challenge;
78}
79
[email protected]96868202014-01-09 10:38:0480GetHeaderResult GetSingleHeaderValue(const HttpResponseHeaders* headers,
81 const base::StringPiece& name,
82 std::string* value) {
olli.raulaee489a52016-01-25 08:37:1083 size_t iter = 0;
[email protected]96868202014-01-09 10:38:0484 size_t num_values = 0;
85 std::string temp_value;
olli.raulaee489a52016-01-25 08:37:1086 while (headers->EnumerateHeader(&iter, name, &temp_value)) {
[email protected]96868202014-01-09 10:38:0487 if (++num_values > 1)
88 return GET_HEADER_MULTIPLE;
89 *value = temp_value;
[email protected]d51365e2013-11-27 10:46:5290 }
[email protected]96868202014-01-09 10:38:0491 return num_values > 0 ? GET_HEADER_OK : GET_HEADER_MISSING;
92}
93
94bool ValidateHeaderHasSingleValue(GetHeaderResult result,
95 const std::string& header_name,
96 std::string* failure_message) {
97 if (result == GET_HEADER_MISSING) {
98 *failure_message = MissingHeaderMessage(header_name);
99 return false;
100 }
101 if (result == GET_HEADER_MULTIPLE) {
Bence Békyb28709c22018-03-06 13:03:44102 *failure_message =
103 WebSocketHandshakeStreamBase::MultipleHeaderValuesMessage(header_name);
[email protected]96868202014-01-09 10:38:04104 return false;
105 }
106 DCHECK_EQ(result, GET_HEADER_OK);
107 return true;
108}
109
110bool ValidateUpgrade(const HttpResponseHeaders* headers,
111 std::string* failure_message) {
112 std::string value;
113 GetHeaderResult result =
114 GetSingleHeaderValue(headers, websockets::kUpgrade, &value);
115 if (!ValidateHeaderHasSingleValue(result,
116 websockets::kUpgrade,
117 failure_message)) {
118 return false;
119 }
120
brettwbc17d2c82015-06-09 22:39:08121 if (!base::LowerCaseEqualsASCII(value, websockets::kWebSocketLowercase)) {
[email protected]96868202014-01-09 10:38:04122 *failure_message =
123 "'Upgrade' header value is not 'WebSocket': " + value;
124 return false;
125 }
126 return true;
127}
128
129bool ValidateSecWebSocketAccept(const HttpResponseHeaders* headers,
130 const std::string& expected,
131 std::string* failure_message) {
132 std::string actual;
133 GetHeaderResult result =
134 GetSingleHeaderValue(headers, websockets::kSecWebSocketAccept, &actual);
135 if (!ValidateHeaderHasSingleValue(result,
136 websockets::kSecWebSocketAccept,
137 failure_message)) {
138 return false;
139 }
140
141 if (expected != actual) {
142 *failure_message = "Incorrect 'Sec-WebSocket-Accept' header value";
143 return false;
144 }
145 return true;
146}
147
148bool ValidateConnection(const HttpResponseHeaders* headers,
149 std::string* failure_message) {
150 // Connection header is permitted to contain other tokens.
151 if (!headers->HasHeader(HttpRequestHeaders::kConnection)) {
152 *failure_message = MissingHeaderMessage(HttpRequestHeaders::kConnection);
153 return false;
154 }
155 if (!headers->HasHeaderValue(HttpRequestHeaders::kConnection,
156 websockets::kUpgrade)) {
157 *failure_message = "'Connection' header value must contain 'Upgrade'";
158 return false;
159 }
160 return true;
[email protected]d51365e2013-11-27 10:46:52161}
162
[email protected]d51365e2013-11-27 10:46:52163} // namespace
164
165WebSocketBasicHandshakeStream::WebSocketBasicHandshakeStream(
danakj9c5cab52016-04-16 00:54:33166 std::unique_ptr<ClientSocketHandle> connection,
[email protected]cd48ed12014-01-22 14:34:22167 WebSocketStream::ConnectDelegate* connect_delegate,
[email protected]d51365e2013-11-27 10:46:52168 bool using_proxy,
169 std::vector<std::string> requested_sub_protocols,
[email protected]8aba0172014-07-03 12:09:53170 std::vector<std::string> requested_extensions,
Adam Rice6f75c0f2018-06-04 08:00:05171 WebSocketStreamRequestAPI* request,
Bence Békyda280c62018-04-12 15:08:37172 WebSocketEndpointLockManager* websocket_endpoint_lock_manager)
Bence Békyde0be312018-03-13 17:51:58173 : result_(HandshakeResult::INCOMPLETE),
174 state_(std::move(connection),
mmenkea7da6da2016-09-01 21:56:52175 using_proxy,
176 false /* http_09_on_non_default_ports_enabled */),
[email protected]cd48ed12014-01-22 14:34:22177 connect_delegate_(connect_delegate),
yhiranoa7e05bb2014-11-06 05:40:39178 http_response_info_(nullptr),
Adam Rice8b382c602018-06-04 12:36:39179 requested_sub_protocols_(std::move(requested_sub_protocols)),
180 requested_extensions_(std::move(requested_extensions)),
Bence Békyda280c62018-04-12 15:08:37181 stream_request_(request),
Bence Békyca0da432019-01-24 15:03:20182 websocket_endpoint_lock_manager_(websocket_endpoint_lock_manager),
183 weak_ptr_factory_(this) {
[email protected]8aba0172014-07-03 12:09:53184 DCHECK(connect_delegate);
tyoshinoccfcfde2016-07-21 14:06:55185 DCHECK(request);
[email protected]8aba0172014-07-03 12:09:53186}
[email protected]d51365e2013-11-27 10:46:52187
Bence Békyde0be312018-03-13 17:51:58188WebSocketBasicHandshakeStream::~WebSocketBasicHandshakeStream() {
Adam Rice8b382c602018-06-04 12:36:39189 // Some members are "stolen" by RenewStreamForAuth() and should not be touched
190 // here. Particularly |connect_delegate_|, |stream_request_|, and
191 // |websocket_endpoint_lock_manager_|.
192
193 // TODO(ricea): What's the right thing to do here if we renewed the stream for
194 // auth? Currently we record it as INCOMPLETE.
Bence Békyde0be312018-03-13 17:51:58195 RecordHandshakeResult(result_);
196}
[email protected]d51365e2013-11-27 10:46:52197
198int WebSocketBasicHandshakeStream::InitializeStream(
199 const HttpRequestInfo* request_info,
Steven Valdezb4ff0412018-01-18 22:39:27200 bool can_send_early,
[email protected]d51365e2013-11-27 10:46:52201 RequestPriority priority,
tfarina42834112016-09-22 13:38:20202 const NetLogWithSource& net_log,
Bence Békya25e3f72018-02-13 21:13:39203 CompletionOnceCallback callback) {
Ramin Halavati20e949f2018-02-14 20:14:32204 DCHECK(request_info->traffic_annotation.is_valid());
[email protected]cd48ed12014-01-22 14:34:22205 url_ = request_info->url;
Findit41ebeea32019-04-08 19:24:30206 state_.Initialize(request_info, can_send_early, priority, net_log);
[email protected]d51365e2013-11-27 10:46:52207 return OK;
208}
209
210int WebSocketBasicHandshakeStream::SendRequest(
211 const HttpRequestHeaders& headers,
212 HttpResponseInfo* response,
Bence Békya25e3f72018-02-13 21:13:39213 CompletionOnceCallback callback) {
[email protected]d51365e2013-11-27 10:46:52214 DCHECK(!headers.HasHeader(websockets::kSecWebSocketKey));
215 DCHECK(!headers.HasHeader(websockets::kSecWebSocketProtocol));
216 DCHECK(!headers.HasHeader(websockets::kSecWebSocketExtensions));
217 DCHECK(headers.HasHeader(HttpRequestHeaders::kOrigin));
218 DCHECK(headers.HasHeader(websockets::kUpgrade));
219 DCHECK(headers.HasHeader(HttpRequestHeaders::kConnection));
220 DCHECK(headers.HasHeader(websockets::kSecWebSocketVersion));
221 DCHECK(parser());
222
223 http_response_info_ = response;
224
225 // Create a copy of the headers object, so that we can add the
226 // Sec-WebSockey-Key header.
227 HttpRequestHeaders enriched_headers;
228 enriched_headers.CopyFrom(headers);
[email protected]a31ecc02013-12-05 08:30:55229 std::string handshake_challenge;
Bence Béky7d0c74d2018-03-05 08:31:09230 if (handshake_challenge_for_testing_.has_value()) {
231 handshake_challenge = handshake_challenge_for_testing_.value();
[email protected]a31ecc02013-12-05 08:30:55232 handshake_challenge_for_testing_.reset();
233 } else {
234 handshake_challenge = GenerateHandshakeChallenge();
235 }
[email protected]d51365e2013-11-27 10:46:52236 enriched_headers.SetHeader(websockets::kSecWebSocketKey, handshake_challenge);
237
[email protected]d51365e2013-11-27 10:46:52238 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketExtensions,
239 requested_extensions_,
240 &enriched_headers);
[email protected]0be93922014-01-29 00:42:45241 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketProtocol,
242 requested_sub_protocols_,
243 &enriched_headers);
[email protected]d51365e2013-11-27 10:46:52244
ricea11bdcd02014-11-20 09:57:07245 handshake_challenge_response_ =
246 ComputeSecWebSocketAccept(handshake_challenge);
[email protected]d51365e2013-11-27 10:46:52247
[email protected]cd48ed12014-01-22 14:34:22248 DCHECK(connect_delegate_);
Bence Béky65623972018-03-05 15:31:56249 auto request =
250 std::make_unique<WebSocketHandshakeRequestInfo>(url_, base::Time::Now());
[email protected]cd48ed12014-01-22 14:34:22251 request->headers.CopyFrom(enriched_headers);
dchengc7eeda422015-12-26 03:56:48252 connect_delegate_->OnStartOpeningHandshake(std::move(request));
[email protected]cd48ed12014-01-22 14:34:22253
Ramin Halavati20e949f2018-02-14 20:14:32254 return parser()->SendRequest(
255 state_.GenerateRequestLine(), enriched_headers,
256 NetworkTrafficAnnotationTag(state_.traffic_annotation()), response,
257 std::move(callback));
[email protected]d51365e2013-11-27 10:46:52258}
259
260int WebSocketBasicHandshakeStream::ReadResponseHeaders(
Bence Békya25e3f72018-02-13 21:13:39261 CompletionOnceCallback callback) {
[email protected]d51365e2013-11-27 10:46:52262 // HttpStreamParser uses a weak pointer when reading from the
263 // socket, so it won't be called back after being destroyed. The
264 // HttpStreamParser is owned by HttpBasicState which is owned by this object,
265 // so this use of base::Unretained() is safe.
Bence Békya25e3f72018-02-13 21:13:39266 int rv = parser()->ReadResponseHeaders(base::BindOnce(
267 &WebSocketBasicHandshakeStream::ReadResponseHeadersCallback,
268 base::Unretained(this), std::move(callback)));
[email protected]cd48ed12014-01-22 14:34:22269 if (rv == ERR_IO_PENDING)
270 return rv;
ricea24c195f2015-02-26 12:18:55271 return ValidateResponse(rv);
[email protected]d51365e2013-11-27 10:46:52272}
273
[email protected]d51365e2013-11-27 10:46:52274int WebSocketBasicHandshakeStream::ReadResponseBody(
275 IOBuffer* buf,
276 int buf_len,
Bence Békya25e3f72018-02-13 21:13:39277 CompletionOnceCallback callback) {
278 return parser()->ReadResponseBody(buf, buf_len, std::move(callback));
[email protected]d51365e2013-11-27 10:46:52279}
280
281void WebSocketBasicHandshakeStream::Close(bool not_reusable) {
282 // This class ignores the value of |not_reusable| and never lets the socket be
283 // re-used.
Matt Menkef171ff8b2019-02-05 20:06:13284 if (!parser())
285 return;
286 StreamSocket* socket = state_.connection()->socket();
287 if (socket)
288 socket->Disconnect();
289 state_.connection()->Reset();
[email protected]d51365e2013-11-27 10:46:52290}
291
292bool WebSocketBasicHandshakeStream::IsResponseBodyComplete() const {
293 return parser()->IsResponseBodyComplete();
294}
295
[email protected]d51365e2013-11-27 10:46:52296bool WebSocketBasicHandshakeStream::IsConnectionReused() const {
Matt Menkef171ff8b2019-02-05 20:06:13297 return state_.IsConnectionReused();
[email protected]d51365e2013-11-27 10:46:52298}
299
300void WebSocketBasicHandshakeStream::SetConnectionReused() {
Matt Menkef171ff8b2019-02-05 20:06:13301 state_.connection()->set_reuse_type(ClientSocketHandle::REUSED_IDLE);
[email protected]d51365e2013-11-27 10:46:52302}
303
mmenkebd84c392015-09-02 14:12:34304bool WebSocketBasicHandshakeStream::CanReuseConnection() const {
Matt Menkef171ff8b2019-02-05 20:06:13305 return parser() && state_.connection()->socket() &&
306 parser()->CanReuseConnection();
[email protected]d51365e2013-11-27 10:46:52307}
308
sclittle4de1bab92015-09-22 21:28:24309int64_t WebSocketBasicHandshakeStream::GetTotalReceivedBytes() const {
[email protected]bc92bc972013-12-13 08:32:59310 return 0;
311}
312
sclittlebe1ccf62015-09-02 19:40:36313int64_t WebSocketBasicHandshakeStream::GetTotalSentBytes() const {
314 return 0;
315}
316
rchcd379012017-04-12 21:53:32317bool WebSocketBasicHandshakeStream::GetAlternativeService(
318 AlternativeService* alternative_service) const {
319 return false;
320}
321
[email protected]d51365e2013-11-27 10:46:52322bool WebSocketBasicHandshakeStream::GetLoadTimingInfo(
323 LoadTimingInfo* load_timing_info) const {
324 return state_.connection()->GetLoadTimingInfo(IsConnectionReused(),
325 load_timing_info);
326}
327
328void WebSocketBasicHandshakeStream::GetSSLInfo(SSLInfo* ssl_info) {
Matt Menkef171ff8b2019-02-05 20:06:13329 if (!state_.connection()->socket()) {
330 ssl_info->Reset();
331 return;
332 }
[email protected]d51365e2013-11-27 10:46:52333 parser()->GetSSLInfo(ssl_info);
334}
335
336void WebSocketBasicHandshakeStream::GetSSLCertRequestInfo(
337 SSLCertRequestInfo* cert_request_info) {
Matt Menkef171ff8b2019-02-05 20:06:13338 if (!state_.connection()->socket()) {
339 cert_request_info->Reset();
340 return;
341 }
[email protected]d51365e2013-11-27 10:46:52342 parser()->GetSSLCertRequestInfo(cert_request_info);
343}
344
ttuttled9dbc652015-09-29 20:00:59345bool WebSocketBasicHandshakeStream::GetRemoteEndpoint(IPEndPoint* endpoint) {
346 if (!state_.connection() || !state_.connection()->socket())
347 return false;
348
349 return state_.connection()->socket()->GetPeerAddress(endpoint) == OK;
350}
351
zhongyica364fbb2015-12-12 03:39:12352void WebSocketBasicHandshakeStream::PopulateNetErrorDetails(
353 NetErrorDetails* /*details*/) {
354 return;
355}
356
[email protected]d51365e2013-11-27 10:46:52357void WebSocketBasicHandshakeStream::Drain(HttpNetworkSession* session) {
358 HttpResponseBodyDrainer* drainer = new HttpResponseBodyDrainer(this);
359 drainer->Start(session);
360 // |drainer| will delete itself.
361}
362
363void WebSocketBasicHandshakeStream::SetPriority(RequestPriority priority) {
364 // TODO(ricea): See TODO comment in HttpBasicStream::SetPriority(). If it is
365 // gone, then copy whatever has happened there over here.
366}
367
yhiranoa7e05bb2014-11-06 05:40:39368HttpStream* WebSocketBasicHandshakeStream::RenewStreamForAuth() {
Adam Rice8b382c602018-06-04 12:36:39369 DCHECK(IsResponseBodyComplete());
370 DCHECK(!parser()->IsMoreDataBuffered());
371 // The HttpStreamParser object still has a pointer to the connection. Just to
372 // be extra-sure it doesn't touch the connection again, delete it here rather
373 // than leaving it until the destructor is called.
374 state_.DeleteParser();
375
376 auto handshake_stream = std::make_unique<WebSocketBasicHandshakeStream>(
377 state_.ReleaseConnection(), connect_delegate_, state_.using_proxy(),
378 std::move(requested_sub_protocols_), std::move(requested_extensions_),
379 stream_request_, websocket_endpoint_lock_manager_);
380
381 stream_request_->OnBasicHandshakeStreamCreated(handshake_stream.get());
382
383 return handshake_stream.release();
yhiranoa7e05bb2014-11-06 05:40:39384}
385
danakj9c5cab52016-04-16 00:54:33386std::unique_ptr<WebSocketStream> WebSocketBasicHandshakeStream::Upgrade() {
[email protected]d51365e2013-11-27 10:46:52387 // The HttpStreamParser object has a pointer to our ClientSocketHandle. Make
388 // sure it does not touch it again before it is destroyed.
389 state_.DeleteParser();
Bence Békyda280c62018-04-12 15:08:37390 WebSocketTransportClientSocketPool::UnlockEndpoint(
391 state_.connection(), websocket_endpoint_lock_manager_);
Bence Béky7294fc22018-02-08 14:26:17392 std::unique_ptr<WebSocketStream> basic_stream =
393 std::make_unique<WebSocketBasicStream>(
394 std::make_unique<WebSocketClientSocketHandleAdapter>(
395 state_.ReleaseConnection()),
396 state_.read_buf(), sub_protocol_, extensions_);
[email protected]0be93922014-01-29 00:42:45397 DCHECK(extension_params_.get());
398 if (extension_params_->deflate_enabled) {
Bence Békyde0be312018-03-13 17:51:58399 RecordDeflateMode(
400 extension_params_->deflate_parameters.client_context_take_over_mode());
[email protected]9c50b042014-04-28 06:40:15401
Bence Béky65623972018-03-05 15:31:56402 return std::make_unique<WebSocketDeflateStream>(
dchengc7eeda422015-12-26 03:56:48403 std::move(basic_stream), extension_params_->deflate_parameters,
Bence Béky65623972018-03-05 15:31:56404 std::make_unique<WebSocketDeflatePredictorImpl>());
[email protected]0be93922014-01-29 00:42:45405 } else {
dchengc7eeda422015-12-26 03:56:48406 return basic_stream;
[email protected]0be93922014-01-29 00:42:45407 }
[email protected]d51365e2013-11-27 10:46:52408}
409
Bence Békyca0da432019-01-24 15:03:20410base::WeakPtr<WebSocketHandshakeStreamBase>
411WebSocketBasicHandshakeStream::GetWeakPtr() {
412 return weak_ptr_factory_.GetWeakPtr();
413}
414
[email protected]a31ecc02013-12-05 08:30:55415void WebSocketBasicHandshakeStream::SetWebSocketKeyForTesting(
416 const std::string& key) {
Bence Béky7d0c74d2018-03-05 08:31:09417 handshake_challenge_for_testing_ = key;
[email protected]a31ecc02013-12-05 08:30:55418}
419
[email protected]d51365e2013-11-27 10:46:52420void WebSocketBasicHandshakeStream::ReadResponseHeadersCallback(
Bence Békya25e3f72018-02-13 21:13:39421 CompletionOnceCallback callback,
[email protected]d51365e2013-11-27 10:46:52422 int result) {
Bence Békya25e3f72018-02-13 21:13:39423 std::move(callback).Run(ValidateResponse(result));
[email protected]d51365e2013-11-27 10:46:52424}
425
[email protected]cd48ed12014-01-22 14:34:22426void WebSocketBasicHandshakeStream::OnFinishOpeningHandshake() {
[email protected]cd48ed12014-01-22 14:34:22427 DCHECK(http_response_info_);
Yutaka Hirano36c94952018-05-30 21:33:33428 WebSocketDispatchOnFinishOpeningHandshake(
429 connect_delegate_, url_, http_response_info_->headers,
Tsuyoshi Horo01faed62019-02-20 22:11:37430 http_response_info_->remote_endpoint, http_response_info_->response_time);
[email protected]cd48ed12014-01-22 14:34:22431}
432
ricea24c195f2015-02-26 12:18:55433int WebSocketBasicHandshakeStream::ValidateResponse(int rv) {
[email protected]d51365e2013-11-27 10:46:52434 DCHECK(http_response_info_);
[email protected]f7e98ca2014-06-19 12:05:43435 // Most net errors happen during connection, so they are not seen by this
436 // method. The histogram for error codes is created in
437 // Delegate::OnResponseStarted in websocket_stream.cc instead.
[email protected]e5760f522014-02-05 12:28:50438 if (rv >= 0) {
[email protected]f7e98ca2014-06-19 12:05:43439 const HttpResponseHeaders* headers = http_response_info_->headers.get();
440 const int response_code = headers->response_code();
Ilya Sherman0eb39802017-12-08 20:58:18441 base::UmaHistogramSparse("Net.WebSocket.ResponseCode", response_code);
[email protected]f7e98ca2014-06-19 12:05:43442 switch (response_code) {
[email protected]e5760f522014-02-05 12:28:50443 case HTTP_SWITCHING_PROTOCOLS:
444 OnFinishOpeningHandshake();
445 return ValidateUpgradeResponse(headers);
[email protected]d51365e2013-11-27 10:46:52446
[email protected]e5760f522014-02-05 12:28:50447 // We need to pass these through for authentication to work.
448 case HTTP_UNAUTHORIZED:
449 case HTTP_PROXY_AUTHENTICATION_REQUIRED:
450 return OK;
[email protected]d51365e2013-11-27 10:46:52451
[email protected]e5760f522014-02-05 12:28:50452 // Other status codes are potentially risky (see the warnings in the
453 // WHATWG WebSocket API spec) and so are dropped by default.
454 default:
[email protected]aeb640d2014-02-21 11:03:18455 // A WebSocket server cannot be using HTTP/0.9, so if we see version
456 // 0.9, it means the response was garbage.
457 // Reporting "Unexpected response code: 200" in this case is not
458 // helpful, so use a different error message.
459 if (headers->GetHttpVersion() == HttpVersion(0, 9)) {
tyoshinoccfcfde2016-07-21 14:06:55460 OnFailure("Error during WebSocket handshake: Invalid status line");
[email protected]aeb640d2014-02-21 11:03:18461 } else {
tyoshinoccfcfde2016-07-21 14:06:55462 OnFailure(base::StringPrintf(
[email protected]aeb640d2014-02-21 11:03:18463 "Error during WebSocket handshake: Unexpected response code: %d",
[email protected]8aba0172014-07-03 12:09:53464 headers->response_code()));
[email protected]aeb640d2014-02-21 11:03:18465 }
[email protected]e5760f522014-02-05 12:28:50466 OnFinishOpeningHandshake();
Bence Békyde0be312018-03-13 17:51:58467 result_ = HandshakeResult::INVALID_STATUS;
[email protected]e5760f522014-02-05 12:28:50468 return ERR_INVALID_RESPONSE;
469 }
470 } else {
[email protected]3efc08f2014-02-07 09:33:34471 if (rv == ERR_EMPTY_RESPONSE) {
tyoshinoccfcfde2016-07-21 14:06:55472 OnFailure("Connection closed before receiving a handshake response");
Bence Békyde0be312018-03-13 17:51:58473 result_ = HandshakeResult::EMPTY_RESPONSE;
[email protected]3efc08f2014-02-07 09:33:34474 return rv;
475 }
tyoshinoccfcfde2016-07-21 14:06:55476 OnFailure(std::string("Error during WebSocket handshake: ") +
477 ErrorToString(rv));
[email protected]e5760f522014-02-05 12:28:50478 OnFinishOpeningHandshake();
ricea23c3f942015-02-02 13:35:13479 // Some error codes (for example ERR_CONNECTION_CLOSED) get changed to OK at
480 // higher levels. To prevent an unvalidated connection getting erroneously
481 // upgraded, don't pass through the status code unchanged if it is
482 // HTTP_SWITCHING_PROTOCOLS.
483 if (http_response_info_->headers &&
484 http_response_info_->headers->response_code() ==
485 HTTP_SWITCHING_PROTOCOLS) {
486 http_response_info_->headers->ReplaceStatusLine(
487 kConnectionErrorStatusLine);
Bence Békyde0be312018-03-13 17:51:58488 result_ = HandshakeResult::FAILED_SWITCHING_PROTOCOLS;
489 return rv;
ricea23c3f942015-02-02 13:35:13490 }
Bence Békyde0be312018-03-13 17:51:58491 result_ = HandshakeResult::FAILED;
[email protected]e5760f522014-02-05 12:28:50492 return rv;
[email protected]d51365e2013-11-27 10:46:52493 }
494}
495
496int WebSocketBasicHandshakeStream::ValidateUpgradeResponse(
[email protected]e5760f522014-02-05 12:28:50497 const HttpResponseHeaders* headers) {
Bence Béky65623972018-03-05 15:31:56498 extension_params_ = std::make_unique<WebSocketExtensionParams>();
[email protected]8aba0172014-07-03 12:09:53499 std::string failure_message;
Bence Békyde0be312018-03-13 17:51:58500 if (!ValidateUpgrade(headers, &failure_message)) {
501 result_ = HandshakeResult::FAILED_UPGRADE;
502 } else if (!ValidateSecWebSocketAccept(headers, handshake_challenge_response_,
503 &failure_message)) {
504 result_ = HandshakeResult::FAILED_ACCEPT;
505 } else if (!ValidateConnection(headers, &failure_message)) {
506 result_ = HandshakeResult::FAILED_CONNECTION;
507 } else if (!ValidateSubProtocol(headers, requested_sub_protocols_,
508 &sub_protocol_, &failure_message)) {
509 result_ = HandshakeResult::FAILED_SUBPROTO;
510 } else if (!ValidateExtensions(headers, &extensions_, &failure_message,
511 extension_params_.get())) {
512 result_ = HandshakeResult::FAILED_EXTENSIONS;
513 } else {
514 result_ = HandshakeResult::CONNECTED;
[email protected]d51365e2013-11-27 10:46:52515 return OK;
516 }
tyoshinoccfcfde2016-07-21 14:06:55517 OnFailure("Error during WebSocket handshake: " + failure_message);
[email protected]d51365e2013-11-27 10:46:52518 return ERR_INVALID_RESPONSE;
519}
520
tyoshinoccfcfde2016-07-21 14:06:55521void WebSocketBasicHandshakeStream::OnFailure(const std::string& message) {
Adam Riced4596a8e2018-07-13 08:06:17522 // Avoid connection reuse if auth did not happen.
523 state_.connection()->socket()->Disconnect();
tyoshinoccfcfde2016-07-21 14:06:55524 stream_request_->OnFailure(message);
[email protected]8aba0172014-07-03 12:09:53525}
526
[email protected]d51365e2013-11-27 10:46:52527} // namespace net