blob: 5b2b031f5b10f4100ab4c388039b45515569116a [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
7#include <algorithm>
8#include <iterator>
[email protected]0be93922014-01-29 00:42:459#include <set>
[email protected]96868202014-01-09 10:38:0410#include <string>
[email protected]cd48ed12014-01-22 14:34:2211#include <vector>
[email protected]d51365e2013-11-27 10:46:5212
13#include "base/base64.h"
14#include "base/basictypes.h"
15#include "base/bind.h"
yhirano27b2b572014-10-30 11:23:4416#include "base/compiler_specific.h"
[email protected]d51365e2013-11-27 10:46:5217#include "base/containers/hash_tables.h"
[email protected]8aba0172014-07-03 12:09:5318#include "base/logging.h"
asvitkinec3c93722015-06-17 14:48:3719#include "base/metrics/histogram_macros.h"
[email protected]f7e98ca2014-06-19 12:05:4320#include "base/metrics/sparse_histogram.h"
[email protected]d51365e2013-11-27 10:46:5221#include "base/stl_util.h"
[email protected]0be93922014-01-29 00:42:4522#include "base/strings/string_number_conversions.h"
[email protected]69d7a492014-02-19 08:36:3223#include "base/strings/string_piece.h"
[email protected]d51365e2013-11-27 10:46:5224#include "base/strings/string_util.h"
[email protected]96868202014-01-09 10:38:0425#include "base/strings/stringprintf.h"
[email protected]cd48ed12014-01-22 14:34:2226#include "base/time/time.h"
[email protected]d51365e2013-11-27 10:46:5227#include "crypto/random.h"
halton.huo299e2002014-12-02 04:39:2428#include "net/base/io_buffer.h"
[email protected]d51365e2013-11-27 10:46:5229#include "net/http/http_request_headers.h"
30#include "net/http/http_request_info.h"
31#include "net/http/http_response_body_drainer.h"
32#include "net/http/http_response_headers.h"
33#include "net/http/http_status_code.h"
34#include "net/http/http_stream_parser.h"
35#include "net/socket/client_socket_handle.h"
[email protected]654866142014-06-24 22:53:3136#include "net/socket/websocket_transport_client_socket_pool.h"
[email protected]d51365e2013-11-27 10:46:5237#include "net/websockets/websocket_basic_stream.h"
[email protected]0be93922014-01-29 00:42:4538#include "net/websockets/websocket_deflate_predictor.h"
39#include "net/websockets/websocket_deflate_predictor_impl.h"
40#include "net/websockets/websocket_deflate_stream.h"
41#include "net/websockets/websocket_deflater.h"
[email protected]96868202014-01-09 10:38:0442#include "net/websockets/websocket_extension_parser.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]0be93922014-01-29 00:42:4557// TODO(ricea): If more extensions are added, replace this with a more general
58// mechanism.
59struct WebSocketExtensionParams {
60 WebSocketExtensionParams()
61 : deflate_enabled(false),
62 client_window_bits(15),
63 deflate_mode(WebSocketDeflater::TAKE_OVER_CONTEXT) {}
64
65 bool deflate_enabled;
66 int client_window_bits;
67 WebSocketDeflater::ContextTakeOverMode deflate_mode;
68};
69
[email protected]d51365e2013-11-27 10:46:5270namespace {
71
[email protected]96868202014-01-09 10:38:0472enum GetHeaderResult {
73 GET_HEADER_OK,
74 GET_HEADER_MISSING,
75 GET_HEADER_MULTIPLE,
76};
77
78std::string MissingHeaderMessage(const std::string& header_name) {
79 return std::string("'") + header_name + "' header is missing";
80}
81
82std::string MultipleHeaderValuesMessage(const std::string& header_name) {
83 return
84 std::string("'") +
85 header_name +
86 "' header must not appear more than once in a response";
87}
88
[email protected]d51365e2013-11-27 10:46:5289std::string GenerateHandshakeChallenge() {
90 std::string raw_challenge(websockets::kRawChallengeLength, '\0');
91 crypto::RandBytes(string_as_array(&raw_challenge), raw_challenge.length());
92 std::string encoded_challenge;
[email protected]33fca122013-12-11 01:48:5093 base::Base64Encode(raw_challenge, &encoded_challenge);
[email protected]d51365e2013-11-27 10:46:5294 return encoded_challenge;
95}
96
97void AddVectorHeaderIfNonEmpty(const char* name,
98 const std::vector<std::string>& value,
99 HttpRequestHeaders* headers) {
100 if (value.empty())
101 return;
brettwd94a22142015-07-15 05:19:26102 headers->SetHeader(name, base::JoinString(value, ", "));
[email protected]d51365e2013-11-27 10:46:52103}
104
[email protected]96868202014-01-09 10:38:04105GetHeaderResult GetSingleHeaderValue(const HttpResponseHeaders* headers,
106 const base::StringPiece& name,
107 std::string* value) {
yhiranoa7e05bb2014-11-06 05:40:39108 void* state = nullptr;
[email protected]96868202014-01-09 10:38:04109 size_t num_values = 0;
110 std::string temp_value;
111 while (headers->EnumerateHeader(&state, name, &temp_value)) {
112 if (++num_values > 1)
113 return GET_HEADER_MULTIPLE;
114 *value = temp_value;
[email protected]d51365e2013-11-27 10:46:52115 }
[email protected]96868202014-01-09 10:38:04116 return num_values > 0 ? GET_HEADER_OK : GET_HEADER_MISSING;
117}
118
119bool ValidateHeaderHasSingleValue(GetHeaderResult result,
120 const std::string& header_name,
121 std::string* failure_message) {
122 if (result == GET_HEADER_MISSING) {
123 *failure_message = MissingHeaderMessage(header_name);
124 return false;
125 }
126 if (result == GET_HEADER_MULTIPLE) {
127 *failure_message = MultipleHeaderValuesMessage(header_name);
128 return false;
129 }
130 DCHECK_EQ(result, GET_HEADER_OK);
131 return true;
132}
133
134bool ValidateUpgrade(const HttpResponseHeaders* headers,
135 std::string* failure_message) {
136 std::string value;
137 GetHeaderResult result =
138 GetSingleHeaderValue(headers, websockets::kUpgrade, &value);
139 if (!ValidateHeaderHasSingleValue(result,
140 websockets::kUpgrade,
141 failure_message)) {
142 return false;
143 }
144
brettwbc17d2c82015-06-09 22:39:08145 if (!base::LowerCaseEqualsASCII(value, websockets::kWebSocketLowercase)) {
[email protected]96868202014-01-09 10:38:04146 *failure_message =
147 "'Upgrade' header value is not 'WebSocket': " + value;
148 return false;
149 }
150 return true;
151}
152
153bool ValidateSecWebSocketAccept(const HttpResponseHeaders* headers,
154 const std::string& expected,
155 std::string* failure_message) {
156 std::string actual;
157 GetHeaderResult result =
158 GetSingleHeaderValue(headers, websockets::kSecWebSocketAccept, &actual);
159 if (!ValidateHeaderHasSingleValue(result,
160 websockets::kSecWebSocketAccept,
161 failure_message)) {
162 return false;
163 }
164
165 if (expected != actual) {
166 *failure_message = "Incorrect 'Sec-WebSocket-Accept' header value";
167 return false;
168 }
169 return true;
170}
171
172bool ValidateConnection(const HttpResponseHeaders* headers,
173 std::string* failure_message) {
174 // Connection header is permitted to contain other tokens.
175 if (!headers->HasHeader(HttpRequestHeaders::kConnection)) {
176 *failure_message = MissingHeaderMessage(HttpRequestHeaders::kConnection);
177 return false;
178 }
179 if (!headers->HasHeaderValue(HttpRequestHeaders::kConnection,
180 websockets::kUpgrade)) {
181 *failure_message = "'Connection' header value must contain 'Upgrade'";
182 return false;
183 }
184 return true;
[email protected]d51365e2013-11-27 10:46:52185}
186
187bool ValidateSubProtocol(
[email protected]96868202014-01-09 10:38:04188 const HttpResponseHeaders* headers,
[email protected]d51365e2013-11-27 10:46:52189 const std::vector<std::string>& requested_sub_protocols,
[email protected]96868202014-01-09 10:38:04190 std::string* sub_protocol,
191 std::string* failure_message) {
yhiranoa7e05bb2014-11-06 05:40:39192 void* state = nullptr;
[email protected]96868202014-01-09 10:38:04193 std::string value;
[email protected]d51365e2013-11-27 10:46:52194 base::hash_set<std::string> requested_set(requested_sub_protocols.begin(),
195 requested_sub_protocols.end());
[email protected]96868202014-01-09 10:38:04196 int count = 0;
197 bool has_multiple_protocols = false;
198 bool has_invalid_protocol = false;
[email protected]d51365e2013-11-27 10:46:52199
[email protected]96868202014-01-09 10:38:04200 while (!has_invalid_protocol || !has_multiple_protocols) {
201 std::string temp_value;
202 if (!headers->EnumerateHeader(
203 &state, websockets::kSecWebSocketProtocol, &temp_value))
204 break;
205 value = temp_value;
206 if (requested_set.count(value) == 0)
207 has_invalid_protocol = true;
208 if (++count > 1)
209 has_multiple_protocols = true;
[email protected]d51365e2013-11-27 10:46:52210 }
[email protected]96868202014-01-09 10:38:04211
212 if (has_multiple_protocols) {
213 *failure_message =
214 MultipleHeaderValuesMessage(websockets::kSecWebSocketProtocol);
215 return false;
216 } else if (count > 0 && requested_sub_protocols.size() == 0) {
217 *failure_message =
218 std::string("Response must not include 'Sec-WebSocket-Protocol' "
219 "header if not present in request: ")
220 + value;
221 return false;
222 } else if (has_invalid_protocol) {
223 *failure_message =
224 "'Sec-WebSocket-Protocol' header value '" +
225 value +
226 "' in response does not match any of sent values";
227 return false;
228 } else if (requested_sub_protocols.size() > 0 && count == 0) {
229 *failure_message =
230 "Sent non-empty 'Sec-WebSocket-Protocol' header "
231 "but no response was received";
232 return false;
233 }
234 *sub_protocol = value;
235 return true;
[email protected]d51365e2013-11-27 10:46:52236}
237
[email protected]69d7a492014-02-19 08:36:32238bool DeflateError(std::string* message, const base::StringPiece& piece) {
239 *message = "Error in permessage-deflate: ";
[email protected]0ecab7892014-03-11 21:15:40240 piece.AppendToString(message);
[email protected]69d7a492014-02-19 08:36:32241 return false;
242}
243
[email protected]0be93922014-01-29 00:42:45244bool ValidatePerMessageDeflateExtension(const WebSocketExtension& extension,
245 std::string* failure_message,
246 WebSocketExtensionParams* params) {
247 static const char kClientPrefix[] = "client_";
248 static const char kServerPrefix[] = "server_";
249 static const char kNoContextTakeover[] = "no_context_takeover";
250 static const char kMaxWindowBits[] = "max_window_bits";
251 const size_t kPrefixLen = arraysize(kClientPrefix) - 1;
mostynb91e0da982015-01-20 19:17:27252 static_assert(kPrefixLen == arraysize(kServerPrefix) - 1,
253 "the strings server and client must be the same length");
[email protected]0be93922014-01-29 00:42:45254 typedef std::vector<WebSocketExtension::Parameter> ParameterVector;
255
[email protected]e5760f522014-02-05 12:28:50256 DCHECK_EQ("permessage-deflate", extension.name());
[email protected]0be93922014-01-29 00:42:45257 const ParameterVector& parameters = extension.parameters();
258 std::set<std::string> seen_names;
259 for (ParameterVector::const_iterator it = parameters.begin();
260 it != parameters.end(); ++it) {
261 const std::string& name = it->name();
262 if (seen_names.count(name) != 0) {
[email protected]69d7a492014-02-19 08:36:32263 return DeflateError(
264 failure_message,
265 "Received duplicate permessage-deflate extension parameter " + name);
[email protected]0be93922014-01-29 00:42:45266 }
267 seen_names.insert(name);
268 const std::string client_or_server(name, 0, kPrefixLen);
269 const bool is_client = (client_or_server == kClientPrefix);
270 if (!is_client && client_or_server != kServerPrefix) {
[email protected]69d7a492014-02-19 08:36:32271 return DeflateError(
272 failure_message,
273 "Received an unexpected permessage-deflate extension parameter");
[email protected]0be93922014-01-29 00:42:45274 }
275 const std::string rest(name, kPrefixLen);
276 if (rest == kNoContextTakeover) {
277 if (it->HasValue()) {
[email protected]69d7a492014-02-19 08:36:32278 return DeflateError(failure_message,
279 "Received invalid " + name + " parameter");
[email protected]0be93922014-01-29 00:42:45280 }
281 if (is_client)
282 params->deflate_mode = WebSocketDeflater::DO_NOT_TAKE_OVER_CONTEXT;
283 } else if (rest == kMaxWindowBits) {
[email protected]69d7a492014-02-19 08:36:32284 if (!it->HasValue())
285 return DeflateError(failure_message, name + " must have value");
[email protected]0be93922014-01-29 00:42:45286 int bits = 0;
287 if (!base::StringToInt(it->value(), &bits) || bits < 8 || bits > 15 ||
288 it->value()[0] == '0' ||
289 it->value().find_first_not_of("0123456789") != std::string::npos) {
[email protected]69d7a492014-02-19 08:36:32290 return DeflateError(failure_message,
291 "Received invalid " + name + " parameter");
[email protected]0be93922014-01-29 00:42:45292 }
293 if (is_client)
294 params->client_window_bits = bits;
295 } else {
[email protected]69d7a492014-02-19 08:36:32296 return DeflateError(
297 failure_message,
298 "Received an unexpected permessage-deflate extension parameter");
[email protected]0be93922014-01-29 00:42:45299 }
300 }
301 params->deflate_enabled = true;
302 return true;
303}
304
[email protected]96868202014-01-09 10:38:04305bool ValidateExtensions(const HttpResponseHeaders* headers,
tyoshino38ee68c2015-04-01 05:52:52306 std::string* accepted_extensions_descriptor,
[email protected]0be93922014-01-29 00:42:45307 std::string* failure_message,
308 WebSocketExtensionParams* params) {
yhiranoa7e05bb2014-11-06 05:40:39309 void* state = nullptr;
tyoshino38ee68c2015-04-01 05:52:52310 std::string header_value;
311 std::vector<std::string> header_values;
[email protected]0be93922014-01-29 00:42:45312 // TODO(ricea): If adding support for additional extensions, generalise this
313 // code.
314 bool seen_permessage_deflate = false;
tyoshino38ee68c2015-04-01 05:52:52315 while (headers->EnumerateHeader(&state, websockets::kSecWebSocketExtensions,
316 &header_value)) {
[email protected]96868202014-01-09 10:38:04317 WebSocketExtensionParser parser;
tyoshinod90d2932015-04-13 16:53:32318 if (!parser.Parse(header_value)) {
[email protected]96868202014-01-09 10:38:04319 // TODO(yhirano) Set appropriate failure message.
320 *failure_message =
321 "'Sec-WebSocket-Extensions' header value is "
322 "rejected by the parser: " +
tyoshino38ee68c2015-04-01 05:52:52323 header_value;
[email protected]96868202014-01-09 10:38:04324 return false;
325 }
tyoshino38ee68c2015-04-01 05:52:52326
327 const std::vector<WebSocketExtension>& extensions = parser.extensions();
328 for (const auto& extension : extensions) {
329 if (extension.name() == "permessage-deflate") {
330 if (seen_permessage_deflate) {
331 *failure_message = "Received duplicate permessage-deflate response";
332 return false;
333 }
334 seen_permessage_deflate = true;
335
336 if (!ValidatePerMessageDeflateExtension(extension, failure_message,
337 params)) {
338 return false;
339 }
340 header_values.push_back(header_value);
341 } else {
342 *failure_message = "Found an unsupported extension '" +
343 extension.name() +
344 "' in 'Sec-WebSocket-Extensions' header";
[email protected]0be93922014-01-29 00:42:45345 return false;
346 }
[email protected]0be93922014-01-29 00:42:45347 }
[email protected]d51365e2013-11-27 10:46:52348 }
brettwd94a22142015-07-15 05:19:26349 *accepted_extensions_descriptor = base::JoinString(header_values, ", ");
[email protected]d51365e2013-11-27 10:46:52350 return true;
351}
352
353} // namespace
354
355WebSocketBasicHandshakeStream::WebSocketBasicHandshakeStream(
356 scoped_ptr<ClientSocketHandle> connection,
[email protected]cd48ed12014-01-22 14:34:22357 WebSocketStream::ConnectDelegate* connect_delegate,
[email protected]d51365e2013-11-27 10:46:52358 bool using_proxy,
359 std::vector<std::string> requested_sub_protocols,
[email protected]8aba0172014-07-03 12:09:53360 std::vector<std::string> requested_extensions,
361 std::string* failure_message)
[email protected]d51365e2013-11-27 10:46:52362 : state_(connection.release(), using_proxy),
[email protected]cd48ed12014-01-22 14:34:22363 connect_delegate_(connect_delegate),
yhiranoa7e05bb2014-11-06 05:40:39364 http_response_info_(nullptr),
[email protected]d51365e2013-11-27 10:46:52365 requested_sub_protocols_(requested_sub_protocols),
[email protected]8aba0172014-07-03 12:09:53366 requested_extensions_(requested_extensions),
367 failure_message_(failure_message) {
368 DCHECK(connect_delegate);
369 DCHECK(failure_message);
370}
[email protected]d51365e2013-11-27 10:46:52371
372WebSocketBasicHandshakeStream::~WebSocketBasicHandshakeStream() {}
373
374int WebSocketBasicHandshakeStream::InitializeStream(
375 const HttpRequestInfo* request_info,
376 RequestPriority priority,
377 const BoundNetLog& net_log,
378 const CompletionCallback& callback) {
[email protected]cd48ed12014-01-22 14:34:22379 url_ = request_info->url;
[email protected]d51365e2013-11-27 10:46:52380 state_.Initialize(request_info, priority, net_log, callback);
381 return OK;
382}
383
384int WebSocketBasicHandshakeStream::SendRequest(
385 const HttpRequestHeaders& headers,
386 HttpResponseInfo* response,
387 const CompletionCallback& callback) {
388 DCHECK(!headers.HasHeader(websockets::kSecWebSocketKey));
389 DCHECK(!headers.HasHeader(websockets::kSecWebSocketProtocol));
390 DCHECK(!headers.HasHeader(websockets::kSecWebSocketExtensions));
391 DCHECK(headers.HasHeader(HttpRequestHeaders::kOrigin));
392 DCHECK(headers.HasHeader(websockets::kUpgrade));
393 DCHECK(headers.HasHeader(HttpRequestHeaders::kConnection));
394 DCHECK(headers.HasHeader(websockets::kSecWebSocketVersion));
395 DCHECK(parser());
396
397 http_response_info_ = response;
398
399 // Create a copy of the headers object, so that we can add the
400 // Sec-WebSockey-Key header.
401 HttpRequestHeaders enriched_headers;
402 enriched_headers.CopyFrom(headers);
[email protected]a31ecc02013-12-05 08:30:55403 std::string handshake_challenge;
404 if (handshake_challenge_for_testing_) {
405 handshake_challenge = *handshake_challenge_for_testing_;
406 handshake_challenge_for_testing_.reset();
407 } else {
408 handshake_challenge = GenerateHandshakeChallenge();
409 }
[email protected]d51365e2013-11-27 10:46:52410 enriched_headers.SetHeader(websockets::kSecWebSocketKey, handshake_challenge);
411
[email protected]d51365e2013-11-27 10:46:52412 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketExtensions,
413 requested_extensions_,
414 &enriched_headers);
[email protected]0be93922014-01-29 00:42:45415 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketProtocol,
416 requested_sub_protocols_,
417 &enriched_headers);
[email protected]d51365e2013-11-27 10:46:52418
ricea11bdcd02014-11-20 09:57:07419 handshake_challenge_response_ =
420 ComputeSecWebSocketAccept(handshake_challenge);
[email protected]d51365e2013-11-27 10:46:52421
[email protected]cd48ed12014-01-22 14:34:22422 DCHECK(connect_delegate_);
423 scoped_ptr<WebSocketHandshakeRequestInfo> request(
424 new WebSocketHandshakeRequestInfo(url_, base::Time::Now()));
425 request->headers.CopyFrom(enriched_headers);
426 connect_delegate_->OnStartOpeningHandshake(request.Pass());
427
[email protected]d51365e2013-11-27 10:46:52428 return parser()->SendRequest(
429 state_.GenerateRequestLine(), enriched_headers, response, callback);
430}
431
432int WebSocketBasicHandshakeStream::ReadResponseHeaders(
433 const CompletionCallback& callback) {
434 // HttpStreamParser uses a weak pointer when reading from the
435 // socket, so it won't be called back after being destroyed. The
436 // HttpStreamParser is owned by HttpBasicState which is owned by this object,
437 // so this use of base::Unretained() is safe.
438 int rv = parser()->ReadResponseHeaders(
439 base::Bind(&WebSocketBasicHandshakeStream::ReadResponseHeadersCallback,
440 base::Unretained(this),
441 callback));
[email protected]cd48ed12014-01-22 14:34:22442 if (rv == ERR_IO_PENDING)
443 return rv;
ricea24c195f2015-02-26 12:18:55444 return ValidateResponse(rv);
[email protected]d51365e2013-11-27 10:46:52445}
446
[email protected]d51365e2013-11-27 10:46:52447int WebSocketBasicHandshakeStream::ReadResponseBody(
448 IOBuffer* buf,
449 int buf_len,
450 const CompletionCallback& callback) {
451 return parser()->ReadResponseBody(buf, buf_len, callback);
452}
453
454void WebSocketBasicHandshakeStream::Close(bool not_reusable) {
455 // This class ignores the value of |not_reusable| and never lets the socket be
456 // re-used.
457 if (parser())
458 parser()->Close(true);
459}
460
461bool WebSocketBasicHandshakeStream::IsResponseBodyComplete() const {
462 return parser()->IsResponseBodyComplete();
463}
464
[email protected]d51365e2013-11-27 10:46:52465bool WebSocketBasicHandshakeStream::IsConnectionReused() const {
466 return parser()->IsConnectionReused();
467}
468
469void WebSocketBasicHandshakeStream::SetConnectionReused() {
470 parser()->SetConnectionReused();
471}
472
mmenkebd84c392015-09-02 14:12:34473bool WebSocketBasicHandshakeStream::CanReuseConnection() const {
[email protected]d51365e2013-11-27 10:46:52474 return false;
475}
476
[email protected]bc92bc972013-12-13 08:32:59477int64 WebSocketBasicHandshakeStream::GetTotalReceivedBytes() const {
478 return 0;
479}
480
[email protected]d51365e2013-11-27 10:46:52481bool WebSocketBasicHandshakeStream::GetLoadTimingInfo(
482 LoadTimingInfo* load_timing_info) const {
483 return state_.connection()->GetLoadTimingInfo(IsConnectionReused(),
484 load_timing_info);
485}
486
487void WebSocketBasicHandshakeStream::GetSSLInfo(SSLInfo* ssl_info) {
488 parser()->GetSSLInfo(ssl_info);
489}
490
491void WebSocketBasicHandshakeStream::GetSSLCertRequestInfo(
492 SSLCertRequestInfo* cert_request_info) {
493 parser()->GetSSLCertRequestInfo(cert_request_info);
494}
495
[email protected]d51365e2013-11-27 10:46:52496void WebSocketBasicHandshakeStream::Drain(HttpNetworkSession* session) {
497 HttpResponseBodyDrainer* drainer = new HttpResponseBodyDrainer(this);
498 drainer->Start(session);
499 // |drainer| will delete itself.
500}
501
502void WebSocketBasicHandshakeStream::SetPriority(RequestPriority priority) {
503 // TODO(ricea): See TODO comment in HttpBasicStream::SetPriority(). If it is
504 // gone, then copy whatever has happened there over here.
505}
506
yhiranoa7e05bb2014-11-06 05:40:39507UploadProgress WebSocketBasicHandshakeStream::GetUploadProgress() const {
508 return UploadProgress();
509}
510
511HttpStream* WebSocketBasicHandshakeStream::RenewStreamForAuth() {
512 // Return null because we don't support renewing the stream.
513 return nullptr;
514}
515
[email protected]d51365e2013-11-27 10:46:52516scoped_ptr<WebSocketStream> WebSocketBasicHandshakeStream::Upgrade() {
[email protected]d51365e2013-11-27 10:46:52517 // The HttpStreamParser object has a pointer to our ClientSocketHandle. Make
518 // sure it does not touch it again before it is destroyed.
519 state_.DeleteParser();
[email protected]654866142014-06-24 22:53:31520 WebSocketTransportClientSocketPool::UnlockEndpoint(state_.connection());
[email protected]0be93922014-01-29 00:42:45521 scoped_ptr<WebSocketStream> basic_stream(
[email protected]d51365e2013-11-27 10:46:52522 new WebSocketBasicStream(state_.ReleaseConnection(),
523 state_.read_buf(),
524 sub_protocol_,
525 extensions_));
[email protected]0be93922014-01-29 00:42:45526 DCHECK(extension_params_.get());
527 if (extension_params_->deflate_enabled) {
[email protected]9c50b042014-04-28 06:40:15528 UMA_HISTOGRAM_ENUMERATION(
529 "Net.WebSocket.DeflateMode",
530 extension_params_->deflate_mode,
531 WebSocketDeflater::NUM_CONTEXT_TAKEOVER_MODE_TYPES);
532
[email protected]0be93922014-01-29 00:42:45533 return scoped_ptr<WebSocketStream>(
534 new WebSocketDeflateStream(basic_stream.Pass(),
535 extension_params_->deflate_mode,
536 extension_params_->client_window_bits,
537 scoped_ptr<WebSocketDeflatePredictor>(
538 new WebSocketDeflatePredictorImpl)));
539 } else {
540 return basic_stream.Pass();
541 }
[email protected]d51365e2013-11-27 10:46:52542}
543
[email protected]a31ecc02013-12-05 08:30:55544void WebSocketBasicHandshakeStream::SetWebSocketKeyForTesting(
545 const std::string& key) {
546 handshake_challenge_for_testing_.reset(new std::string(key));
547}
548
[email protected]d51365e2013-11-27 10:46:52549void WebSocketBasicHandshakeStream::ReadResponseHeadersCallback(
550 const CompletionCallback& callback,
551 int result) {
ricea24c195f2015-02-26 12:18:55552 callback.Run(ValidateResponse(result));
[email protected]d51365e2013-11-27 10:46:52553}
554
[email protected]cd48ed12014-01-22 14:34:22555void WebSocketBasicHandshakeStream::OnFinishOpeningHandshake() {
[email protected]cd48ed12014-01-22 14:34:22556 DCHECK(http_response_info_);
[email protected]e69c1cd2014-07-29 07:42:29557 WebSocketDispatchOnFinishOpeningHandshake(connect_delegate_,
558 url_,
559 http_response_info_->headers,
560 http_response_info_->response_time);
[email protected]cd48ed12014-01-22 14:34:22561}
562
ricea24c195f2015-02-26 12:18:55563int WebSocketBasicHandshakeStream::ValidateResponse(int rv) {
[email protected]d51365e2013-11-27 10:46:52564 DCHECK(http_response_info_);
[email protected]f7e98ca2014-06-19 12:05:43565 // Most net errors happen during connection, so they are not seen by this
566 // method. The histogram for error codes is created in
567 // Delegate::OnResponseStarted in websocket_stream.cc instead.
[email protected]e5760f522014-02-05 12:28:50568 if (rv >= 0) {
[email protected]f7e98ca2014-06-19 12:05:43569 const HttpResponseHeaders* headers = http_response_info_->headers.get();
570 const int response_code = headers->response_code();
571 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.WebSocket.ResponseCode", response_code);
572 switch (response_code) {
[email protected]e5760f522014-02-05 12:28:50573 case HTTP_SWITCHING_PROTOCOLS:
574 OnFinishOpeningHandshake();
575 return ValidateUpgradeResponse(headers);
[email protected]d51365e2013-11-27 10:46:52576
[email protected]e5760f522014-02-05 12:28:50577 // We need to pass these through for authentication to work.
578 case HTTP_UNAUTHORIZED:
579 case HTTP_PROXY_AUTHENTICATION_REQUIRED:
580 return OK;
[email protected]d51365e2013-11-27 10:46:52581
[email protected]e5760f522014-02-05 12:28:50582 // Other status codes are potentially risky (see the warnings in the
583 // WHATWG WebSocket API spec) and so are dropped by default.
584 default:
[email protected]aeb640d2014-02-21 11:03:18585 // A WebSocket server cannot be using HTTP/0.9, so if we see version
586 // 0.9, it means the response was garbage.
587 // Reporting "Unexpected response code: 200" in this case is not
588 // helpful, so use a different error message.
589 if (headers->GetHttpVersion() == HttpVersion(0, 9)) {
[email protected]8aba0172014-07-03 12:09:53590 set_failure_message(
591 "Error during WebSocket handshake: Invalid status line");
[email protected]aeb640d2014-02-21 11:03:18592 } else {
[email protected]8aba0172014-07-03 12:09:53593 set_failure_message(base::StringPrintf(
[email protected]aeb640d2014-02-21 11:03:18594 "Error during WebSocket handshake: Unexpected response code: %d",
[email protected]8aba0172014-07-03 12:09:53595 headers->response_code()));
[email protected]aeb640d2014-02-21 11:03:18596 }
[email protected]e5760f522014-02-05 12:28:50597 OnFinishOpeningHandshake();
598 return ERR_INVALID_RESPONSE;
599 }
600 } else {
[email protected]3efc08f2014-02-07 09:33:34601 if (rv == ERR_EMPTY_RESPONSE) {
[email protected]8aba0172014-07-03 12:09:53602 set_failure_message(
603 "Connection closed before receiving a handshake response");
[email protected]3efc08f2014-02-07 09:33:34604 return rv;
605 }
[email protected]8aba0172014-07-03 12:09:53606 set_failure_message(std::string("Error during WebSocket handshake: ") +
607 ErrorToString(rv));
[email protected]e5760f522014-02-05 12:28:50608 OnFinishOpeningHandshake();
ricea23c3f942015-02-02 13:35:13609 // Some error codes (for example ERR_CONNECTION_CLOSED) get changed to OK at
610 // higher levels. To prevent an unvalidated connection getting erroneously
611 // upgraded, don't pass through the status code unchanged if it is
612 // HTTP_SWITCHING_PROTOCOLS.
613 if (http_response_info_->headers &&
614 http_response_info_->headers->response_code() ==
615 HTTP_SWITCHING_PROTOCOLS) {
616 http_response_info_->headers->ReplaceStatusLine(
617 kConnectionErrorStatusLine);
618 }
[email protected]e5760f522014-02-05 12:28:50619 return rv;
[email protected]d51365e2013-11-27 10:46:52620 }
621}
622
623int WebSocketBasicHandshakeStream::ValidateUpgradeResponse(
[email protected]e5760f522014-02-05 12:28:50624 const HttpResponseHeaders* headers) {
[email protected]0be93922014-01-29 00:42:45625 extension_params_.reset(new WebSocketExtensionParams);
[email protected]8aba0172014-07-03 12:09:53626 std::string failure_message;
627 if (ValidateUpgrade(headers, &failure_message) &&
628 ValidateSecWebSocketAccept(
629 headers, handshake_challenge_response_, &failure_message) &&
630 ValidateConnection(headers, &failure_message) &&
[email protected]e5760f522014-02-05 12:28:50631 ValidateSubProtocol(headers,
[email protected]96868202014-01-09 10:38:04632 requested_sub_protocols_,
633 &sub_protocol_,
[email protected]8aba0172014-07-03 12:09:53634 &failure_message) &&
[email protected]e5760f522014-02-05 12:28:50635 ValidateExtensions(headers,
[email protected]96868202014-01-09 10:38:04636 &extensions_,
[email protected]8aba0172014-07-03 12:09:53637 &failure_message,
[email protected]0be93922014-01-29 00:42:45638 extension_params_.get())) {
[email protected]d51365e2013-11-27 10:46:52639 return OK;
640 }
[email protected]8aba0172014-07-03 12:09:53641 set_failure_message("Error during WebSocket handshake: " + failure_message);
[email protected]d51365e2013-11-27 10:46:52642 return ERR_INVALID_RESPONSE;
643}
644
[email protected]8aba0172014-07-03 12:09:53645void WebSocketBasicHandshakeStream::set_failure_message(
646 const std::string& failure_message) {
647 *failure_message_ = failure_message;
648}
649
[email protected]d51365e2013-11-27 10:46:52650} // namespace net