blob: 6255d8f2f97de3c469d6d05dbf8eb8c3114f1ea0 [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"
[email protected]9c50b042014-04-28 06:40:1519#include "base/metrics/histogram.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"
28#include "net/http/http_request_headers.h"
29#include "net/http/http_request_info.h"
30#include "net/http/http_response_body_drainer.h"
31#include "net/http/http_response_headers.h"
32#include "net/http/http_status_code.h"
33#include "net/http/http_stream_parser.h"
34#include "net/socket/client_socket_handle.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"
[email protected]0be93922014-01-29 00:42:4537#include "net/websockets/websocket_deflate_predictor.h"
38#include "net/websockets/websocket_deflate_predictor_impl.h"
39#include "net/websockets/websocket_deflate_stream.h"
40#include "net/websockets/websocket_deflater.h"
[email protected]96868202014-01-09 10:38:0441#include "net/websockets/websocket_extension_parser.h"
[email protected]d51365e2013-11-27 10:46:5242#include "net/websockets/websocket_handshake_constants.h"
43#include "net/websockets/websocket_handshake_handler.h"
[email protected]cd48ed12014-01-22 14:34:2244#include "net/websockets/websocket_handshake_request_info.h"
45#include "net/websockets/websocket_handshake_response_info.h"
[email protected]d51365e2013-11-27 10:46:5246#include "net/websockets/websocket_stream.h"
47
48namespace net {
[email protected]0be93922014-01-29 00:42:4549
yhirano27b2b572014-10-30 11:23:4450namespace {
51
52// TODO(yhirano): Remove these functions once http://crbug.com/399535 is fixed.
53NOINLINE void RunCallbackWithOk(const CompletionCallback& callback,
54 int result) {
55 DCHECK_EQ(result, OK);
56 callback.Run(OK);
57}
58
59NOINLINE void RunCallbackWithInvalidResponseCausedByRedirect(
60 const CompletionCallback& callback,
61 int result) {
62 DCHECK_EQ(result, ERR_INVALID_RESPONSE);
63 callback.Run(ERR_INVALID_RESPONSE);
64}
65
66NOINLINE void RunCallbackWithInvalidResponse(
67 const CompletionCallback& callback,
68 int result) {
69 DCHECK_EQ(result, ERR_INVALID_RESPONSE);
70 callback.Run(ERR_INVALID_RESPONSE);
71}
72
73NOINLINE void RunCallback(const CompletionCallback& callback, int result) {
74 callback.Run(result);
75}
76
77} // namespace
78
[email protected]0be93922014-01-29 00:42:4579// TODO(ricea): If more extensions are added, replace this with a more general
80// mechanism.
81struct WebSocketExtensionParams {
82 WebSocketExtensionParams()
83 : deflate_enabled(false),
84 client_window_bits(15),
85 deflate_mode(WebSocketDeflater::TAKE_OVER_CONTEXT) {}
86
87 bool deflate_enabled;
88 int client_window_bits;
89 WebSocketDeflater::ContextTakeOverMode deflate_mode;
90};
91
[email protected]d51365e2013-11-27 10:46:5292namespace {
93
[email protected]96868202014-01-09 10:38:0494enum GetHeaderResult {
95 GET_HEADER_OK,
96 GET_HEADER_MISSING,
97 GET_HEADER_MULTIPLE,
98};
99
100std::string MissingHeaderMessage(const std::string& header_name) {
101 return std::string("'") + header_name + "' header is missing";
102}
103
104std::string MultipleHeaderValuesMessage(const std::string& header_name) {
105 return
106 std::string("'") +
107 header_name +
108 "' header must not appear more than once in a response";
109}
110
[email protected]d51365e2013-11-27 10:46:52111std::string GenerateHandshakeChallenge() {
112 std::string raw_challenge(websockets::kRawChallengeLength, '\0');
113 crypto::RandBytes(string_as_array(&raw_challenge), raw_challenge.length());
114 std::string encoded_challenge;
[email protected]33fca122013-12-11 01:48:50115 base::Base64Encode(raw_challenge, &encoded_challenge);
[email protected]d51365e2013-11-27 10:46:52116 return encoded_challenge;
117}
118
119void AddVectorHeaderIfNonEmpty(const char* name,
120 const std::vector<std::string>& value,
121 HttpRequestHeaders* headers) {
122 if (value.empty())
123 return;
124 headers->SetHeader(name, JoinString(value, ", "));
125}
126
[email protected]96868202014-01-09 10:38:04127GetHeaderResult GetSingleHeaderValue(const HttpResponseHeaders* headers,
128 const base::StringPiece& name,
129 std::string* value) {
[email protected]d51365e2013-11-27 10:46:52130 void* state = NULL;
[email protected]96868202014-01-09 10:38:04131 size_t num_values = 0;
132 std::string temp_value;
133 while (headers->EnumerateHeader(&state, name, &temp_value)) {
134 if (++num_values > 1)
135 return GET_HEADER_MULTIPLE;
136 *value = temp_value;
[email protected]d51365e2013-11-27 10:46:52137 }
[email protected]96868202014-01-09 10:38:04138 return num_values > 0 ? GET_HEADER_OK : GET_HEADER_MISSING;
139}
140
141bool ValidateHeaderHasSingleValue(GetHeaderResult result,
142 const std::string& header_name,
143 std::string* failure_message) {
144 if (result == GET_HEADER_MISSING) {
145 *failure_message = MissingHeaderMessage(header_name);
146 return false;
147 }
148 if (result == GET_HEADER_MULTIPLE) {
149 *failure_message = MultipleHeaderValuesMessage(header_name);
150 return false;
151 }
152 DCHECK_EQ(result, GET_HEADER_OK);
153 return true;
154}
155
156bool ValidateUpgrade(const HttpResponseHeaders* headers,
157 std::string* failure_message) {
158 std::string value;
159 GetHeaderResult result =
160 GetSingleHeaderValue(headers, websockets::kUpgrade, &value);
161 if (!ValidateHeaderHasSingleValue(result,
162 websockets::kUpgrade,
163 failure_message)) {
164 return false;
165 }
166
[email protected]df807042014-08-13 16:48:41167 if (!LowerCaseEqualsASCII(value, websockets::kWebSocketLowercase)) {
[email protected]96868202014-01-09 10:38:04168 *failure_message =
169 "'Upgrade' header value is not 'WebSocket': " + value;
170 return false;
171 }
172 return true;
173}
174
175bool ValidateSecWebSocketAccept(const HttpResponseHeaders* headers,
176 const std::string& expected,
177 std::string* failure_message) {
178 std::string actual;
179 GetHeaderResult result =
180 GetSingleHeaderValue(headers, websockets::kSecWebSocketAccept, &actual);
181 if (!ValidateHeaderHasSingleValue(result,
182 websockets::kSecWebSocketAccept,
183 failure_message)) {
184 return false;
185 }
186
187 if (expected != actual) {
188 *failure_message = "Incorrect 'Sec-WebSocket-Accept' header value";
189 return false;
190 }
191 return true;
192}
193
194bool ValidateConnection(const HttpResponseHeaders* headers,
195 std::string* failure_message) {
196 // Connection header is permitted to contain other tokens.
197 if (!headers->HasHeader(HttpRequestHeaders::kConnection)) {
198 *failure_message = MissingHeaderMessage(HttpRequestHeaders::kConnection);
199 return false;
200 }
201 if (!headers->HasHeaderValue(HttpRequestHeaders::kConnection,
202 websockets::kUpgrade)) {
203 *failure_message = "'Connection' header value must contain 'Upgrade'";
204 return false;
205 }
206 return true;
[email protected]d51365e2013-11-27 10:46:52207}
208
209bool ValidateSubProtocol(
[email protected]96868202014-01-09 10:38:04210 const HttpResponseHeaders* headers,
[email protected]d51365e2013-11-27 10:46:52211 const std::vector<std::string>& requested_sub_protocols,
[email protected]96868202014-01-09 10:38:04212 std::string* sub_protocol,
213 std::string* failure_message) {
[email protected]d51365e2013-11-27 10:46:52214 void* state = NULL;
[email protected]96868202014-01-09 10:38:04215 std::string value;
[email protected]d51365e2013-11-27 10:46:52216 base::hash_set<std::string> requested_set(requested_sub_protocols.begin(),
217 requested_sub_protocols.end());
[email protected]96868202014-01-09 10:38:04218 int count = 0;
219 bool has_multiple_protocols = false;
220 bool has_invalid_protocol = false;
[email protected]d51365e2013-11-27 10:46:52221
[email protected]96868202014-01-09 10:38:04222 while (!has_invalid_protocol || !has_multiple_protocols) {
223 std::string temp_value;
224 if (!headers->EnumerateHeader(
225 &state, websockets::kSecWebSocketProtocol, &temp_value))
226 break;
227 value = temp_value;
228 if (requested_set.count(value) == 0)
229 has_invalid_protocol = true;
230 if (++count > 1)
231 has_multiple_protocols = true;
[email protected]d51365e2013-11-27 10:46:52232 }
[email protected]96868202014-01-09 10:38:04233
234 if (has_multiple_protocols) {
235 *failure_message =
236 MultipleHeaderValuesMessage(websockets::kSecWebSocketProtocol);
237 return false;
238 } else if (count > 0 && requested_sub_protocols.size() == 0) {
239 *failure_message =
240 std::string("Response must not include 'Sec-WebSocket-Protocol' "
241 "header if not present in request: ")
242 + value;
243 return false;
244 } else if (has_invalid_protocol) {
245 *failure_message =
246 "'Sec-WebSocket-Protocol' header value '" +
247 value +
248 "' in response does not match any of sent values";
249 return false;
250 } else if (requested_sub_protocols.size() > 0 && count == 0) {
251 *failure_message =
252 "Sent non-empty 'Sec-WebSocket-Protocol' header "
253 "but no response was received";
254 return false;
255 }
256 *sub_protocol = value;
257 return true;
[email protected]d51365e2013-11-27 10:46:52258}
259
[email protected]69d7a492014-02-19 08:36:32260bool DeflateError(std::string* message, const base::StringPiece& piece) {
261 *message = "Error in permessage-deflate: ";
[email protected]0ecab7892014-03-11 21:15:40262 piece.AppendToString(message);
[email protected]69d7a492014-02-19 08:36:32263 return false;
264}
265
[email protected]0be93922014-01-29 00:42:45266bool ValidatePerMessageDeflateExtension(const WebSocketExtension& extension,
267 std::string* failure_message,
268 WebSocketExtensionParams* params) {
269 static const char kClientPrefix[] = "client_";
270 static const char kServerPrefix[] = "server_";
271 static const char kNoContextTakeover[] = "no_context_takeover";
272 static const char kMaxWindowBits[] = "max_window_bits";
273 const size_t kPrefixLen = arraysize(kClientPrefix) - 1;
274 COMPILE_ASSERT(kPrefixLen == arraysize(kServerPrefix) - 1,
275 the_strings_server_and_client_must_be_the_same_length);
276 typedef std::vector<WebSocketExtension::Parameter> ParameterVector;
277
[email protected]e5760f522014-02-05 12:28:50278 DCHECK_EQ("permessage-deflate", extension.name());
[email protected]0be93922014-01-29 00:42:45279 const ParameterVector& parameters = extension.parameters();
280 std::set<std::string> seen_names;
281 for (ParameterVector::const_iterator it = parameters.begin();
282 it != parameters.end(); ++it) {
283 const std::string& name = it->name();
284 if (seen_names.count(name) != 0) {
[email protected]69d7a492014-02-19 08:36:32285 return DeflateError(
286 failure_message,
287 "Received duplicate permessage-deflate extension parameter " + name);
[email protected]0be93922014-01-29 00:42:45288 }
289 seen_names.insert(name);
290 const std::string client_or_server(name, 0, kPrefixLen);
291 const bool is_client = (client_or_server == kClientPrefix);
292 if (!is_client && client_or_server != kServerPrefix) {
[email protected]69d7a492014-02-19 08:36:32293 return DeflateError(
294 failure_message,
295 "Received an unexpected permessage-deflate extension parameter");
[email protected]0be93922014-01-29 00:42:45296 }
297 const std::string rest(name, kPrefixLen);
298 if (rest == kNoContextTakeover) {
299 if (it->HasValue()) {
[email protected]69d7a492014-02-19 08:36:32300 return DeflateError(failure_message,
301 "Received invalid " + name + " parameter");
[email protected]0be93922014-01-29 00:42:45302 }
303 if (is_client)
304 params->deflate_mode = WebSocketDeflater::DO_NOT_TAKE_OVER_CONTEXT;
305 } else if (rest == kMaxWindowBits) {
[email protected]69d7a492014-02-19 08:36:32306 if (!it->HasValue())
307 return DeflateError(failure_message, name + " must have value");
[email protected]0be93922014-01-29 00:42:45308 int bits = 0;
309 if (!base::StringToInt(it->value(), &bits) || bits < 8 || bits > 15 ||
310 it->value()[0] == '0' ||
311 it->value().find_first_not_of("0123456789") != std::string::npos) {
[email protected]69d7a492014-02-19 08:36:32312 return DeflateError(failure_message,
313 "Received invalid " + name + " parameter");
[email protected]0be93922014-01-29 00:42:45314 }
315 if (is_client)
316 params->client_window_bits = bits;
317 } else {
[email protected]69d7a492014-02-19 08:36:32318 return DeflateError(
319 failure_message,
320 "Received an unexpected permessage-deflate extension parameter");
[email protected]0be93922014-01-29 00:42:45321 }
322 }
323 params->deflate_enabled = true;
324 return true;
325}
326
[email protected]96868202014-01-09 10:38:04327bool ValidateExtensions(const HttpResponseHeaders* headers,
[email protected]d51365e2013-11-27 10:46:52328 const std::vector<std::string>& requested_extensions,
[email protected]96868202014-01-09 10:38:04329 std::string* extensions,
[email protected]0be93922014-01-29 00:42:45330 std::string* failure_message,
331 WebSocketExtensionParams* params) {
[email protected]d51365e2013-11-27 10:46:52332 void* state = NULL;
[email protected]96868202014-01-09 10:38:04333 std::string value;
[email protected]0be93922014-01-29 00:42:45334 std::vector<std::string> accepted_extensions;
335 // TODO(ricea): If adding support for additional extensions, generalise this
336 // code.
337 bool seen_permessage_deflate = false;
[email protected]d51365e2013-11-27 10:46:52338 while (headers->EnumerateHeader(
[email protected]e5760f522014-02-05 12:28:50339 &state, websockets::kSecWebSocketExtensions, &value)) {
[email protected]96868202014-01-09 10:38:04340 WebSocketExtensionParser parser;
341 parser.Parse(value);
342 if (parser.has_error()) {
343 // TODO(yhirano) Set appropriate failure message.
344 *failure_message =
345 "'Sec-WebSocket-Extensions' header value is "
346 "rejected by the parser: " +
347 value;
348 return false;
349 }
[email protected]0be93922014-01-29 00:42:45350 if (parser.extension().name() == "permessage-deflate") {
351 if (seen_permessage_deflate) {
352 *failure_message = "Received duplicate permessage-deflate response";
353 return false;
354 }
355 seen_permessage_deflate = true;
356 if (!ValidatePerMessageDeflateExtension(
[email protected]e5760f522014-02-05 12:28:50357 parser.extension(), failure_message, params))
[email protected]0be93922014-01-29 00:42:45358 return false;
359 } else {
360 *failure_message =
361 "Found an unsupported extension '" +
362 parser.extension().name() +
363 "' in 'Sec-WebSocket-Extensions' header";
364 return false;
365 }
366 accepted_extensions.push_back(value);
[email protected]d51365e2013-11-27 10:46:52367 }
[email protected]0be93922014-01-29 00:42:45368 *extensions = JoinString(accepted_extensions, ", ");
[email protected]d51365e2013-11-27 10:46:52369 return true;
370}
371
372} // namespace
373
374WebSocketBasicHandshakeStream::WebSocketBasicHandshakeStream(
375 scoped_ptr<ClientSocketHandle> connection,
[email protected]cd48ed12014-01-22 14:34:22376 WebSocketStream::ConnectDelegate* connect_delegate,
[email protected]d51365e2013-11-27 10:46:52377 bool using_proxy,
378 std::vector<std::string> requested_sub_protocols,
[email protected]8aba0172014-07-03 12:09:53379 std::vector<std::string> requested_extensions,
380 std::string* failure_message)
[email protected]d51365e2013-11-27 10:46:52381 : state_(connection.release(), using_proxy),
[email protected]cd48ed12014-01-22 14:34:22382 connect_delegate_(connect_delegate),
[email protected]d51365e2013-11-27 10:46:52383 http_response_info_(NULL),
384 requested_sub_protocols_(requested_sub_protocols),
[email protected]8aba0172014-07-03 12:09:53385 requested_extensions_(requested_extensions),
386 failure_message_(failure_message) {
387 DCHECK(connect_delegate);
388 DCHECK(failure_message);
389}
[email protected]d51365e2013-11-27 10:46:52390
391WebSocketBasicHandshakeStream::~WebSocketBasicHandshakeStream() {}
392
393int WebSocketBasicHandshakeStream::InitializeStream(
394 const HttpRequestInfo* request_info,
395 RequestPriority priority,
396 const BoundNetLog& net_log,
397 const CompletionCallback& callback) {
[email protected]cd48ed12014-01-22 14:34:22398 url_ = request_info->url;
[email protected]d51365e2013-11-27 10:46:52399 state_.Initialize(request_info, priority, net_log, callback);
400 return OK;
401}
402
403int WebSocketBasicHandshakeStream::SendRequest(
404 const HttpRequestHeaders& headers,
405 HttpResponseInfo* response,
406 const CompletionCallback& callback) {
407 DCHECK(!headers.HasHeader(websockets::kSecWebSocketKey));
408 DCHECK(!headers.HasHeader(websockets::kSecWebSocketProtocol));
409 DCHECK(!headers.HasHeader(websockets::kSecWebSocketExtensions));
410 DCHECK(headers.HasHeader(HttpRequestHeaders::kOrigin));
411 DCHECK(headers.HasHeader(websockets::kUpgrade));
412 DCHECK(headers.HasHeader(HttpRequestHeaders::kConnection));
413 DCHECK(headers.HasHeader(websockets::kSecWebSocketVersion));
414 DCHECK(parser());
415
416 http_response_info_ = response;
417
418 // Create a copy of the headers object, so that we can add the
419 // Sec-WebSockey-Key header.
420 HttpRequestHeaders enriched_headers;
421 enriched_headers.CopyFrom(headers);
[email protected]a31ecc02013-12-05 08:30:55422 std::string handshake_challenge;
423 if (handshake_challenge_for_testing_) {
424 handshake_challenge = *handshake_challenge_for_testing_;
425 handshake_challenge_for_testing_.reset();
426 } else {
427 handshake_challenge = GenerateHandshakeChallenge();
428 }
[email protected]d51365e2013-11-27 10:46:52429 enriched_headers.SetHeader(websockets::kSecWebSocketKey, handshake_challenge);
430
[email protected]d51365e2013-11-27 10:46:52431 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketExtensions,
432 requested_extensions_,
433 &enriched_headers);
[email protected]0be93922014-01-29 00:42:45434 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketProtocol,
435 requested_sub_protocols_,
436 &enriched_headers);
[email protected]d51365e2013-11-27 10:46:52437
438 ComputeSecWebSocketAccept(handshake_challenge,
439 &handshake_challenge_response_);
440
[email protected]cd48ed12014-01-22 14:34:22441 DCHECK(connect_delegate_);
442 scoped_ptr<WebSocketHandshakeRequestInfo> request(
443 new WebSocketHandshakeRequestInfo(url_, base::Time::Now()));
444 request->headers.CopyFrom(enriched_headers);
445 connect_delegate_->OnStartOpeningHandshake(request.Pass());
446
[email protected]d51365e2013-11-27 10:46:52447 return parser()->SendRequest(
448 state_.GenerateRequestLine(), enriched_headers, response, callback);
449}
450
451int WebSocketBasicHandshakeStream::ReadResponseHeaders(
452 const CompletionCallback& callback) {
453 // HttpStreamParser uses a weak pointer when reading from the
454 // socket, so it won't be called back after being destroyed. The
455 // HttpStreamParser is owned by HttpBasicState which is owned by this object,
456 // so this use of base::Unretained() is safe.
457 int rv = parser()->ReadResponseHeaders(
458 base::Bind(&WebSocketBasicHandshakeStream::ReadResponseHeadersCallback,
459 base::Unretained(this),
460 callback));
[email protected]cd48ed12014-01-22 14:34:22461 if (rv == ERR_IO_PENDING)
462 return rv;
yhirano27b2b572014-10-30 11:23:44463 bool is_redirect = false;
464 return ValidateResponse(rv, &is_redirect);
[email protected]d51365e2013-11-27 10:46:52465}
466
[email protected]d51365e2013-11-27 10:46:52467int WebSocketBasicHandshakeStream::ReadResponseBody(
468 IOBuffer* buf,
469 int buf_len,
470 const CompletionCallback& callback) {
471 return parser()->ReadResponseBody(buf, buf_len, callback);
472}
473
474void WebSocketBasicHandshakeStream::Close(bool not_reusable) {
475 // This class ignores the value of |not_reusable| and never lets the socket be
476 // re-used.
477 if (parser())
478 parser()->Close(true);
479}
480
481bool WebSocketBasicHandshakeStream::IsResponseBodyComplete() const {
482 return parser()->IsResponseBodyComplete();
483}
484
485bool WebSocketBasicHandshakeStream::CanFindEndOfResponse() const {
486 return parser() && parser()->CanFindEndOfResponse();
487}
488
489bool WebSocketBasicHandshakeStream::IsConnectionReused() const {
490 return parser()->IsConnectionReused();
491}
492
493void WebSocketBasicHandshakeStream::SetConnectionReused() {
494 parser()->SetConnectionReused();
495}
496
497bool WebSocketBasicHandshakeStream::IsConnectionReusable() const {
498 return false;
499}
500
[email protected]bc92bc972013-12-13 08:32:59501int64 WebSocketBasicHandshakeStream::GetTotalReceivedBytes() const {
502 return 0;
503}
504
[email protected]d51365e2013-11-27 10:46:52505bool WebSocketBasicHandshakeStream::GetLoadTimingInfo(
506 LoadTimingInfo* load_timing_info) const {
507 return state_.connection()->GetLoadTimingInfo(IsConnectionReused(),
508 load_timing_info);
509}
510
511void WebSocketBasicHandshakeStream::GetSSLInfo(SSLInfo* ssl_info) {
512 parser()->GetSSLInfo(ssl_info);
513}
514
515void WebSocketBasicHandshakeStream::GetSSLCertRequestInfo(
516 SSLCertRequestInfo* cert_request_info) {
517 parser()->GetSSLCertRequestInfo(cert_request_info);
518}
519
520bool WebSocketBasicHandshakeStream::IsSpdyHttpStream() const { return false; }
521
522void WebSocketBasicHandshakeStream::Drain(HttpNetworkSession* session) {
523 HttpResponseBodyDrainer* drainer = new HttpResponseBodyDrainer(this);
524 drainer->Start(session);
525 // |drainer| will delete itself.
526}
527
528void WebSocketBasicHandshakeStream::SetPriority(RequestPriority priority) {
529 // TODO(ricea): See TODO comment in HttpBasicStream::SetPriority(). If it is
530 // gone, then copy whatever has happened there over here.
531}
532
533scoped_ptr<WebSocketStream> WebSocketBasicHandshakeStream::Upgrade() {
[email protected]d51365e2013-11-27 10:46:52534 // The HttpStreamParser object has a pointer to our ClientSocketHandle. Make
535 // sure it does not touch it again before it is destroyed.
536 state_.DeleteParser();
[email protected]654866142014-06-24 22:53:31537 WebSocketTransportClientSocketPool::UnlockEndpoint(state_.connection());
[email protected]0be93922014-01-29 00:42:45538 scoped_ptr<WebSocketStream> basic_stream(
[email protected]d51365e2013-11-27 10:46:52539 new WebSocketBasicStream(state_.ReleaseConnection(),
540 state_.read_buf(),
541 sub_protocol_,
542 extensions_));
[email protected]0be93922014-01-29 00:42:45543 DCHECK(extension_params_.get());
544 if (extension_params_->deflate_enabled) {
[email protected]9c50b042014-04-28 06:40:15545 UMA_HISTOGRAM_ENUMERATION(
546 "Net.WebSocket.DeflateMode",
547 extension_params_->deflate_mode,
548 WebSocketDeflater::NUM_CONTEXT_TAKEOVER_MODE_TYPES);
549
[email protected]0be93922014-01-29 00:42:45550 return scoped_ptr<WebSocketStream>(
551 new WebSocketDeflateStream(basic_stream.Pass(),
552 extension_params_->deflate_mode,
553 extension_params_->client_window_bits,
554 scoped_ptr<WebSocketDeflatePredictor>(
555 new WebSocketDeflatePredictorImpl)));
556 } else {
557 return basic_stream.Pass();
558 }
[email protected]d51365e2013-11-27 10:46:52559}
560
[email protected]a31ecc02013-12-05 08:30:55561void WebSocketBasicHandshakeStream::SetWebSocketKeyForTesting(
562 const std::string& key) {
563 handshake_challenge_for_testing_.reset(new std::string(key));
564}
565
[email protected]d51365e2013-11-27 10:46:52566void WebSocketBasicHandshakeStream::ReadResponseHeadersCallback(
567 const CompletionCallback& callback,
568 int result) {
yhirano27b2b572014-10-30 11:23:44569 bool is_redirect = false;
570 int rv = ValidateResponse(result, &is_redirect);
571
572 // TODO(yhirano): Simplify this statement once http://crbug.com/399535 is
573 // fixed.
574 switch (rv) {
575 case OK:
576 RunCallbackWithOk(callback, rv);
577 break;
578 case ERR_INVALID_RESPONSE:
579 if (is_redirect)
580 RunCallbackWithInvalidResponseCausedByRedirect(callback, rv);
581 else
582 RunCallbackWithInvalidResponse(callback, rv);
583 break;
584 default:
585 RunCallback(callback, rv);
586 break;
587 }
[email protected]d51365e2013-11-27 10:46:52588}
589
[email protected]cd48ed12014-01-22 14:34:22590void WebSocketBasicHandshakeStream::OnFinishOpeningHandshake() {
[email protected]cd48ed12014-01-22 14:34:22591 DCHECK(http_response_info_);
[email protected]e69c1cd2014-07-29 07:42:29592 WebSocketDispatchOnFinishOpeningHandshake(connect_delegate_,
593 url_,
594 http_response_info_->headers,
595 http_response_info_->response_time);
[email protected]cd48ed12014-01-22 14:34:22596}
597
yhirano27b2b572014-10-30 11:23:44598int WebSocketBasicHandshakeStream::ValidateResponse(int rv,
599 bool* is_redirect) {
[email protected]d51365e2013-11-27 10:46:52600 DCHECK(http_response_info_);
yhirano27b2b572014-10-30 11:23:44601 *is_redirect = false;
[email protected]f7e98ca2014-06-19 12:05:43602 // Most net errors happen during connection, so they are not seen by this
603 // method. The histogram for error codes is created in
604 // Delegate::OnResponseStarted in websocket_stream.cc instead.
[email protected]e5760f522014-02-05 12:28:50605 if (rv >= 0) {
[email protected]f7e98ca2014-06-19 12:05:43606 const HttpResponseHeaders* headers = http_response_info_->headers.get();
607 const int response_code = headers->response_code();
yhirano27b2b572014-10-30 11:23:44608 *is_redirect = HttpResponseHeaders::IsRedirectResponseCode(response_code);
[email protected]f7e98ca2014-06-19 12:05:43609 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.WebSocket.ResponseCode", response_code);
610 switch (response_code) {
[email protected]e5760f522014-02-05 12:28:50611 case HTTP_SWITCHING_PROTOCOLS:
612 OnFinishOpeningHandshake();
613 return ValidateUpgradeResponse(headers);
[email protected]d51365e2013-11-27 10:46:52614
[email protected]e5760f522014-02-05 12:28:50615 // We need to pass these through for authentication to work.
616 case HTTP_UNAUTHORIZED:
617 case HTTP_PROXY_AUTHENTICATION_REQUIRED:
618 return OK;
[email protected]d51365e2013-11-27 10:46:52619
[email protected]e5760f522014-02-05 12:28:50620 // Other status codes are potentially risky (see the warnings in the
621 // WHATWG WebSocket API spec) and so are dropped by default.
622 default:
[email protected]aeb640d2014-02-21 11:03:18623 // A WebSocket server cannot be using HTTP/0.9, so if we see version
624 // 0.9, it means the response was garbage.
625 // Reporting "Unexpected response code: 200" in this case is not
626 // helpful, so use a different error message.
627 if (headers->GetHttpVersion() == HttpVersion(0, 9)) {
[email protected]8aba0172014-07-03 12:09:53628 set_failure_message(
629 "Error during WebSocket handshake: Invalid status line");
[email protected]aeb640d2014-02-21 11:03:18630 } else {
[email protected]8aba0172014-07-03 12:09:53631 set_failure_message(base::StringPrintf(
[email protected]aeb640d2014-02-21 11:03:18632 "Error during WebSocket handshake: Unexpected response code: %d",
[email protected]8aba0172014-07-03 12:09:53633 headers->response_code()));
[email protected]aeb640d2014-02-21 11:03:18634 }
[email protected]e5760f522014-02-05 12:28:50635 OnFinishOpeningHandshake();
636 return ERR_INVALID_RESPONSE;
637 }
638 } else {
[email protected]3efc08f2014-02-07 09:33:34639 if (rv == ERR_EMPTY_RESPONSE) {
[email protected]8aba0172014-07-03 12:09:53640 set_failure_message(
641 "Connection closed before receiving a handshake response");
[email protected]3efc08f2014-02-07 09:33:34642 return rv;
643 }
[email protected]8aba0172014-07-03 12:09:53644 set_failure_message(std::string("Error during WebSocket handshake: ") +
645 ErrorToString(rv));
[email protected]e5760f522014-02-05 12:28:50646 OnFinishOpeningHandshake();
647 return rv;
[email protected]d51365e2013-11-27 10:46:52648 }
649}
650
651int WebSocketBasicHandshakeStream::ValidateUpgradeResponse(
[email protected]e5760f522014-02-05 12:28:50652 const HttpResponseHeaders* headers) {
[email protected]0be93922014-01-29 00:42:45653 extension_params_.reset(new WebSocketExtensionParams);
[email protected]8aba0172014-07-03 12:09:53654 std::string failure_message;
655 if (ValidateUpgrade(headers, &failure_message) &&
656 ValidateSecWebSocketAccept(
657 headers, handshake_challenge_response_, &failure_message) &&
658 ValidateConnection(headers, &failure_message) &&
[email protected]e5760f522014-02-05 12:28:50659 ValidateSubProtocol(headers,
[email protected]96868202014-01-09 10:38:04660 requested_sub_protocols_,
661 &sub_protocol_,
[email protected]8aba0172014-07-03 12:09:53662 &failure_message) &&
[email protected]e5760f522014-02-05 12:28:50663 ValidateExtensions(headers,
[email protected]96868202014-01-09 10:38:04664 requested_extensions_,
665 &extensions_,
[email protected]8aba0172014-07-03 12:09:53666 &failure_message,
[email protected]0be93922014-01-29 00:42:45667 extension_params_.get())) {
[email protected]d51365e2013-11-27 10:46:52668 return OK;
669 }
[email protected]8aba0172014-07-03 12:09:53670 set_failure_message("Error during WebSocket handshake: " + failure_message);
[email protected]d51365e2013-11-27 10:46:52671 return ERR_INVALID_RESPONSE;
672}
673
[email protected]8aba0172014-07-03 12:09:53674void WebSocketBasicHandshakeStream::set_failure_message(
675 const std::string& failure_message) {
676 *failure_message_ = failure_message;
677}
678
[email protected]d51365e2013-11-27 10:46:52679} // namespace net