blob: 3fcdf38e02642e53f8fac7ba3eb93fd55b1fc5ee [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"
[email protected]d51365e2013-11-27 10:46:5226#include "net/http/http_request_headers.h"
27#include "net/http/http_request_info.h"
28#include "net/http/http_response_body_drainer.h"
29#include "net/http/http_response_headers.h"
30#include "net/http/http_status_code.h"
31#include "net/http/http_stream_parser.h"
32#include "net/socket/client_socket_handle.h"
Bence Béky3cb271d2018-03-29 22:00:4833#include "net/socket/ssl_client_socket.h"
Bence Békyda280c62018-04-12 15:08:3734#include "net/socket/websocket_endpoint_lock_manager.h"
[email protected]654866142014-06-24 22:53:3135#include "net/socket/websocket_transport_client_socket_pool.h"
[email protected]d51365e2013-11-27 10:46:5236#include "net/websockets/websocket_basic_stream.h"
Bence Béky7294fc22018-02-08 14:26:1737#include "net/websockets/websocket_basic_stream_adapters.h"
yhirano8387aee2015-09-14 05:46:4938#include "net/websockets/websocket_deflate_parameters.h"
[email protected]0be93922014-01-29 00:42:4539#include "net/websockets/websocket_deflate_predictor.h"
40#include "net/websockets/websocket_deflate_predictor_impl.h"
41#include "net/websockets/websocket_deflate_stream.h"
42#include "net/websockets/websocket_deflater.h"
ricea11bdcd02014-11-20 09:57:0743#include "net/websockets/websocket_handshake_challenge.h"
[email protected]d51365e2013-11-27 10:46:5244#include "net/websockets/websocket_handshake_constants.h"
[email protected]cd48ed12014-01-22 14:34:2245#include "net/websockets/websocket_handshake_request_info.h"
46#include "net/websockets/websocket_handshake_response_info.h"
[email protected]d51365e2013-11-27 10:46:5247#include "net/websockets/websocket_stream.h"
48
49namespace net {
[email protected]0be93922014-01-29 00:42:4550
yhirano27b2b572014-10-30 11:23:4451namespace {
52
ricea23c3f942015-02-02 13:35:1353const char kConnectionErrorStatusLine[] = "HTTP/1.1 503 Connection Error";
54
yhirano27b2b572014-10-30 11:23:4455} // namespace
56
[email protected]d51365e2013-11-27 10:46:5257namespace {
58
[email protected]96868202014-01-09 10:38:0459enum GetHeaderResult {
60 GET_HEADER_OK,
61 GET_HEADER_MISSING,
62 GET_HEADER_MULTIPLE,
63};
64
65std::string MissingHeaderMessage(const std::string& header_name) {
66 return std::string("'") + header_name + "' header is missing";
67}
68
[email protected]d51365e2013-11-27 10:46:5269std::string GenerateHandshakeChallenge() {
70 std::string raw_challenge(websockets::kRawChallengeLength, '\0');
Ryan Sleevi972b2ff2018-05-14 15:45:1071 crypto::RandBytes(base::data(raw_challenge), raw_challenge.length());
[email protected]d51365e2013-11-27 10:46:5272 std::string encoded_challenge;
[email protected]33fca122013-12-11 01:48:5073 base::Base64Encode(raw_challenge, &encoded_challenge);
[email protected]d51365e2013-11-27 10:46:5274 return encoded_challenge;
75}
76
[email protected]96868202014-01-09 10:38:0477GetHeaderResult GetSingleHeaderValue(const HttpResponseHeaders* headers,
78 const base::StringPiece& name,
79 std::string* value) {
olli.raulaee489a52016-01-25 08:37:1080 size_t iter = 0;
[email protected]96868202014-01-09 10:38:0481 size_t num_values = 0;
82 std::string temp_value;
olli.raulaee489a52016-01-25 08:37:1083 while (headers->EnumerateHeader(&iter, name, &temp_value)) {
[email protected]96868202014-01-09 10:38:0484 if (++num_values > 1)
85 return GET_HEADER_MULTIPLE;
86 *value = temp_value;
[email protected]d51365e2013-11-27 10:46:5287 }
[email protected]96868202014-01-09 10:38:0488 return num_values > 0 ? GET_HEADER_OK : GET_HEADER_MISSING;
89}
90
91bool ValidateHeaderHasSingleValue(GetHeaderResult result,
92 const std::string& header_name,
93 std::string* failure_message) {
94 if (result == GET_HEADER_MISSING) {
95 *failure_message = MissingHeaderMessage(header_name);
96 return false;
97 }
98 if (result == GET_HEADER_MULTIPLE) {
Bence Békyb28709c22018-03-06 13:03:4499 *failure_message =
100 WebSocketHandshakeStreamBase::MultipleHeaderValuesMessage(header_name);
[email protected]96868202014-01-09 10:38:04101 return false;
102 }
103 DCHECK_EQ(result, GET_HEADER_OK);
104 return true;
105}
106
107bool ValidateUpgrade(const HttpResponseHeaders* headers,
108 std::string* failure_message) {
109 std::string value;
110 GetHeaderResult result =
111 GetSingleHeaderValue(headers, websockets::kUpgrade, &value);
112 if (!ValidateHeaderHasSingleValue(result,
113 websockets::kUpgrade,
114 failure_message)) {
115 return false;
116 }
117
brettwbc17d2c82015-06-09 22:39:08118 if (!base::LowerCaseEqualsASCII(value, websockets::kWebSocketLowercase)) {
[email protected]96868202014-01-09 10:38:04119 *failure_message =
120 "'Upgrade' header value is not 'WebSocket': " + value;
121 return false;
122 }
123 return true;
124}
125
126bool ValidateSecWebSocketAccept(const HttpResponseHeaders* headers,
127 const std::string& expected,
128 std::string* failure_message) {
129 std::string actual;
130 GetHeaderResult result =
131 GetSingleHeaderValue(headers, websockets::kSecWebSocketAccept, &actual);
132 if (!ValidateHeaderHasSingleValue(result,
133 websockets::kSecWebSocketAccept,
134 failure_message)) {
135 return false;
136 }
137
138 if (expected != actual) {
139 *failure_message = "Incorrect 'Sec-WebSocket-Accept' header value";
140 return false;
141 }
142 return true;
143}
144
145bool ValidateConnection(const HttpResponseHeaders* headers,
146 std::string* failure_message) {
147 // Connection header is permitted to contain other tokens.
148 if (!headers->HasHeader(HttpRequestHeaders::kConnection)) {
149 *failure_message = MissingHeaderMessage(HttpRequestHeaders::kConnection);
150 return false;
151 }
152 if (!headers->HasHeaderValue(HttpRequestHeaders::kConnection,
153 websockets::kUpgrade)) {
154 *failure_message = "'Connection' header value must contain 'Upgrade'";
155 return false;
156 }
157 return true;
[email protected]d51365e2013-11-27 10:46:52158}
159
[email protected]d51365e2013-11-27 10:46:52160} // namespace
161
Adam Ricec786ad8a2018-05-22 09:49:15162const base::Feature
163 WebSocketBasicHandshakeStream::kWebSocketHandshakeReuseConnection{
164 "WebSocketHandshakeReuseConnection", base::FEATURE_DISABLED_BY_DEFAULT};
165
[email protected]d51365e2013-11-27 10:46:52166WebSocketBasicHandshakeStream::WebSocketBasicHandshakeStream(
danakj9c5cab52016-04-16 00:54:33167 std::unique_ptr<ClientSocketHandle> connection,
[email protected]cd48ed12014-01-22 14:34:22168 WebSocketStream::ConnectDelegate* connect_delegate,
[email protected]d51365e2013-11-27 10:46:52169 bool using_proxy,
170 std::vector<std::string> requested_sub_protocols,
[email protected]8aba0172014-07-03 12:09:53171 std::vector<std::string> requested_extensions,
Adam Rice6f75c0f2018-06-04 08:00:05172 WebSocketStreamRequestAPI* request,
Bence Békyda280c62018-04-12 15:08:37173 WebSocketEndpointLockManager* websocket_endpoint_lock_manager)
Bence Békyde0be312018-03-13 17:51:58174 : result_(HandshakeResult::INCOMPLETE),
175 state_(std::move(connection),
mmenkea7da6da2016-09-01 21:56:52176 using_proxy,
177 false /* http_09_on_non_default_ports_enabled */),
[email protected]cd48ed12014-01-22 14:34:22178 connect_delegate_(connect_delegate),
yhiranoa7e05bb2014-11-06 05:40:39179 http_response_info_(nullptr),
Adam Rice8b382c602018-06-04 12:36:39180 requested_sub_protocols_(std::move(requested_sub_protocols)),
181 requested_extensions_(std::move(requested_extensions)),
Bence Békyda280c62018-04-12 15:08:37182 stream_request_(request),
183 websocket_endpoint_lock_manager_(websocket_endpoint_lock_manager) {
[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;
Bence Békyd5d65a912018-02-11 04:28:00206 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.
284 if (parser())
285 parser()->Close(true);
286}
287
288bool WebSocketBasicHandshakeStream::IsResponseBodyComplete() const {
289 return parser()->IsResponseBodyComplete();
290}
291
[email protected]d51365e2013-11-27 10:46:52292bool WebSocketBasicHandshakeStream::IsConnectionReused() const {
293 return parser()->IsConnectionReused();
294}
295
296void WebSocketBasicHandshakeStream::SetConnectionReused() {
297 parser()->SetConnectionReused();
298}
299
mmenkebd84c392015-09-02 14:12:34300bool WebSocketBasicHandshakeStream::CanReuseConnection() const {
Adam Ricec786ad8a2018-05-22 09:49:15301 if (!base::FeatureList::IsEnabled(kWebSocketHandshakeReuseConnection))
302 return false;
303
304 return parser() && parser()->CanReuseConnection();
[email protected]d51365e2013-11-27 10:46:52305}
306
sclittle4de1bab92015-09-22 21:28:24307int64_t WebSocketBasicHandshakeStream::GetTotalReceivedBytes() const {
[email protected]bc92bc972013-12-13 08:32:59308 return 0;
309}
310
sclittlebe1ccf62015-09-02 19:40:36311int64_t WebSocketBasicHandshakeStream::GetTotalSentBytes() const {
312 return 0;
313}
314
rchcd379012017-04-12 21:53:32315bool WebSocketBasicHandshakeStream::GetAlternativeService(
316 AlternativeService* alternative_service) const {
317 return false;
318}
319
[email protected]d51365e2013-11-27 10:46:52320bool WebSocketBasicHandshakeStream::GetLoadTimingInfo(
321 LoadTimingInfo* load_timing_info) const {
322 return state_.connection()->GetLoadTimingInfo(IsConnectionReused(),
323 load_timing_info);
324}
325
326void WebSocketBasicHandshakeStream::GetSSLInfo(SSLInfo* ssl_info) {
327 parser()->GetSSLInfo(ssl_info);
328}
329
330void WebSocketBasicHandshakeStream::GetSSLCertRequestInfo(
331 SSLCertRequestInfo* cert_request_info) {
332 parser()->GetSSLCertRequestInfo(cert_request_info);
333}
334
ttuttled9dbc652015-09-29 20:00:59335bool WebSocketBasicHandshakeStream::GetRemoteEndpoint(IPEndPoint* endpoint) {
336 if (!state_.connection() || !state_.connection()->socket())
337 return false;
338
339 return state_.connection()->socket()->GetPeerAddress(endpoint) == OK;
340}
341
zhongyica364fbb2015-12-12 03:39:12342void WebSocketBasicHandshakeStream::PopulateNetErrorDetails(
343 NetErrorDetails* /*details*/) {
344 return;
345}
346
nharper78e6d2b2016-09-21 05:42:35347Error WebSocketBasicHandshakeStream::GetTokenBindingSignature(
nharperb7441ef2016-01-25 23:54:14348 crypto::ECPrivateKey* key,
nharper78e6d2b2016-09-21 05:42:35349 TokenBindingType tb_type,
nharperb7441ef2016-01-25 23:54:14350 std::vector<uint8_t>* out) {
Bence Béky3cb271d2018-03-29 22:00:48351 DCHECK(url_.SchemeIsCryptographic());
352
Bence Békydae8af5f2018-04-13 08:53:17353 return state_.connection()->socket()->GetTokenBindingSignature(key, tb_type,
354 out);
nharperb7441ef2016-01-25 23:54:14355}
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 if (!base::FeatureList::IsEnabled(kWebSocketHandshakeReuseConnection))
370 return nullptr;
371
372 DCHECK(IsResponseBodyComplete());
373 DCHECK(!parser()->IsMoreDataBuffered());
374 // The HttpStreamParser object still has a pointer to the connection. Just to
375 // be extra-sure it doesn't touch the connection again, delete it here rather
376 // than leaving it until the destructor is called.
377 state_.DeleteParser();
378
379 auto handshake_stream = std::make_unique<WebSocketBasicHandshakeStream>(
380 state_.ReleaseConnection(), connect_delegate_, state_.using_proxy(),
381 std::move(requested_sub_protocols_), std::move(requested_extensions_),
382 stream_request_, websocket_endpoint_lock_manager_);
383
384 stream_request_->OnBasicHandshakeStreamCreated(handshake_stream.get());
385
386 return handshake_stream.release();
yhiranoa7e05bb2014-11-06 05:40:39387}
388
danakj9c5cab52016-04-16 00:54:33389std::unique_ptr<WebSocketStream> WebSocketBasicHandshakeStream::Upgrade() {
[email protected]d51365e2013-11-27 10:46:52390 // The HttpStreamParser object has a pointer to our ClientSocketHandle. Make
391 // sure it does not touch it again before it is destroyed.
392 state_.DeleteParser();
Bence Békyda280c62018-04-12 15:08:37393 WebSocketTransportClientSocketPool::UnlockEndpoint(
394 state_.connection(), websocket_endpoint_lock_manager_);
Bence Béky7294fc22018-02-08 14:26:17395 std::unique_ptr<WebSocketStream> basic_stream =
396 std::make_unique<WebSocketBasicStream>(
397 std::make_unique<WebSocketClientSocketHandleAdapter>(
398 state_.ReleaseConnection()),
399 state_.read_buf(), sub_protocol_, extensions_);
[email protected]0be93922014-01-29 00:42:45400 DCHECK(extension_params_.get());
401 if (extension_params_->deflate_enabled) {
Bence Békyde0be312018-03-13 17:51:58402 RecordDeflateMode(
403 extension_params_->deflate_parameters.client_context_take_over_mode());
[email protected]9c50b042014-04-28 06:40:15404
Bence Béky65623972018-03-05 15:31:56405 return std::make_unique<WebSocketDeflateStream>(
dchengc7eeda422015-12-26 03:56:48406 std::move(basic_stream), extension_params_->deflate_parameters,
Bence Béky65623972018-03-05 15:31:56407 std::make_unique<WebSocketDeflatePredictorImpl>());
[email protected]0be93922014-01-29 00:42:45408 } else {
dchengc7eeda422015-12-26 03:56:48409 return basic_stream;
[email protected]0be93922014-01-29 00:42:45410 }
[email protected]d51365e2013-11-27 10:46:52411}
412
[email protected]a31ecc02013-12-05 08:30:55413void WebSocketBasicHandshakeStream::SetWebSocketKeyForTesting(
414 const std::string& key) {
Bence Béky7d0c74d2018-03-05 08:31:09415 handshake_challenge_for_testing_ = key;
[email protected]a31ecc02013-12-05 08:30:55416}
417
[email protected]d51365e2013-11-27 10:46:52418void WebSocketBasicHandshakeStream::ReadResponseHeadersCallback(
Bence Békya25e3f72018-02-13 21:13:39419 CompletionOnceCallback callback,
[email protected]d51365e2013-11-27 10:46:52420 int result) {
Bence Békya25e3f72018-02-13 21:13:39421 std::move(callback).Run(ValidateResponse(result));
[email protected]d51365e2013-11-27 10:46:52422}
423
[email protected]cd48ed12014-01-22 14:34:22424void WebSocketBasicHandshakeStream::OnFinishOpeningHandshake() {
[email protected]cd48ed12014-01-22 14:34:22425 DCHECK(http_response_info_);
Yutaka Hirano36c94952018-05-30 21:33:33426 WebSocketDispatchOnFinishOpeningHandshake(
427 connect_delegate_, url_, http_response_info_->headers,
428 http_response_info_->socket_address, http_response_info_->response_time);
[email protected]cd48ed12014-01-22 14:34:22429}
430
ricea24c195f2015-02-26 12:18:55431int WebSocketBasicHandshakeStream::ValidateResponse(int rv) {
[email protected]d51365e2013-11-27 10:46:52432 DCHECK(http_response_info_);
[email protected]f7e98ca2014-06-19 12:05:43433 // Most net errors happen during connection, so they are not seen by this
434 // method. The histogram for error codes is created in
435 // Delegate::OnResponseStarted in websocket_stream.cc instead.
[email protected]e5760f522014-02-05 12:28:50436 if (rv >= 0) {
[email protected]f7e98ca2014-06-19 12:05:43437 const HttpResponseHeaders* headers = http_response_info_->headers.get();
438 const int response_code = headers->response_code();
Ilya Sherman0eb39802017-12-08 20:58:18439 base::UmaHistogramSparse("Net.WebSocket.ResponseCode", response_code);
[email protected]f7e98ca2014-06-19 12:05:43440 switch (response_code) {
[email protected]e5760f522014-02-05 12:28:50441 case HTTP_SWITCHING_PROTOCOLS:
442 OnFinishOpeningHandshake();
443 return ValidateUpgradeResponse(headers);
[email protected]d51365e2013-11-27 10:46:52444
[email protected]e5760f522014-02-05 12:28:50445 // We need to pass these through for authentication to work.
446 case HTTP_UNAUTHORIZED:
447 case HTTP_PROXY_AUTHENTICATION_REQUIRED:
448 return OK;
[email protected]d51365e2013-11-27 10:46:52449
[email protected]e5760f522014-02-05 12:28:50450 // Other status codes are potentially risky (see the warnings in the
451 // WHATWG WebSocket API spec) and so are dropped by default.
452 default:
[email protected]aeb640d2014-02-21 11:03:18453 // A WebSocket server cannot be using HTTP/0.9, so if we see version
454 // 0.9, it means the response was garbage.
455 // Reporting "Unexpected response code: 200" in this case is not
456 // helpful, so use a different error message.
457 if (headers->GetHttpVersion() == HttpVersion(0, 9)) {
tyoshinoccfcfde2016-07-21 14:06:55458 OnFailure("Error during WebSocket handshake: Invalid status line");
[email protected]aeb640d2014-02-21 11:03:18459 } else {
tyoshinoccfcfde2016-07-21 14:06:55460 OnFailure(base::StringPrintf(
[email protected]aeb640d2014-02-21 11:03:18461 "Error during WebSocket handshake: Unexpected response code: %d",
[email protected]8aba0172014-07-03 12:09:53462 headers->response_code()));
[email protected]aeb640d2014-02-21 11:03:18463 }
[email protected]e5760f522014-02-05 12:28:50464 OnFinishOpeningHandshake();
Bence Békyde0be312018-03-13 17:51:58465 result_ = HandshakeResult::INVALID_STATUS;
[email protected]e5760f522014-02-05 12:28:50466 return ERR_INVALID_RESPONSE;
467 }
468 } else {
[email protected]3efc08f2014-02-07 09:33:34469 if (rv == ERR_EMPTY_RESPONSE) {
tyoshinoccfcfde2016-07-21 14:06:55470 OnFailure("Connection closed before receiving a handshake response");
Bence Békyde0be312018-03-13 17:51:58471 result_ = HandshakeResult::EMPTY_RESPONSE;
[email protected]3efc08f2014-02-07 09:33:34472 return rv;
473 }
tyoshinoccfcfde2016-07-21 14:06:55474 OnFailure(std::string("Error during WebSocket handshake: ") +
475 ErrorToString(rv));
[email protected]e5760f522014-02-05 12:28:50476 OnFinishOpeningHandshake();
ricea23c3f942015-02-02 13:35:13477 // Some error codes (for example ERR_CONNECTION_CLOSED) get changed to OK at
478 // higher levels. To prevent an unvalidated connection getting erroneously
479 // upgraded, don't pass through the status code unchanged if it is
480 // HTTP_SWITCHING_PROTOCOLS.
481 if (http_response_info_->headers &&
482 http_response_info_->headers->response_code() ==
483 HTTP_SWITCHING_PROTOCOLS) {
484 http_response_info_->headers->ReplaceStatusLine(
485 kConnectionErrorStatusLine);
Bence Békyde0be312018-03-13 17:51:58486 result_ = HandshakeResult::FAILED_SWITCHING_PROTOCOLS;
487 return rv;
ricea23c3f942015-02-02 13:35:13488 }
Bence Békyde0be312018-03-13 17:51:58489 result_ = HandshakeResult::FAILED;
[email protected]e5760f522014-02-05 12:28:50490 return rv;
[email protected]d51365e2013-11-27 10:46:52491 }
492}
493
494int WebSocketBasicHandshakeStream::ValidateUpgradeResponse(
[email protected]e5760f522014-02-05 12:28:50495 const HttpResponseHeaders* headers) {
Bence Béky65623972018-03-05 15:31:56496 extension_params_ = std::make_unique<WebSocketExtensionParams>();
[email protected]8aba0172014-07-03 12:09:53497 std::string failure_message;
Bence Békyde0be312018-03-13 17:51:58498 if (!ValidateUpgrade(headers, &failure_message)) {
499 result_ = HandshakeResult::FAILED_UPGRADE;
500 } else if (!ValidateSecWebSocketAccept(headers, handshake_challenge_response_,
501 &failure_message)) {
502 result_ = HandshakeResult::FAILED_ACCEPT;
503 } else if (!ValidateConnection(headers, &failure_message)) {
504 result_ = HandshakeResult::FAILED_CONNECTION;
505 } else if (!ValidateSubProtocol(headers, requested_sub_protocols_,
506 &sub_protocol_, &failure_message)) {
507 result_ = HandshakeResult::FAILED_SUBPROTO;
508 } else if (!ValidateExtensions(headers, &extensions_, &failure_message,
509 extension_params_.get())) {
510 result_ = HandshakeResult::FAILED_EXTENSIONS;
511 } else {
512 result_ = HandshakeResult::CONNECTED;
[email protected]d51365e2013-11-27 10:46:52513 return OK;
514 }
tyoshinoccfcfde2016-07-21 14:06:55515 OnFailure("Error during WebSocket handshake: " + failure_message);
[email protected]d51365e2013-11-27 10:46:52516 return ERR_INVALID_RESPONSE;
517}
518
tyoshinoccfcfde2016-07-21 14:06:55519void WebSocketBasicHandshakeStream::OnFailure(const std::string& message) {
Adam Riced4596a8e2018-07-13 08:06:17520 // Avoid connection reuse if auth did not happen.
521 state_.connection()->socket()->Disconnect();
tyoshinoccfcfde2016-07-21 14:06:55522 stream_request_->OnFailure(message);
[email protected]8aba0172014-07-03 12:09:53523}
524
[email protected]d51365e2013-11-27 10:46:52525} // namespace net