blob: b7c212bda2a3dac956174de5562220c93ed147d0 [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>
[email protected]96868202014-01-09 10:38:0411#include <string>
davidben1e912ea2016-04-20 19:17:0712#include <unordered_set>
dchengc7eeda422015-12-26 03:56:4813#include <utility>
[email protected]cd48ed12014-01-22 14:34:2214#include <vector>
[email protected]d51365e2013-11-27 10:46:5215
16#include "base/base64.h"
[email protected]d51365e2013-11-27 10:46:5217#include "base/bind.h"
yhirano27b2b572014-10-30 11:23:4418#include "base/compiler_specific.h"
[email protected]8aba0172014-07-03 12:09:5319#include "base/logging.h"
Ilya Sherman0eb39802017-12-08 20:58:1820#include "base/metrics/histogram_functions.h"
asvitkinec3c93722015-06-17 14:48:3721#include "base/metrics/histogram_macros.h"
[email protected]d51365e2013-11-27 10:46:5222#include "base/stl_util.h"
[email protected]0be93922014-01-29 00:42:4523#include "base/strings/string_number_conversions.h"
[email protected]69d7a492014-02-19 08:36:3224#include "base/strings/string_piece.h"
[email protected]d51365e2013-11-27 10:46:5225#include "base/strings/string_util.h"
[email protected]96868202014-01-09 10:38:0426#include "base/strings/stringprintf.h"
[email protected]cd48ed12014-01-22 14:34:2227#include "base/time/time.h"
[email protected]d51365e2013-11-27 10:46:5228#include "crypto/random.h"
halton.huo299e2002014-12-02 04:39:2429#include "net/base/io_buffer.h"
[email protected]d51365e2013-11-27 10:46:5230#include "net/http/http_request_headers.h"
31#include "net/http/http_request_info.h"
32#include "net/http/http_response_body_drainer.h"
33#include "net/http/http_response_headers.h"
34#include "net/http/http_status_code.h"
35#include "net/http/http_stream_parser.h"
36#include "net/socket/client_socket_handle.h"
[email protected]654866142014-06-24 22:53:3137#include "net/socket/websocket_transport_client_socket_pool.h"
[email protected]d51365e2013-11-27 10:46:5238#include "net/websockets/websocket_basic_stream.h"
Bence Béky7294fc22018-02-08 14:26:1739#include "net/websockets/websocket_basic_stream_adapters.h"
yhirano8387aee2015-09-14 05:46:4940#include "net/websockets/websocket_deflate_parameters.h"
[email protected]0be93922014-01-29 00:42:4541#include "net/websockets/websocket_deflate_predictor.h"
42#include "net/websockets/websocket_deflate_predictor_impl.h"
43#include "net/websockets/websocket_deflate_stream.h"
44#include "net/websockets/websocket_deflater.h"
[email protected]96868202014-01-09 10:38:0445#include "net/websockets/websocket_extension_parser.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]0be93922014-01-29 00:42:4560// TODO(ricea): If more extensions are added, replace this with a more general
61// mechanism.
62struct WebSocketExtensionParams {
yhirano8387aee2015-09-14 05:46:4963 bool deflate_enabled = false;
64 WebSocketDeflateParameters deflate_parameters;
[email protected]0be93922014-01-29 00:42:4565};
66
[email protected]d51365e2013-11-27 10:46:5267namespace {
68
[email protected]96868202014-01-09 10:38:0469enum GetHeaderResult {
70 GET_HEADER_OK,
71 GET_HEADER_MISSING,
72 GET_HEADER_MULTIPLE,
73};
74
75std::string MissingHeaderMessage(const std::string& header_name) {
76 return std::string("'") + header_name + "' header is missing";
77}
78
79std::string MultipleHeaderValuesMessage(const std::string& header_name) {
80 return
81 std::string("'") +
82 header_name +
83 "' header must not appear more than once in a response";
84}
85
[email protected]d51365e2013-11-27 10:46:5286std::string GenerateHandshakeChallenge() {
87 std::string raw_challenge(websockets::kRawChallengeLength, '\0');
skyostilb8f60ca2016-08-12 12:34:4388 crypto::RandBytes(base::string_as_array(&raw_challenge),
89 raw_challenge.length());
[email protected]d51365e2013-11-27 10:46:5290 std::string encoded_challenge;
[email protected]33fca122013-12-11 01:48:5091 base::Base64Encode(raw_challenge, &encoded_challenge);
[email protected]d51365e2013-11-27 10:46:5292 return encoded_challenge;
93}
94
95void AddVectorHeaderIfNonEmpty(const char* name,
96 const std::vector<std::string>& value,
97 HttpRequestHeaders* headers) {
98 if (value.empty())
99 return;
brettwd94a22142015-07-15 05:19:26100 headers->SetHeader(name, base::JoinString(value, ", "));
[email protected]d51365e2013-11-27 10:46:52101}
102
[email protected]96868202014-01-09 10:38:04103GetHeaderResult GetSingleHeaderValue(const HttpResponseHeaders* headers,
104 const base::StringPiece& name,
105 std::string* value) {
olli.raulaee489a52016-01-25 08:37:10106 size_t iter = 0;
[email protected]96868202014-01-09 10:38:04107 size_t num_values = 0;
108 std::string temp_value;
olli.raulaee489a52016-01-25 08:37:10109 while (headers->EnumerateHeader(&iter, name, &temp_value)) {
[email protected]96868202014-01-09 10:38:04110 if (++num_values > 1)
111 return GET_HEADER_MULTIPLE;
112 *value = temp_value;
[email protected]d51365e2013-11-27 10:46:52113 }
[email protected]96868202014-01-09 10:38:04114 return num_values > 0 ? GET_HEADER_OK : GET_HEADER_MISSING;
115}
116
117bool ValidateHeaderHasSingleValue(GetHeaderResult result,
118 const std::string& header_name,
119 std::string* failure_message) {
120 if (result == GET_HEADER_MISSING) {
121 *failure_message = MissingHeaderMessage(header_name);
122 return false;
123 }
124 if (result == GET_HEADER_MULTIPLE) {
125 *failure_message = MultipleHeaderValuesMessage(header_name);
126 return false;
127 }
128 DCHECK_EQ(result, GET_HEADER_OK);
129 return true;
130}
131
132bool ValidateUpgrade(const HttpResponseHeaders* headers,
133 std::string* failure_message) {
134 std::string value;
135 GetHeaderResult result =
136 GetSingleHeaderValue(headers, websockets::kUpgrade, &value);
137 if (!ValidateHeaderHasSingleValue(result,
138 websockets::kUpgrade,
139 failure_message)) {
140 return false;
141 }
142
brettwbc17d2c82015-06-09 22:39:08143 if (!base::LowerCaseEqualsASCII(value, websockets::kWebSocketLowercase)) {
[email protected]96868202014-01-09 10:38:04144 *failure_message =
145 "'Upgrade' header value is not 'WebSocket': " + value;
146 return false;
147 }
148 return true;
149}
150
151bool ValidateSecWebSocketAccept(const HttpResponseHeaders* headers,
152 const std::string& expected,
153 std::string* failure_message) {
154 std::string actual;
155 GetHeaderResult result =
156 GetSingleHeaderValue(headers, websockets::kSecWebSocketAccept, &actual);
157 if (!ValidateHeaderHasSingleValue(result,
158 websockets::kSecWebSocketAccept,
159 failure_message)) {
160 return false;
161 }
162
163 if (expected != actual) {
164 *failure_message = "Incorrect 'Sec-WebSocket-Accept' header value";
165 return false;
166 }
167 return true;
168}
169
170bool ValidateConnection(const HttpResponseHeaders* headers,
171 std::string* failure_message) {
172 // Connection header is permitted to contain other tokens.
173 if (!headers->HasHeader(HttpRequestHeaders::kConnection)) {
174 *failure_message = MissingHeaderMessage(HttpRequestHeaders::kConnection);
175 return false;
176 }
177 if (!headers->HasHeaderValue(HttpRequestHeaders::kConnection,
178 websockets::kUpgrade)) {
179 *failure_message = "'Connection' header value must contain 'Upgrade'";
180 return false;
181 }
182 return true;
[email protected]d51365e2013-11-27 10:46:52183}
184
185bool ValidateSubProtocol(
[email protected]96868202014-01-09 10:38:04186 const HttpResponseHeaders* headers,
[email protected]d51365e2013-11-27 10:46:52187 const std::vector<std::string>& requested_sub_protocols,
[email protected]96868202014-01-09 10:38:04188 std::string* sub_protocol,
189 std::string* failure_message) {
olli.raulaee489a52016-01-25 08:37:10190 size_t iter = 0;
[email protected]96868202014-01-09 10:38:04191 std::string value;
davidben1e912ea2016-04-20 19:17:07192 std::unordered_set<std::string> requested_set(requested_sub_protocols.begin(),
193 requested_sub_protocols.end());
[email protected]96868202014-01-09 10:38:04194 int count = 0;
195 bool has_multiple_protocols = false;
196 bool has_invalid_protocol = false;
[email protected]d51365e2013-11-27 10:46:52197
[email protected]96868202014-01-09 10:38:04198 while (!has_invalid_protocol || !has_multiple_protocols) {
199 std::string temp_value;
olli.raulaee489a52016-01-25 08:37:10200 if (!headers->EnumerateHeader(&iter, websockets::kSecWebSocketProtocol,
201 &temp_value))
[email protected]96868202014-01-09 10:38:04202 break;
203 value = temp_value;
204 if (requested_set.count(value) == 0)
205 has_invalid_protocol = true;
206 if (++count > 1)
207 has_multiple_protocols = true;
[email protected]d51365e2013-11-27 10:46:52208 }
[email protected]96868202014-01-09 10:38:04209
210 if (has_multiple_protocols) {
211 *failure_message =
212 MultipleHeaderValuesMessage(websockets::kSecWebSocketProtocol);
213 return false;
214 } else if (count > 0 && requested_sub_protocols.size() == 0) {
215 *failure_message =
216 std::string("Response must not include 'Sec-WebSocket-Protocol' "
217 "header if not present in request: ")
218 + value;
219 return false;
220 } else if (has_invalid_protocol) {
221 *failure_message =
222 "'Sec-WebSocket-Protocol' header value '" +
223 value +
224 "' in response does not match any of sent values";
225 return false;
226 } else if (requested_sub_protocols.size() > 0 && count == 0) {
227 *failure_message =
228 "Sent non-empty 'Sec-WebSocket-Protocol' header "
229 "but no response was received";
230 return false;
231 }
232 *sub_protocol = value;
233 return true;
[email protected]d51365e2013-11-27 10:46:52234}
235
[email protected]96868202014-01-09 10:38:04236bool ValidateExtensions(const HttpResponseHeaders* headers,
tyoshino38ee68c2015-04-01 05:52:52237 std::string* accepted_extensions_descriptor,
[email protected]0be93922014-01-29 00:42:45238 std::string* failure_message,
239 WebSocketExtensionParams* params) {
olli.raulaee489a52016-01-25 08:37:10240 size_t iter = 0;
tyoshino38ee68c2015-04-01 05:52:52241 std::string header_value;
242 std::vector<std::string> header_values;
[email protected]0be93922014-01-29 00:42:45243 // TODO(ricea): If adding support for additional extensions, generalise this
244 // code.
245 bool seen_permessage_deflate = false;
olli.raulaee489a52016-01-25 08:37:10246 while (headers->EnumerateHeader(&iter, websockets::kSecWebSocketExtensions,
tyoshino38ee68c2015-04-01 05:52:52247 &header_value)) {
[email protected]96868202014-01-09 10:38:04248 WebSocketExtensionParser parser;
tyoshinod90d2932015-04-13 16:53:32249 if (!parser.Parse(header_value)) {
[email protected]96868202014-01-09 10:38:04250 // TODO(yhirano) Set appropriate failure message.
251 *failure_message =
252 "'Sec-WebSocket-Extensions' header value is "
253 "rejected by the parser: " +
tyoshino38ee68c2015-04-01 05:52:52254 header_value;
[email protected]96868202014-01-09 10:38:04255 return false;
256 }
tyoshino38ee68c2015-04-01 05:52:52257
258 const std::vector<WebSocketExtension>& extensions = parser.extensions();
259 for (const auto& extension : extensions) {
260 if (extension.name() == "permessage-deflate") {
261 if (seen_permessage_deflate) {
262 *failure_message = "Received duplicate permessage-deflate response";
263 return false;
264 }
265 seen_permessage_deflate = true;
yhirano8387aee2015-09-14 05:46:49266 auto& deflate_parameters = params->deflate_parameters;
267 if (!deflate_parameters.Initialize(extension, failure_message) ||
268 !deflate_parameters.IsValidAsResponse(failure_message)) {
269 *failure_message = "Error in permessage-deflate: " + *failure_message;
tyoshino38ee68c2015-04-01 05:52:52270 return false;
271 }
yhirano8387aee2015-09-14 05:46:49272 // Note that we don't have to check the request-response compatibility
273 // here because we send a request compatible with any valid responses.
274 // TODO(yhirano): Place a DCHECK here.
275
tyoshino38ee68c2015-04-01 05:52:52276 header_values.push_back(header_value);
277 } else {
278 *failure_message = "Found an unsupported extension '" +
279 extension.name() +
280 "' in 'Sec-WebSocket-Extensions' header";
[email protected]0be93922014-01-29 00:42:45281 return false;
282 }
[email protected]0be93922014-01-29 00:42:45283 }
[email protected]d51365e2013-11-27 10:46:52284 }
brettwd94a22142015-07-15 05:19:26285 *accepted_extensions_descriptor = base::JoinString(header_values, ", ");
yhirano8387aee2015-09-14 05:46:49286 params->deflate_enabled = seen_permessage_deflate;
[email protected]d51365e2013-11-27 10:46:52287 return true;
288}
289
290} // namespace
291
292WebSocketBasicHandshakeStream::WebSocketBasicHandshakeStream(
danakj9c5cab52016-04-16 00:54:33293 std::unique_ptr<ClientSocketHandle> connection,
[email protected]cd48ed12014-01-22 14:34:22294 WebSocketStream::ConnectDelegate* connect_delegate,
[email protected]d51365e2013-11-27 10:46:52295 bool using_proxy,
296 std::vector<std::string> requested_sub_protocols,
[email protected]8aba0172014-07-03 12:09:53297 std::vector<std::string> requested_extensions,
tyoshinoccfcfde2016-07-21 14:06:55298 WebSocketStreamRequest* request)
mmenkea7da6da2016-09-01 21:56:52299 : state_(std::move(connection),
300 using_proxy,
301 false /* http_09_on_non_default_ports_enabled */),
[email protected]cd48ed12014-01-22 14:34:22302 connect_delegate_(connect_delegate),
yhiranoa7e05bb2014-11-06 05:40:39303 http_response_info_(nullptr),
[email protected]d51365e2013-11-27 10:46:52304 requested_sub_protocols_(requested_sub_protocols),
[email protected]8aba0172014-07-03 12:09:53305 requested_extensions_(requested_extensions),
tyoshinoccfcfde2016-07-21 14:06:55306 stream_request_(request) {
[email protected]8aba0172014-07-03 12:09:53307 DCHECK(connect_delegate);
tyoshinoccfcfde2016-07-21 14:06:55308 DCHECK(request);
[email protected]8aba0172014-07-03 12:09:53309}
[email protected]d51365e2013-11-27 10:46:52310
Chris Watkins28c2fdd2017-11-30 06:06:52311WebSocketBasicHandshakeStream::~WebSocketBasicHandshakeStream() = default;
[email protected]d51365e2013-11-27 10:46:52312
313int WebSocketBasicHandshakeStream::InitializeStream(
314 const HttpRequestInfo* request_info,
Steven Valdezb4ff0412018-01-18 22:39:27315 bool can_send_early,
[email protected]d51365e2013-11-27 10:46:52316 RequestPriority priority,
tfarina42834112016-09-22 13:38:20317 const NetLogWithSource& net_log,
Bence Békya25e3f72018-02-13 21:13:39318 CompletionOnceCallback callback) {
Ramin Halavati20e949f2018-02-14 20:14:32319 DCHECK(request_info->traffic_annotation.is_valid());
[email protected]cd48ed12014-01-22 14:34:22320 url_ = request_info->url;
Bence Békyd5d65a912018-02-11 04:28:00321 state_.Initialize(request_info, can_send_early, priority, net_log);
[email protected]d51365e2013-11-27 10:46:52322 return OK;
323}
324
325int WebSocketBasicHandshakeStream::SendRequest(
326 const HttpRequestHeaders& headers,
327 HttpResponseInfo* response,
Bence Békya25e3f72018-02-13 21:13:39328 CompletionOnceCallback callback) {
[email protected]d51365e2013-11-27 10:46:52329 DCHECK(!headers.HasHeader(websockets::kSecWebSocketKey));
330 DCHECK(!headers.HasHeader(websockets::kSecWebSocketProtocol));
331 DCHECK(!headers.HasHeader(websockets::kSecWebSocketExtensions));
332 DCHECK(headers.HasHeader(HttpRequestHeaders::kOrigin));
333 DCHECK(headers.HasHeader(websockets::kUpgrade));
334 DCHECK(headers.HasHeader(HttpRequestHeaders::kConnection));
335 DCHECK(headers.HasHeader(websockets::kSecWebSocketVersion));
336 DCHECK(parser());
337
338 http_response_info_ = response;
339
340 // Create a copy of the headers object, so that we can add the
341 // Sec-WebSockey-Key header.
342 HttpRequestHeaders enriched_headers;
343 enriched_headers.CopyFrom(headers);
[email protected]a31ecc02013-12-05 08:30:55344 std::string handshake_challenge;
345 if (handshake_challenge_for_testing_) {
346 handshake_challenge = *handshake_challenge_for_testing_;
347 handshake_challenge_for_testing_.reset();
348 } else {
349 handshake_challenge = GenerateHandshakeChallenge();
350 }
[email protected]d51365e2013-11-27 10:46:52351 enriched_headers.SetHeader(websockets::kSecWebSocketKey, handshake_challenge);
352
[email protected]d51365e2013-11-27 10:46:52353 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketExtensions,
354 requested_extensions_,
355 &enriched_headers);
[email protected]0be93922014-01-29 00:42:45356 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketProtocol,
357 requested_sub_protocols_,
358 &enriched_headers);
[email protected]d51365e2013-11-27 10:46:52359
ricea11bdcd02014-11-20 09:57:07360 handshake_challenge_response_ =
361 ComputeSecWebSocketAccept(handshake_challenge);
[email protected]d51365e2013-11-27 10:46:52362
[email protected]cd48ed12014-01-22 14:34:22363 DCHECK(connect_delegate_);
danakj9c5cab52016-04-16 00:54:33364 std::unique_ptr<WebSocketHandshakeRequestInfo> request(
[email protected]cd48ed12014-01-22 14:34:22365 new WebSocketHandshakeRequestInfo(url_, base::Time::Now()));
366 request->headers.CopyFrom(enriched_headers);
dchengc7eeda422015-12-26 03:56:48367 connect_delegate_->OnStartOpeningHandshake(std::move(request));
[email protected]cd48ed12014-01-22 14:34:22368
Ramin Halavati20e949f2018-02-14 20:14:32369 return parser()->SendRequest(
370 state_.GenerateRequestLine(), enriched_headers,
371 NetworkTrafficAnnotationTag(state_.traffic_annotation()), response,
372 std::move(callback));
[email protected]d51365e2013-11-27 10:46:52373}
374
375int WebSocketBasicHandshakeStream::ReadResponseHeaders(
Bence Békya25e3f72018-02-13 21:13:39376 CompletionOnceCallback callback) {
[email protected]d51365e2013-11-27 10:46:52377 // HttpStreamParser uses a weak pointer when reading from the
378 // socket, so it won't be called back after being destroyed. The
379 // HttpStreamParser is owned by HttpBasicState which is owned by this object,
380 // so this use of base::Unretained() is safe.
Bence Békya25e3f72018-02-13 21:13:39381 int rv = parser()->ReadResponseHeaders(base::BindOnce(
382 &WebSocketBasicHandshakeStream::ReadResponseHeadersCallback,
383 base::Unretained(this), std::move(callback)));
[email protected]cd48ed12014-01-22 14:34:22384 if (rv == ERR_IO_PENDING)
385 return rv;
ricea24c195f2015-02-26 12:18:55386 return ValidateResponse(rv);
[email protected]d51365e2013-11-27 10:46:52387}
388
[email protected]d51365e2013-11-27 10:46:52389int WebSocketBasicHandshakeStream::ReadResponseBody(
390 IOBuffer* buf,
391 int buf_len,
Bence Békya25e3f72018-02-13 21:13:39392 CompletionOnceCallback callback) {
393 return parser()->ReadResponseBody(buf, buf_len, std::move(callback));
[email protected]d51365e2013-11-27 10:46:52394}
395
396void WebSocketBasicHandshakeStream::Close(bool not_reusable) {
397 // This class ignores the value of |not_reusable| and never lets the socket be
398 // re-used.
399 if (parser())
400 parser()->Close(true);
401}
402
403bool WebSocketBasicHandshakeStream::IsResponseBodyComplete() const {
404 return parser()->IsResponseBodyComplete();
405}
406
[email protected]d51365e2013-11-27 10:46:52407bool WebSocketBasicHandshakeStream::IsConnectionReused() const {
408 return parser()->IsConnectionReused();
409}
410
411void WebSocketBasicHandshakeStream::SetConnectionReused() {
412 parser()->SetConnectionReused();
413}
414
mmenkebd84c392015-09-02 14:12:34415bool WebSocketBasicHandshakeStream::CanReuseConnection() const {
[email protected]d51365e2013-11-27 10:46:52416 return false;
417}
418
sclittle4de1bab92015-09-22 21:28:24419int64_t WebSocketBasicHandshakeStream::GetTotalReceivedBytes() const {
[email protected]bc92bc972013-12-13 08:32:59420 return 0;
421}
422
sclittlebe1ccf62015-09-02 19:40:36423int64_t WebSocketBasicHandshakeStream::GetTotalSentBytes() const {
424 return 0;
425}
426
rchcd379012017-04-12 21:53:32427bool WebSocketBasicHandshakeStream::GetAlternativeService(
428 AlternativeService* alternative_service) const {
429 return false;
430}
431
[email protected]d51365e2013-11-27 10:46:52432bool WebSocketBasicHandshakeStream::GetLoadTimingInfo(
433 LoadTimingInfo* load_timing_info) const {
434 return state_.connection()->GetLoadTimingInfo(IsConnectionReused(),
435 load_timing_info);
436}
437
438void WebSocketBasicHandshakeStream::GetSSLInfo(SSLInfo* ssl_info) {
439 parser()->GetSSLInfo(ssl_info);
440}
441
442void WebSocketBasicHandshakeStream::GetSSLCertRequestInfo(
443 SSLCertRequestInfo* cert_request_info) {
444 parser()->GetSSLCertRequestInfo(cert_request_info);
445}
446
ttuttled9dbc652015-09-29 20:00:59447bool WebSocketBasicHandshakeStream::GetRemoteEndpoint(IPEndPoint* endpoint) {
448 if (!state_.connection() || !state_.connection()->socket())
449 return false;
450
451 return state_.connection()->socket()->GetPeerAddress(endpoint) == OK;
452}
453
zhongyica364fbb2015-12-12 03:39:12454void WebSocketBasicHandshakeStream::PopulateNetErrorDetails(
455 NetErrorDetails* /*details*/) {
456 return;
457}
458
nharper78e6d2b2016-09-21 05:42:35459Error WebSocketBasicHandshakeStream::GetTokenBindingSignature(
nharperb7441ef2016-01-25 23:54:14460 crypto::ECPrivateKey* key,
nharper78e6d2b2016-09-21 05:42:35461 TokenBindingType tb_type,
nharperb7441ef2016-01-25 23:54:14462 std::vector<uint8_t>* out) {
463 NOTREACHED();
464 return ERR_NOT_IMPLEMENTED;
465}
466
[email protected]d51365e2013-11-27 10:46:52467void WebSocketBasicHandshakeStream::Drain(HttpNetworkSession* session) {
468 HttpResponseBodyDrainer* drainer = new HttpResponseBodyDrainer(this);
469 drainer->Start(session);
470 // |drainer| will delete itself.
471}
472
473void WebSocketBasicHandshakeStream::SetPriority(RequestPriority priority) {
474 // TODO(ricea): See TODO comment in HttpBasicStream::SetPriority(). If it is
475 // gone, then copy whatever has happened there over here.
476}
477
yhiranoa7e05bb2014-11-06 05:40:39478HttpStream* WebSocketBasicHandshakeStream::RenewStreamForAuth() {
479 // Return null because we don't support renewing the stream.
480 return nullptr;
481}
482
danakj9c5cab52016-04-16 00:54:33483std::unique_ptr<WebSocketStream> WebSocketBasicHandshakeStream::Upgrade() {
[email protected]d51365e2013-11-27 10:46:52484 // The HttpStreamParser object has a pointer to our ClientSocketHandle. Make
485 // sure it does not touch it again before it is destroyed.
486 state_.DeleteParser();
[email protected]654866142014-06-24 22:53:31487 WebSocketTransportClientSocketPool::UnlockEndpoint(state_.connection());
Bence Béky7294fc22018-02-08 14:26:17488 std::unique_ptr<WebSocketStream> basic_stream =
489 std::make_unique<WebSocketBasicStream>(
490 std::make_unique<WebSocketClientSocketHandleAdapter>(
491 state_.ReleaseConnection()),
492 state_.read_buf(), sub_protocol_, extensions_);
[email protected]0be93922014-01-29 00:42:45493 DCHECK(extension_params_.get());
494 if (extension_params_->deflate_enabled) {
[email protected]9c50b042014-04-28 06:40:15495 UMA_HISTOGRAM_ENUMERATION(
496 "Net.WebSocket.DeflateMode",
yhirano8387aee2015-09-14 05:46:49497 extension_params_->deflate_parameters.client_context_take_over_mode(),
[email protected]9c50b042014-04-28 06:40:15498 WebSocketDeflater::NUM_CONTEXT_TAKEOVER_MODE_TYPES);
499
danakj9c5cab52016-04-16 00:54:33500 return std::unique_ptr<WebSocketStream>(new WebSocketDeflateStream(
dchengc7eeda422015-12-26 03:56:48501 std::move(basic_stream), extension_params_->deflate_parameters,
danakj9c5cab52016-04-16 00:54:33502 std::unique_ptr<WebSocketDeflatePredictor>(
yhirano8387aee2015-09-14 05:46:49503 new WebSocketDeflatePredictorImpl)));
[email protected]0be93922014-01-29 00:42:45504 } else {
dchengc7eeda422015-12-26 03:56:48505 return basic_stream;
[email protected]0be93922014-01-29 00:42:45506 }
[email protected]d51365e2013-11-27 10:46:52507}
508
[email protected]a31ecc02013-12-05 08:30:55509void WebSocketBasicHandshakeStream::SetWebSocketKeyForTesting(
510 const std::string& key) {
511 handshake_challenge_for_testing_.reset(new std::string(key));
512}
513
[email protected]d51365e2013-11-27 10:46:52514void WebSocketBasicHandshakeStream::ReadResponseHeadersCallback(
Bence Békya25e3f72018-02-13 21:13:39515 CompletionOnceCallback callback,
[email protected]d51365e2013-11-27 10:46:52516 int result) {
Bence Békya25e3f72018-02-13 21:13:39517 std::move(callback).Run(ValidateResponse(result));
[email protected]d51365e2013-11-27 10:46:52518}
519
[email protected]cd48ed12014-01-22 14:34:22520void WebSocketBasicHandshakeStream::OnFinishOpeningHandshake() {
[email protected]cd48ed12014-01-22 14:34:22521 DCHECK(http_response_info_);
[email protected]e69c1cd2014-07-29 07:42:29522 WebSocketDispatchOnFinishOpeningHandshake(connect_delegate_,
523 url_,
524 http_response_info_->headers,
525 http_response_info_->response_time);
[email protected]cd48ed12014-01-22 14:34:22526}
527
ricea24c195f2015-02-26 12:18:55528int WebSocketBasicHandshakeStream::ValidateResponse(int rv) {
[email protected]d51365e2013-11-27 10:46:52529 DCHECK(http_response_info_);
[email protected]f7e98ca2014-06-19 12:05:43530 // Most net errors happen during connection, so they are not seen by this
531 // method. The histogram for error codes is created in
532 // Delegate::OnResponseStarted in websocket_stream.cc instead.
[email protected]e5760f522014-02-05 12:28:50533 if (rv >= 0) {
[email protected]f7e98ca2014-06-19 12:05:43534 const HttpResponseHeaders* headers = http_response_info_->headers.get();
535 const int response_code = headers->response_code();
Ilya Sherman0eb39802017-12-08 20:58:18536 base::UmaHistogramSparse("Net.WebSocket.ResponseCode", response_code);
[email protected]f7e98ca2014-06-19 12:05:43537 switch (response_code) {
[email protected]e5760f522014-02-05 12:28:50538 case HTTP_SWITCHING_PROTOCOLS:
539 OnFinishOpeningHandshake();
540 return ValidateUpgradeResponse(headers);
[email protected]d51365e2013-11-27 10:46:52541
[email protected]e5760f522014-02-05 12:28:50542 // We need to pass these through for authentication to work.
543 case HTTP_UNAUTHORIZED:
544 case HTTP_PROXY_AUTHENTICATION_REQUIRED:
545 return OK;
[email protected]d51365e2013-11-27 10:46:52546
[email protected]e5760f522014-02-05 12:28:50547 // Other status codes are potentially risky (see the warnings in the
548 // WHATWG WebSocket API spec) and so are dropped by default.
549 default:
[email protected]aeb640d2014-02-21 11:03:18550 // A WebSocket server cannot be using HTTP/0.9, so if we see version
551 // 0.9, it means the response was garbage.
552 // Reporting "Unexpected response code: 200" in this case is not
553 // helpful, so use a different error message.
554 if (headers->GetHttpVersion() == HttpVersion(0, 9)) {
tyoshinoccfcfde2016-07-21 14:06:55555 OnFailure("Error during WebSocket handshake: Invalid status line");
[email protected]aeb640d2014-02-21 11:03:18556 } else {
tyoshinoccfcfde2016-07-21 14:06:55557 OnFailure(base::StringPrintf(
[email protected]aeb640d2014-02-21 11:03:18558 "Error during WebSocket handshake: Unexpected response code: %d",
[email protected]8aba0172014-07-03 12:09:53559 headers->response_code()));
[email protected]aeb640d2014-02-21 11:03:18560 }
[email protected]e5760f522014-02-05 12:28:50561 OnFinishOpeningHandshake();
562 return ERR_INVALID_RESPONSE;
563 }
564 } else {
[email protected]3efc08f2014-02-07 09:33:34565 if (rv == ERR_EMPTY_RESPONSE) {
tyoshinoccfcfde2016-07-21 14:06:55566 OnFailure("Connection closed before receiving a handshake response");
[email protected]3efc08f2014-02-07 09:33:34567 return rv;
568 }
tyoshinoccfcfde2016-07-21 14:06:55569 OnFailure(std::string("Error during WebSocket handshake: ") +
570 ErrorToString(rv));
[email protected]e5760f522014-02-05 12:28:50571 OnFinishOpeningHandshake();
ricea23c3f942015-02-02 13:35:13572 // Some error codes (for example ERR_CONNECTION_CLOSED) get changed to OK at
573 // higher levels. To prevent an unvalidated connection getting erroneously
574 // upgraded, don't pass through the status code unchanged if it is
575 // HTTP_SWITCHING_PROTOCOLS.
576 if (http_response_info_->headers &&
577 http_response_info_->headers->response_code() ==
578 HTTP_SWITCHING_PROTOCOLS) {
579 http_response_info_->headers->ReplaceStatusLine(
580 kConnectionErrorStatusLine);
581 }
[email protected]e5760f522014-02-05 12:28:50582 return rv;
[email protected]d51365e2013-11-27 10:46:52583 }
584}
585
586int WebSocketBasicHandshakeStream::ValidateUpgradeResponse(
[email protected]e5760f522014-02-05 12:28:50587 const HttpResponseHeaders* headers) {
[email protected]0be93922014-01-29 00:42:45588 extension_params_.reset(new WebSocketExtensionParams);
[email protected]8aba0172014-07-03 12:09:53589 std::string failure_message;
590 if (ValidateUpgrade(headers, &failure_message) &&
591 ValidateSecWebSocketAccept(
592 headers, handshake_challenge_response_, &failure_message) &&
593 ValidateConnection(headers, &failure_message) &&
[email protected]e5760f522014-02-05 12:28:50594 ValidateSubProtocol(headers,
[email protected]96868202014-01-09 10:38:04595 requested_sub_protocols_,
596 &sub_protocol_,
[email protected]8aba0172014-07-03 12:09:53597 &failure_message) &&
[email protected]e5760f522014-02-05 12:28:50598 ValidateExtensions(headers,
[email protected]96868202014-01-09 10:38:04599 &extensions_,
[email protected]8aba0172014-07-03 12:09:53600 &failure_message,
[email protected]0be93922014-01-29 00:42:45601 extension_params_.get())) {
[email protected]d51365e2013-11-27 10:46:52602 return OK;
603 }
tyoshinoccfcfde2016-07-21 14:06:55604 OnFailure("Error during WebSocket handshake: " + failure_message);
[email protected]d51365e2013-11-27 10:46:52605 return ERR_INVALID_RESPONSE;
606}
607
tyoshinoccfcfde2016-07-21 14:06:55608void WebSocketBasicHandshakeStream::OnFailure(const std::string& message) {
609 stream_request_->OnFailure(message);
[email protected]8aba0172014-07-03 12:09:53610}
611
[email protected]d51365e2013-11-27 10:46:52612} // namespace net