blob: 1d4bf4337eff44f9ea1ebc99c50a1c6d4c0730b7 [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{
Adam Rice6612adc2018-10-16 18:08:47164 "WebSocketHandshakeReuseConnection", base::FEATURE_ENABLED_BY_DEFAULT};
Adam Ricec786ad8a2018-05-22 09:49:15165
[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,
tfarina428341112016-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
[email protected]d51365e2013-11-27 10:46:52347void WebSocketBasicHandshakeStream::Drain(HttpNetworkSession* session) {
348 HttpResponseBodyDrainer* drainer = new HttpResponseBodyDrainer(this);
349 drainer->Start(session);
350 // |drainer| will delete itself.
351}
352
353void WebSocketBasicHandshakeStream::SetPriority(RequestPriority priority) {
354 // TODO(ricea): See TODO comment in HttpBasicStream::SetPriority(). If it is
355 // gone, then copy whatever has happened there over here.
356}
357
yhiranoa7e05bb2014-11-06 05:40:39358HttpStream* WebSocketBasicHandshakeStream::RenewStreamForAuth() {
Adam Rice8b382c602018-06-04 12:36:39359 if (!base::FeatureList::IsEnabled(kWebSocketHandshakeReuseConnection))
360 return nullptr;
361
362 DCHECK(IsResponseBodyComplete());
363 DCHECK(!parser()->IsMoreDataBuffered());
364 // The HttpStreamParser object still has a pointer to the connection. Just to
365 // be extra-sure it doesn't touch the connection again, delete it here rather
366 // than leaving it until the destructor is called.
367 state_.DeleteParser();
368
369 auto handshake_stream = std::make_unique<WebSocketBasicHandshakeStream>(
370 state_.ReleaseConnection(), connect_delegate_, state_.using_proxy(),
371 std::move(requested_sub_protocols_), std::move(requested_extensions_),
372 stream_request_, websocket_endpoint_lock_manager_);
373
374 stream_request_->OnBasicHandshakeStreamCreated(handshake_stream.get());
375
376 return handshake_stream.release();
yhiranoa7e05bb2014-11-06 05:40:39377}
378
danakj9c5cab52016-04-16 00:54:33379std::unique_ptr<WebSocketStream> WebSocketBasicHandshakeStream::Upgrade() {
[email protected]d51365e2013-11-27 10:46:52380 // The HttpStreamParser object has a pointer to our ClientSocketHandle. Make
381 // sure it does not touch it again before it is destroyed.
382 state_.DeleteParser();
Bence Békyda280c62018-04-12 15:08:37383 WebSocketTransportClientSocketPool::UnlockEndpoint(
384 state_.connection(), websocket_endpoint_lock_manager_);
Bence Béky7294fc22018-02-08 14:26:17385 std::unique_ptr<WebSocketStream> basic_stream =
386 std::make_unique<WebSocketBasicStream>(
387 std::make_unique<WebSocketClientSocketHandleAdapter>(
388 state_.ReleaseConnection()),
389 state_.read_buf(), sub_protocol_, extensions_);
[email protected]0be93922014-01-29 00:42:45390 DCHECK(extension_params_.get());
391 if (extension_params_->deflate_enabled) {
Bence Békyde0be312018-03-13 17:51:58392 RecordDeflateMode(
393 extension_params_->deflate_parameters.client_context_take_over_mode());
[email protected]9c50b042014-04-28 06:40:15394
Bence Béky65623972018-03-05 15:31:56395 return std::make_unique<WebSocketDeflateStream>(
dchengc7eeda422015-12-26 03:56:48396 std::move(basic_stream), extension_params_->deflate_parameters,
Bence Béky65623972018-03-05 15:31:56397 std::make_unique<WebSocketDeflatePredictorImpl>());
[email protected]0be93922014-01-29 00:42:45398 } else {
dchengc7eeda422015-12-26 03:56:48399 return basic_stream;
[email protected]0be93922014-01-29 00:42:45400 }
[email protected]d51365e2013-11-27 10:46:52401}
402
[email protected]a31ecc02013-12-05 08:30:55403void WebSocketBasicHandshakeStream::SetWebSocketKeyForTesting(
404 const std::string& key) {
Bence Béky7d0c74d2018-03-05 08:31:09405 handshake_challenge_for_testing_ = key;
[email protected]a31ecc02013-12-05 08:30:55406}
407
[email protected]d51365e2013-11-27 10:46:52408void WebSocketBasicHandshakeStream::ReadResponseHeadersCallback(
Bence Békya25e3f72018-02-13 21:13:39409 CompletionOnceCallback callback,
[email protected]d51365e2013-11-27 10:46:52410 int result) {
Bence Békya25e3f72018-02-13 21:13:39411 std::move(callback).Run(ValidateResponse(result));
[email protected]d51365e2013-11-27 10:46:52412}
413
[email protected]cd48ed12014-01-22 14:34:22414void WebSocketBasicHandshakeStream::OnFinishOpeningHandshake() {
[email protected]cd48ed12014-01-22 14:34:22415 DCHECK(http_response_info_);
Yutaka Hirano36c94952018-05-30 21:33:33416 WebSocketDispatchOnFinishOpeningHandshake(
417 connect_delegate_, url_, http_response_info_->headers,
418 http_response_info_->socket_address, http_response_info_->response_time);
[email protected]cd48ed12014-01-22 14:34:22419}
420
ricea24c195f2015-02-26 12:18:55421int WebSocketBasicHandshakeStream::ValidateResponse(int rv) {
[email protected]d51365e2013-11-27 10:46:52422 DCHECK(http_response_info_);
[email protected]f7e98ca2014-06-19 12:05:43423 // Most net errors happen during connection, so they are not seen by this
424 // method. The histogram for error codes is created in
425 // Delegate::OnResponseStarted in websocket_stream.cc instead.
[email protected]e5760f522014-02-05 12:28:50426 if (rv >= 0) {
[email protected]f7e98ca2014-06-19 12:05:43427 const HttpResponseHeaders* headers = http_response_info_->headers.get();
428 const int response_code = headers->response_code();
Ilya Sherman0eb39802017-12-08 20:58:18429 base::UmaHistogramSparse("Net.WebSocket.ResponseCode", response_code);
[email protected]f7e98ca2014-06-19 12:05:43430 switch (response_code) {
[email protected]e5760f522014-02-05 12:28:50431 case HTTP_SWITCHING_PROTOCOLS:
432 OnFinishOpeningHandshake();
433 return ValidateUpgradeResponse(headers);
[email protected]d51365e2013-11-27 10:46:52434
[email protected]e5760f522014-02-05 12:28:50435 // We need to pass these through for authentication to work.
436 case HTTP_UNAUTHORIZED:
437 case HTTP_PROXY_AUTHENTICATION_REQUIRED:
438 return OK;
[email protected]d51365e2013-11-27 10:46:52439
[email protected]e5760f522014-02-05 12:28:50440 // Other status codes are potentially risky (see the warnings in the
441 // WHATWG WebSocket API spec) and so are dropped by default.
442 default:
[email protected]aeb640d2014-02-21 11:03:18443 // A WebSocket server cannot be using HTTP/0.9, so if we see version
444 // 0.9, it means the response was garbage.
445 // Reporting "Unexpected response code: 200" in this case is not
446 // helpful, so use a different error message.
447 if (headers->GetHttpVersion() == HttpVersion(0, 9)) {
tyoshinoccfcfde2016-07-21 14:06:55448 OnFailure("Error during WebSocket handshake: Invalid status line");
[email protected]aeb640d2014-02-21 11:03:18449 } else {
tyoshinoccfcfde2016-07-21 14:06:55450 OnFailure(base::StringPrintf(
[email protected]aeb640d2014-02-21 11:03:18451 "Error during WebSocket handshake: Unexpected response code: %d",
[email protected]8aba0172014-07-03 12:09:53452 headers->response_code()));
[email protected]aeb640d2014-02-21 11:03:18453 }
[email protected]e5760f522014-02-05 12:28:50454 OnFinishOpeningHandshake();
Bence Békyde0be312018-03-13 17:51:58455 result_ = HandshakeResult::INVALID_STATUS;
[email protected]e5760f522014-02-05 12:28:50456 return ERR_INVALID_RESPONSE;
457 }
458 } else {
[email protected]3efc08f2014-02-07 09:33:34459 if (rv == ERR_EMPTY_RESPONSE) {
tyoshinoccfcfde2016-07-21 14:06:55460 OnFailure("Connection closed before receiving a handshake response");
Bence Békyde0be312018-03-13 17:51:58461 result_ = HandshakeResult::EMPTY_RESPONSE;
[email protected]3efc08f2014-02-07 09:33:34462 return rv;
463 }
tyoshinoccfcfde2016-07-21 14:06:55464 OnFailure(std::string("Error during WebSocket handshake: ") +
465 ErrorToString(rv));
[email protected]e5760f522014-02-05 12:28:50466 OnFinishOpeningHandshake();
ricea23c3f942015-02-02 13:35:13467 // Some error codes (for example ERR_CONNECTION_CLOSED) get changed to OK at
468 // higher levels. To prevent an unvalidated connection getting erroneously
469 // upgraded, don't pass through the status code unchanged if it is
470 // HTTP_SWITCHING_PROTOCOLS.
471 if (http_response_info_->headers &&
472 http_response_info_->headers->response_code() ==
473 HTTP_SWITCHING_PROTOCOLS) {
474 http_response_info_->headers->ReplaceStatusLine(
475 kConnectionErrorStatusLine);
Bence Békyde0be312018-03-13 17:51:58476 result_ = HandshakeResult::FAILED_SWITCHING_PROTOCOLS;
477 return rv;
ricea23c3f942015-02-02 13:35:13478 }
Bence Békyde0be312018-03-13 17:51:58479 result_ = HandshakeResult::FAILED;
[email protected]e5760f522014-02-05 12:28:50480 return rv;
[email protected]d51365e2013-11-27 10:46:52481 }
482}
483
484int WebSocketBasicHandshakeStream::ValidateUpgradeResponse(
[email protected]e5760f522014-02-05 12:28:50485 const HttpResponseHeaders* headers) {
Bence Béky65623972018-03-05 15:31:56486 extension_params_ = std::make_unique<WebSocketExtensionParams>();
[email protected]8aba0172014-07-03 12:09:53487 std::string failure_message;
Bence Békyde0be312018-03-13 17:51:58488 if (!ValidateUpgrade(headers, &failure_message)) {
489 result_ = HandshakeResult::FAILED_UPGRADE;
490 } else if (!ValidateSecWebSocketAccept(headers, handshake_challenge_response_,
491 &failure_message)) {
492 result_ = HandshakeResult::FAILED_ACCEPT;
493 } else if (!ValidateConnection(headers, &failure_message)) {
494 result_ = HandshakeResult::FAILED_CONNECTION;
495 } else if (!ValidateSubProtocol(headers, requested_sub_protocols_,
496 &sub_protocol_, &failure_message)) {
497 result_ = HandshakeResult::FAILED_SUBPROTO;
498 } else if (!ValidateExtensions(headers, &extensions_, &failure_message,
499 extension_params_.get())) {
500 result_ = HandshakeResult::FAILED_EXTENSIONS;
501 } else {
502 result_ = HandshakeResult::CONNECTED;
[email protected]d51365e2013-11-27 10:46:52503 return OK;
504 }
tyoshinoccfcfde2016-07-21 14:06:55505 OnFailure("Error during WebSocket handshake: " + failure_message);
[email protected]d51365e2013-11-27 10:46:52506 return ERR_INVALID_RESPONSE;
507}
508
tyoshinoccfcfde2016-07-21 14:06:55509void WebSocketBasicHandshakeStream::OnFailure(const std::string& message) {
Adam Riced4596a8e2018-07-13 08:06:17510 // Avoid connection reuse if auth did not happen.
511 state_.connection()->socket()->Disconnect();
tyoshinoccfcfde2016-07-21 14:06:55512 stream_request_->OnFailure(message);
[email protected]8aba0172014-07-03 12:09:53513}
514
[email protected]d51365e2013-11-27 10:46:52515} // namespace net