blob: c67eb4a838c236d2d4a651cd31ab5087ce73cd73 [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"
asvitkinec3c93722015-06-17 14:48:3720#include "base/metrics/histogram_macros.h"
[email protected]f7e98ca2014-06-19 12:05:4321#include "base/metrics/sparse_histogram.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"
yhirano8387aee2015-09-14 05:46:4939#include "net/websockets/websocket_deflate_parameters.h"
[email protected]0be93922014-01-29 00:42:4540#include "net/websockets/websocket_deflate_predictor.h"
41#include "net/websockets/websocket_deflate_predictor_impl.h"
42#include "net/websockets/websocket_deflate_stream.h"
43#include "net/websockets/websocket_deflater.h"
[email protected]96868202014-01-09 10:38:0444#include "net/websockets/websocket_extension_parser.h"
ricea11bdcd02014-11-20 09:57:0745#include "net/websockets/websocket_handshake_challenge.h"
[email protected]d51365e2013-11-27 10:46:5246#include "net/websockets/websocket_handshake_constants.h"
[email protected]cd48ed12014-01-22 14:34:2247#include "net/websockets/websocket_handshake_request_info.h"
48#include "net/websockets/websocket_handshake_response_info.h"
[email protected]d51365e2013-11-27 10:46:5249#include "net/websockets/websocket_stream.h"
50
51namespace net {
[email protected]0be93922014-01-29 00:42:4552
yhirano27b2b572014-10-30 11:23:4453namespace {
54
ricea23c3f942015-02-02 13:35:1355const char kConnectionErrorStatusLine[] = "HTTP/1.1 503 Connection Error";
56
yhirano27b2b572014-10-30 11:23:4457} // namespace
58
[email protected]0be93922014-01-29 00:42:4559// TODO(ricea): If more extensions are added, replace this with a more general
60// mechanism.
61struct WebSocketExtensionParams {
yhirano8387aee2015-09-14 05:46:4962 bool deflate_enabled = false;
63 WebSocketDeflateParameters deflate_parameters;
[email protected]0be93922014-01-29 00:42:4564};
65
[email protected]d51365e2013-11-27 10:46:5266namespace {
67
[email protected]96868202014-01-09 10:38:0468enum GetHeaderResult {
69 GET_HEADER_OK,
70 GET_HEADER_MISSING,
71 GET_HEADER_MULTIPLE,
72};
73
74std::string MissingHeaderMessage(const std::string& header_name) {
75 return std::string("'") + header_name + "' header is missing";
76}
77
78std::string MultipleHeaderValuesMessage(const std::string& header_name) {
79 return
80 std::string("'") +
81 header_name +
82 "' header must not appear more than once in a response";
83}
84
[email protected]d51365e2013-11-27 10:46:5285std::string GenerateHandshakeChallenge() {
86 std::string raw_challenge(websockets::kRawChallengeLength, '\0');
skyostilb8f60ca2016-08-12 12:34:4387 crypto::RandBytes(base::string_as_array(&raw_challenge),
88 raw_challenge.length());
[email protected]d51365e2013-11-27 10:46:5289 std::string encoded_challenge;
[email protected]33fca122013-12-11 01:48:5090 base::Base64Encode(raw_challenge, &encoded_challenge);
[email protected]d51365e2013-11-27 10:46:5291 return encoded_challenge;
92}
93
94void AddVectorHeaderIfNonEmpty(const char* name,
95 const std::vector<std::string>& value,
96 HttpRequestHeaders* headers) {
97 if (value.empty())
98 return;
brettwd94a22142015-07-15 05:19:2699 headers->SetHeader(name, base::JoinString(value, ", "));
[email protected]d51365e2013-11-27 10:46:52100}
101
[email protected]96868202014-01-09 10:38:04102GetHeaderResult GetSingleHeaderValue(const HttpResponseHeaders* headers,
103 const base::StringPiece& name,
104 std::string* value) {
olli.raulaee489a52016-01-25 08:37:10105 size_t iter = 0;
[email protected]96868202014-01-09 10:38:04106 size_t num_values = 0;
107 std::string temp_value;
olli.raulaee489a52016-01-25 08:37:10108 while (headers->EnumerateHeader(&iter, name, &temp_value)) {
[email protected]96868202014-01-09 10:38:04109 if (++num_values > 1)
110 return GET_HEADER_MULTIPLE;
111 *value = temp_value;
[email protected]d51365e2013-11-27 10:46:52112 }
[email protected]96868202014-01-09 10:38:04113 return num_values > 0 ? GET_HEADER_OK : GET_HEADER_MISSING;
114}
115
116bool ValidateHeaderHasSingleValue(GetHeaderResult result,
117 const std::string& header_name,
118 std::string* failure_message) {
119 if (result == GET_HEADER_MISSING) {
120 *failure_message = MissingHeaderMessage(header_name);
121 return false;
122 }
123 if (result == GET_HEADER_MULTIPLE) {
124 *failure_message = MultipleHeaderValuesMessage(header_name);
125 return false;
126 }
127 DCHECK_EQ(result, GET_HEADER_OK);
128 return true;
129}
130
131bool ValidateUpgrade(const HttpResponseHeaders* headers,
132 std::string* failure_message) {
133 std::string value;
134 GetHeaderResult result =
135 GetSingleHeaderValue(headers, websockets::kUpgrade, &value);
136 if (!ValidateHeaderHasSingleValue(result,
137 websockets::kUpgrade,
138 failure_message)) {
139 return false;
140 }
141
brettwbc17d2c82015-06-09 22:39:08142 if (!base::LowerCaseEqualsASCII(value, websockets::kWebSocketLowercase)) {
[email protected]96868202014-01-09 10:38:04143 *failure_message =
144 "'Upgrade' header value is not 'WebSocket': " + value;
145 return false;
146 }
147 return true;
148}
149
150bool ValidateSecWebSocketAccept(const HttpResponseHeaders* headers,
151 const std::string& expected,
152 std::string* failure_message) {
153 std::string actual;
154 GetHeaderResult result =
155 GetSingleHeaderValue(headers, websockets::kSecWebSocketAccept, &actual);
156 if (!ValidateHeaderHasSingleValue(result,
157 websockets::kSecWebSocketAccept,
158 failure_message)) {
159 return false;
160 }
161
162 if (expected != actual) {
163 *failure_message = "Incorrect 'Sec-WebSocket-Accept' header value";
164 return false;
165 }
166 return true;
167}
168
169bool ValidateConnection(const HttpResponseHeaders* headers,
170 std::string* failure_message) {
171 // Connection header is permitted to contain other tokens.
172 if (!headers->HasHeader(HttpRequestHeaders::kConnection)) {
173 *failure_message = MissingHeaderMessage(HttpRequestHeaders::kConnection);
174 return false;
175 }
176 if (!headers->HasHeaderValue(HttpRequestHeaders::kConnection,
177 websockets::kUpgrade)) {
178 *failure_message = "'Connection' header value must contain 'Upgrade'";
179 return false;
180 }
181 return true;
[email protected]d51365e2013-11-27 10:46:52182}
183
184bool ValidateSubProtocol(
[email protected]96868202014-01-09 10:38:04185 const HttpResponseHeaders* headers,
[email protected]d51365e2013-11-27 10:46:52186 const std::vector<std::string>& requested_sub_protocols,
[email protected]96868202014-01-09 10:38:04187 std::string* sub_protocol,
188 std::string* failure_message) {
olli.raulaee489a52016-01-25 08:37:10189 size_t iter = 0;
[email protected]96868202014-01-09 10:38:04190 std::string value;
davidben1e912ea2016-04-20 19:17:07191 std::unordered_set<std::string> requested_set(requested_sub_protocols.begin(),
192 requested_sub_protocols.end());
[email protected]96868202014-01-09 10:38:04193 int count = 0;
194 bool has_multiple_protocols = false;
195 bool has_invalid_protocol = false;
[email protected]d51365e2013-11-27 10:46:52196
[email protected]96868202014-01-09 10:38:04197 while (!has_invalid_protocol || !has_multiple_protocols) {
198 std::string temp_value;
olli.raulaee489a52016-01-25 08:37:10199 if (!headers->EnumerateHeader(&iter, websockets::kSecWebSocketProtocol,
200 &temp_value))
[email protected]96868202014-01-09 10:38:04201 break;
202 value = temp_value;
203 if (requested_set.count(value) == 0)
204 has_invalid_protocol = true;
205 if (++count > 1)
206 has_multiple_protocols = true;
[email protected]d51365e2013-11-27 10:46:52207 }
[email protected]96868202014-01-09 10:38:04208
209 if (has_multiple_protocols) {
210 *failure_message =
211 MultipleHeaderValuesMessage(websockets::kSecWebSocketProtocol);
212 return false;
213 } else if (count > 0 && requested_sub_protocols.size() == 0) {
214 *failure_message =
215 std::string("Response must not include 'Sec-WebSocket-Protocol' "
216 "header if not present in request: ")
217 + value;
218 return false;
219 } else if (has_invalid_protocol) {
220 *failure_message =
221 "'Sec-WebSocket-Protocol' header value '" +
222 value +
223 "' in response does not match any of sent values";
224 return false;
225 } else if (requested_sub_protocols.size() > 0 && count == 0) {
226 *failure_message =
227 "Sent non-empty 'Sec-WebSocket-Protocol' header "
228 "but no response was received";
229 return false;
230 }
231 *sub_protocol = value;
232 return true;
[email protected]d51365e2013-11-27 10:46:52233}
234
[email protected]96868202014-01-09 10:38:04235bool ValidateExtensions(const HttpResponseHeaders* headers,
tyoshino38ee68c2015-04-01 05:52:52236 std::string* accepted_extensions_descriptor,
[email protected]0be93922014-01-29 00:42:45237 std::string* failure_message,
238 WebSocketExtensionParams* params) {
olli.raulaee489a52016-01-25 08:37:10239 size_t iter = 0;
tyoshino38ee68c2015-04-01 05:52:52240 std::string header_value;
241 std::vector<std::string> header_values;
[email protected]0be93922014-01-29 00:42:45242 // TODO(ricea): If adding support for additional extensions, generalise this
243 // code.
244 bool seen_permessage_deflate = false;
olli.raulaee489a52016-01-25 08:37:10245 while (headers->EnumerateHeader(&iter, websockets::kSecWebSocketExtensions,
tyoshino38ee68c2015-04-01 05:52:52246 &header_value)) {
[email protected]96868202014-01-09 10:38:04247 WebSocketExtensionParser parser;
tyoshinod90d2932015-04-13 16:53:32248 if (!parser.Parse(header_value)) {
[email protected]96868202014-01-09 10:38:04249 // TODO(yhirano) Set appropriate failure message.
250 *failure_message =
251 "'Sec-WebSocket-Extensions' header value is "
252 "rejected by the parser: " +
tyoshino38ee68c2015-04-01 05:52:52253 header_value;
[email protected]96868202014-01-09 10:38:04254 return false;
255 }
tyoshino38ee68c2015-04-01 05:52:52256
257 const std::vector<WebSocketExtension>& extensions = parser.extensions();
258 for (const auto& extension : extensions) {
259 if (extension.name() == "permessage-deflate") {
260 if (seen_permessage_deflate) {
261 *failure_message = "Received duplicate permessage-deflate response";
262 return false;
263 }
264 seen_permessage_deflate = true;
yhirano8387aee2015-09-14 05:46:49265 auto& deflate_parameters = params->deflate_parameters;
266 if (!deflate_parameters.Initialize(extension, failure_message) ||
267 !deflate_parameters.IsValidAsResponse(failure_message)) {
268 *failure_message = "Error in permessage-deflate: " + *failure_message;
tyoshino38ee68c2015-04-01 05:52:52269 return false;
270 }
yhirano8387aee2015-09-14 05:46:49271 // Note that we don't have to check the request-response compatibility
272 // here because we send a request compatible with any valid responses.
273 // TODO(yhirano): Place a DCHECK here.
274
tyoshino38ee68c2015-04-01 05:52:52275 header_values.push_back(header_value);
276 } else {
277 *failure_message = "Found an unsupported extension '" +
278 extension.name() +
279 "' in 'Sec-WebSocket-Extensions' header";
[email protected]0be93922014-01-29 00:42:45280 return false;
281 }
[email protected]0be93922014-01-29 00:42:45282 }
[email protected]d51365e2013-11-27 10:46:52283 }
brettwd94a22142015-07-15 05:19:26284 *accepted_extensions_descriptor = base::JoinString(header_values, ", ");
yhirano8387aee2015-09-14 05:46:49285 params->deflate_enabled = seen_permessage_deflate;
[email protected]d51365e2013-11-27 10:46:52286 return true;
287}
288
289} // namespace
290
291WebSocketBasicHandshakeStream::WebSocketBasicHandshakeStream(
danakj9c5cab52016-04-16 00:54:33292 std::unique_ptr<ClientSocketHandle> connection,
[email protected]cd48ed12014-01-22 14:34:22293 WebSocketStream::ConnectDelegate* connect_delegate,
[email protected]d51365e2013-11-27 10:46:52294 bool using_proxy,
295 std::vector<std::string> requested_sub_protocols,
[email protected]8aba0172014-07-03 12:09:53296 std::vector<std::string> requested_extensions,
tyoshinoccfcfde2016-07-21 14:06:55297 WebSocketStreamRequest* request)
mmenkea7da6da2016-09-01 21:56:52298 : state_(std::move(connection),
299 using_proxy,
300 false /* http_09_on_non_default_ports_enabled */),
[email protected]cd48ed12014-01-22 14:34:22301 connect_delegate_(connect_delegate),
yhiranoa7e05bb2014-11-06 05:40:39302 http_response_info_(nullptr),
[email protected]d51365e2013-11-27 10:46:52303 requested_sub_protocols_(requested_sub_protocols),
[email protected]8aba0172014-07-03 12:09:53304 requested_extensions_(requested_extensions),
tyoshinoccfcfde2016-07-21 14:06:55305 stream_request_(request) {
[email protected]8aba0172014-07-03 12:09:53306 DCHECK(connect_delegate);
tyoshinoccfcfde2016-07-21 14:06:55307 DCHECK(request);
[email protected]8aba0172014-07-03 12:09:53308}
[email protected]d51365e2013-11-27 10:46:52309
310WebSocketBasicHandshakeStream::~WebSocketBasicHandshakeStream() {}
311
312int WebSocketBasicHandshakeStream::InitializeStream(
313 const HttpRequestInfo* request_info,
314 RequestPriority priority,
tfarina42834112016-09-22 13:38:20315 const NetLogWithSource& net_log,
[email protected]d51365e2013-11-27 10:46:52316 const CompletionCallback& callback) {
[email protected]cd48ed12014-01-22 14:34:22317 url_ = request_info->url;
[email protected]d51365e2013-11-27 10:46:52318 state_.Initialize(request_info, priority, net_log, callback);
319 return OK;
320}
321
322int WebSocketBasicHandshakeStream::SendRequest(
323 const HttpRequestHeaders& headers,
324 HttpResponseInfo* response,
325 const CompletionCallback& callback) {
326 DCHECK(!headers.HasHeader(websockets::kSecWebSocketKey));
327 DCHECK(!headers.HasHeader(websockets::kSecWebSocketProtocol));
328 DCHECK(!headers.HasHeader(websockets::kSecWebSocketExtensions));
329 DCHECK(headers.HasHeader(HttpRequestHeaders::kOrigin));
330 DCHECK(headers.HasHeader(websockets::kUpgrade));
331 DCHECK(headers.HasHeader(HttpRequestHeaders::kConnection));
332 DCHECK(headers.HasHeader(websockets::kSecWebSocketVersion));
333 DCHECK(parser());
334
335 http_response_info_ = response;
336
337 // Create a copy of the headers object, so that we can add the
338 // Sec-WebSockey-Key header.
339 HttpRequestHeaders enriched_headers;
340 enriched_headers.CopyFrom(headers);
[email protected]a31ecc02013-12-05 08:30:55341 std::string handshake_challenge;
342 if (handshake_challenge_for_testing_) {
343 handshake_challenge = *handshake_challenge_for_testing_;
344 handshake_challenge_for_testing_.reset();
345 } else {
346 handshake_challenge = GenerateHandshakeChallenge();
347 }
[email protected]d51365e2013-11-27 10:46:52348 enriched_headers.SetHeader(websockets::kSecWebSocketKey, handshake_challenge);
349
[email protected]d51365e2013-11-27 10:46:52350 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketExtensions,
351 requested_extensions_,
352 &enriched_headers);
[email protected]0be93922014-01-29 00:42:45353 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketProtocol,
354 requested_sub_protocols_,
355 &enriched_headers);
[email protected]d51365e2013-11-27 10:46:52356
ricea11bdcd02014-11-20 09:57:07357 handshake_challenge_response_ =
358 ComputeSecWebSocketAccept(handshake_challenge);
[email protected]d51365e2013-11-27 10:46:52359
[email protected]cd48ed12014-01-22 14:34:22360 DCHECK(connect_delegate_);
danakj9c5cab52016-04-16 00:54:33361 std::unique_ptr<WebSocketHandshakeRequestInfo> request(
[email protected]cd48ed12014-01-22 14:34:22362 new WebSocketHandshakeRequestInfo(url_, base::Time::Now()));
363 request->headers.CopyFrom(enriched_headers);
dchengc7eeda422015-12-26 03:56:48364 connect_delegate_->OnStartOpeningHandshake(std::move(request));
[email protected]cd48ed12014-01-22 14:34:22365
[email protected]d51365e2013-11-27 10:46:52366 return parser()->SendRequest(
367 state_.GenerateRequestLine(), enriched_headers, response, callback);
368}
369
370int WebSocketBasicHandshakeStream::ReadResponseHeaders(
371 const CompletionCallback& callback) {
372 // HttpStreamParser uses a weak pointer when reading from the
373 // socket, so it won't be called back after being destroyed. The
374 // HttpStreamParser is owned by HttpBasicState which is owned by this object,
375 // so this use of base::Unretained() is safe.
376 int rv = parser()->ReadResponseHeaders(
377 base::Bind(&WebSocketBasicHandshakeStream::ReadResponseHeadersCallback,
378 base::Unretained(this),
379 callback));
[email protected]cd48ed12014-01-22 14:34:22380 if (rv == ERR_IO_PENDING)
381 return rv;
ricea24c195f2015-02-26 12:18:55382 return ValidateResponse(rv);
[email protected]d51365e2013-11-27 10:46:52383}
384
[email protected]d51365e2013-11-27 10:46:52385int WebSocketBasicHandshakeStream::ReadResponseBody(
386 IOBuffer* buf,
387 int buf_len,
388 const CompletionCallback& callback) {
389 return parser()->ReadResponseBody(buf, buf_len, callback);
390}
391
392void WebSocketBasicHandshakeStream::Close(bool not_reusable) {
393 // This class ignores the value of |not_reusable| and never lets the socket be
394 // re-used.
395 if (parser())
396 parser()->Close(true);
397}
398
399bool WebSocketBasicHandshakeStream::IsResponseBodyComplete() const {
400 return parser()->IsResponseBodyComplete();
401}
402
[email protected]d51365e2013-11-27 10:46:52403bool WebSocketBasicHandshakeStream::IsConnectionReused() const {
404 return parser()->IsConnectionReused();
405}
406
407void WebSocketBasicHandshakeStream::SetConnectionReused() {
408 parser()->SetConnectionReused();
409}
410
mmenkebd84c392015-09-02 14:12:34411bool WebSocketBasicHandshakeStream::CanReuseConnection() const {
[email protected]d51365e2013-11-27 10:46:52412 return false;
413}
414
sclittle4de1bab92015-09-22 21:28:24415int64_t WebSocketBasicHandshakeStream::GetTotalReceivedBytes() const {
[email protected]bc92bc972013-12-13 08:32:59416 return 0;
417}
418
sclittlebe1ccf62015-09-02 19:40:36419int64_t WebSocketBasicHandshakeStream::GetTotalSentBytes() const {
420 return 0;
421}
422
rchcd379012017-04-12 21:53:32423bool WebSocketBasicHandshakeStream::GetAlternativeService(
424 AlternativeService* alternative_service) const {
425 return false;
426}
427
[email protected]d51365e2013-11-27 10:46:52428bool WebSocketBasicHandshakeStream::GetLoadTimingInfo(
429 LoadTimingInfo* load_timing_info) const {
430 return state_.connection()->GetLoadTimingInfo(IsConnectionReused(),
431 load_timing_info);
432}
433
434void WebSocketBasicHandshakeStream::GetSSLInfo(SSLInfo* ssl_info) {
435 parser()->GetSSLInfo(ssl_info);
436}
437
438void WebSocketBasicHandshakeStream::GetSSLCertRequestInfo(
439 SSLCertRequestInfo* cert_request_info) {
440 parser()->GetSSLCertRequestInfo(cert_request_info);
441}
442
ttuttled9dbc652015-09-29 20:00:59443bool WebSocketBasicHandshakeStream::GetRemoteEndpoint(IPEndPoint* endpoint) {
444 if (!state_.connection() || !state_.connection()->socket())
445 return false;
446
447 return state_.connection()->socket()->GetPeerAddress(endpoint) == OK;
448}
449
zhongyica364fbb2015-12-12 03:39:12450void WebSocketBasicHandshakeStream::PopulateNetErrorDetails(
451 NetErrorDetails* /*details*/) {
452 return;
453}
454
nharper78e6d2b2016-09-21 05:42:35455Error WebSocketBasicHandshakeStream::GetTokenBindingSignature(
nharperb7441ef2016-01-25 23:54:14456 crypto::ECPrivateKey* key,
nharper78e6d2b2016-09-21 05:42:35457 TokenBindingType tb_type,
nharperb7441ef2016-01-25 23:54:14458 std::vector<uint8_t>* out) {
459 NOTREACHED();
460 return ERR_NOT_IMPLEMENTED;
461}
462
[email protected]d51365e2013-11-27 10:46:52463void WebSocketBasicHandshakeStream::Drain(HttpNetworkSession* session) {
464 HttpResponseBodyDrainer* drainer = new HttpResponseBodyDrainer(this);
465 drainer->Start(session);
466 // |drainer| will delete itself.
467}
468
469void WebSocketBasicHandshakeStream::SetPriority(RequestPriority priority) {
470 // TODO(ricea): See TODO comment in HttpBasicStream::SetPriority(). If it is
471 // gone, then copy whatever has happened there over here.
472}
473
yhiranoa7e05bb2014-11-06 05:40:39474HttpStream* WebSocketBasicHandshakeStream::RenewStreamForAuth() {
475 // Return null because we don't support renewing the stream.
476 return nullptr;
477}
478
danakj9c5cab52016-04-16 00:54:33479std::unique_ptr<WebSocketStream> WebSocketBasicHandshakeStream::Upgrade() {
[email protected]d51365e2013-11-27 10:46:52480 // The HttpStreamParser object has a pointer to our ClientSocketHandle. Make
481 // sure it does not touch it again before it is destroyed.
482 state_.DeleteParser();
[email protected]654866142014-06-24 22:53:31483 WebSocketTransportClientSocketPool::UnlockEndpoint(state_.connection());
danakj9c5cab52016-04-16 00:54:33484 std::unique_ptr<WebSocketStream> basic_stream(
485 new WebSocketBasicStream(state_.ReleaseConnection(), state_.read_buf(),
486 sub_protocol_, extensions_));
[email protected]0be93922014-01-29 00:42:45487 DCHECK(extension_params_.get());
488 if (extension_params_->deflate_enabled) {
[email protected]9c50b042014-04-28 06:40:15489 UMA_HISTOGRAM_ENUMERATION(
490 "Net.WebSocket.DeflateMode",
yhirano8387aee2015-09-14 05:46:49491 extension_params_->deflate_parameters.client_context_take_over_mode(),
[email protected]9c50b042014-04-28 06:40:15492 WebSocketDeflater::NUM_CONTEXT_TAKEOVER_MODE_TYPES);
493
danakj9c5cab52016-04-16 00:54:33494 return std::unique_ptr<WebSocketStream>(new WebSocketDeflateStream(
dchengc7eeda422015-12-26 03:56:48495 std::move(basic_stream), extension_params_->deflate_parameters,
danakj9c5cab52016-04-16 00:54:33496 std::unique_ptr<WebSocketDeflatePredictor>(
yhirano8387aee2015-09-14 05:46:49497 new WebSocketDeflatePredictorImpl)));
[email protected]0be93922014-01-29 00:42:45498 } else {
dchengc7eeda422015-12-26 03:56:48499 return basic_stream;
[email protected]0be93922014-01-29 00:42:45500 }
[email protected]d51365e2013-11-27 10:46:52501}
502
[email protected]a31ecc02013-12-05 08:30:55503void WebSocketBasicHandshakeStream::SetWebSocketKeyForTesting(
504 const std::string& key) {
505 handshake_challenge_for_testing_.reset(new std::string(key));
506}
507
[email protected]d51365e2013-11-27 10:46:52508void WebSocketBasicHandshakeStream::ReadResponseHeadersCallback(
509 const CompletionCallback& callback,
510 int result) {
ricea24c195f2015-02-26 12:18:55511 callback.Run(ValidateResponse(result));
[email protected]d51365e2013-11-27 10:46:52512}
513
[email protected]cd48ed12014-01-22 14:34:22514void WebSocketBasicHandshakeStream::OnFinishOpeningHandshake() {
[email protected]cd48ed12014-01-22 14:34:22515 DCHECK(http_response_info_);
[email protected]e69c1cd2014-07-29 07:42:29516 WebSocketDispatchOnFinishOpeningHandshake(connect_delegate_,
517 url_,
518 http_response_info_->headers,
519 http_response_info_->response_time);
[email protected]cd48ed12014-01-22 14:34:22520}
521
ricea24c195f2015-02-26 12:18:55522int WebSocketBasicHandshakeStream::ValidateResponse(int rv) {
[email protected]d51365e2013-11-27 10:46:52523 DCHECK(http_response_info_);
[email protected]f7e98ca2014-06-19 12:05:43524 // Most net errors happen during connection, so they are not seen by this
525 // method. The histogram for error codes is created in
526 // Delegate::OnResponseStarted in websocket_stream.cc instead.
[email protected]e5760f522014-02-05 12:28:50527 if (rv >= 0) {
[email protected]f7e98ca2014-06-19 12:05:43528 const HttpResponseHeaders* headers = http_response_info_->headers.get();
529 const int response_code = headers->response_code();
530 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.WebSocket.ResponseCode", response_code);
531 switch (response_code) {
[email protected]e5760f522014-02-05 12:28:50532 case HTTP_SWITCHING_PROTOCOLS:
533 OnFinishOpeningHandshake();
534 return ValidateUpgradeResponse(headers);
[email protected]d51365e2013-11-27 10:46:52535
[email protected]e5760f522014-02-05 12:28:50536 // We need to pass these through for authentication to work.
537 case HTTP_UNAUTHORIZED:
538 case HTTP_PROXY_AUTHENTICATION_REQUIRED:
539 return OK;
[email protected]d51365e2013-11-27 10:46:52540
[email protected]e5760f522014-02-05 12:28:50541 // Other status codes are potentially risky (see the warnings in the
542 // WHATWG WebSocket API spec) and so are dropped by default.
543 default:
[email protected]aeb640d2014-02-21 11:03:18544 // A WebSocket server cannot be using HTTP/0.9, so if we see version
545 // 0.9, it means the response was garbage.
546 // Reporting "Unexpected response code: 200" in this case is not
547 // helpful, so use a different error message.
548 if (headers->GetHttpVersion() == HttpVersion(0, 9)) {
tyoshinoccfcfde2016-07-21 14:06:55549 OnFailure("Error during WebSocket handshake: Invalid status line");
[email protected]aeb640d2014-02-21 11:03:18550 } else {
tyoshinoccfcfde2016-07-21 14:06:55551 OnFailure(base::StringPrintf(
[email protected]aeb640d2014-02-21 11:03:18552 "Error during WebSocket handshake: Unexpected response code: %d",
[email protected]8aba0172014-07-03 12:09:53553 headers->response_code()));
[email protected]aeb640d2014-02-21 11:03:18554 }
[email protected]e5760f522014-02-05 12:28:50555 OnFinishOpeningHandshake();
556 return ERR_INVALID_RESPONSE;
557 }
558 } else {
[email protected]3efc08f2014-02-07 09:33:34559 if (rv == ERR_EMPTY_RESPONSE) {
tyoshinoccfcfde2016-07-21 14:06:55560 OnFailure("Connection closed before receiving a handshake response");
[email protected]3efc08f2014-02-07 09:33:34561 return rv;
562 }
tyoshinoccfcfde2016-07-21 14:06:55563 OnFailure(std::string("Error during WebSocket handshake: ") +
564 ErrorToString(rv));
[email protected]e5760f522014-02-05 12:28:50565 OnFinishOpeningHandshake();
ricea23c3f942015-02-02 13:35:13566 // Some error codes (for example ERR_CONNECTION_CLOSED) get changed to OK at
567 // higher levels. To prevent an unvalidated connection getting erroneously
568 // upgraded, don't pass through the status code unchanged if it is
569 // HTTP_SWITCHING_PROTOCOLS.
570 if (http_response_info_->headers &&
571 http_response_info_->headers->response_code() ==
572 HTTP_SWITCHING_PROTOCOLS) {
573 http_response_info_->headers->ReplaceStatusLine(
574 kConnectionErrorStatusLine);
575 }
[email protected]e5760f522014-02-05 12:28:50576 return rv;
[email protected]d51365e2013-11-27 10:46:52577 }
578}
579
580int WebSocketBasicHandshakeStream::ValidateUpgradeResponse(
[email protected]e5760f522014-02-05 12:28:50581 const HttpResponseHeaders* headers) {
[email protected]0be93922014-01-29 00:42:45582 extension_params_.reset(new WebSocketExtensionParams);
[email protected]8aba0172014-07-03 12:09:53583 std::string failure_message;
584 if (ValidateUpgrade(headers, &failure_message) &&
585 ValidateSecWebSocketAccept(
586 headers, handshake_challenge_response_, &failure_message) &&
587 ValidateConnection(headers, &failure_message) &&
[email protected]e5760f522014-02-05 12:28:50588 ValidateSubProtocol(headers,
[email protected]96868202014-01-09 10:38:04589 requested_sub_protocols_,
590 &sub_protocol_,
[email protected]8aba0172014-07-03 12:09:53591 &failure_message) &&
[email protected]e5760f522014-02-05 12:28:50592 ValidateExtensions(headers,
[email protected]96868202014-01-09 10:38:04593 &extensions_,
[email protected]8aba0172014-07-03 12:09:53594 &failure_message,
[email protected]0be93922014-01-29 00:42:45595 extension_params_.get())) {
[email protected]d51365e2013-11-27 10:46:52596 return OK;
597 }
tyoshinoccfcfde2016-07-21 14:06:55598 OnFailure("Error during WebSocket handshake: " + failure_message);
[email protected]d51365e2013-11-27 10:46:52599 return ERR_INVALID_RESPONSE;
600}
601
tyoshinoccfcfde2016-07-21 14:06:55602void WebSocketBasicHandshakeStream::OnFailure(const std::string& message) {
603 stream_request_->OnFailure(message);
[email protected]8aba0172014-07-03 12:09:53604}
605
[email protected]d51365e2013-11-27 10:46:52606} // namespace net