blob: a19de55f6c07f33c4d4fce501edf31ded73efee7 [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"
16#include "base/containers/hash_tables.h"
[email protected]9c50b042014-04-28 06:40:1517#include "base/metrics/histogram.h"
[email protected]f7e98ca2014-06-19 12:05:4318#include "base/metrics/sparse_histogram.h"
[email protected]d51365e2013-11-27 10:46:5219#include "base/stl_util.h"
[email protected]0be93922014-01-29 00:42:4520#include "base/strings/string_number_conversions.h"
[email protected]69d7a492014-02-19 08:36:3221#include "base/strings/string_piece.h"
[email protected]d51365e2013-11-27 10:46:5222#include "base/strings/string_util.h"
[email protected]96868202014-01-09 10:38:0423#include "base/strings/stringprintf.h"
[email protected]cd48ed12014-01-22 14:34:2224#include "base/time/time.h"
[email protected]d51365e2013-11-27 10:46:5225#include "crypto/random.h"
26#include "net/http/http_request_headers.h"
27#include "net/http/http_request_info.h"
28#include "net/http/http_response_body_drainer.h"
29#include "net/http/http_response_headers.h"
30#include "net/http/http_status_code.h"
31#include "net/http/http_stream_parser.h"
32#include "net/socket/client_socket_handle.h"
[email protected]654866142014-06-24 22:53:3133#include "net/socket/websocket_transport_client_socket_pool.h"
[email protected]d51365e2013-11-27 10:46:5234#include "net/websockets/websocket_basic_stream.h"
[email protected]0be93922014-01-29 00:42:4535#include "net/websockets/websocket_deflate_predictor.h"
36#include "net/websockets/websocket_deflate_predictor_impl.h"
37#include "net/websockets/websocket_deflate_stream.h"
38#include "net/websockets/websocket_deflater.h"
[email protected]96868202014-01-09 10:38:0439#include "net/websockets/websocket_extension_parser.h"
[email protected]d51365e2013-11-27 10:46:5240#include "net/websockets/websocket_handshake_constants.h"
41#include "net/websockets/websocket_handshake_handler.h"
[email protected]cd48ed12014-01-22 14:34:2242#include "net/websockets/websocket_handshake_request_info.h"
43#include "net/websockets/websocket_handshake_response_info.h"
[email protected]d51365e2013-11-27 10:46:5244#include "net/websockets/websocket_stream.h"
45
46namespace net {
[email protected]0be93922014-01-29 00:42:4547
48// TODO(ricea): If more extensions are added, replace this with a more general
49// mechanism.
50struct WebSocketExtensionParams {
51 WebSocketExtensionParams()
52 : deflate_enabled(false),
53 client_window_bits(15),
54 deflate_mode(WebSocketDeflater::TAKE_OVER_CONTEXT) {}
55
56 bool deflate_enabled;
57 int client_window_bits;
58 WebSocketDeflater::ContextTakeOverMode deflate_mode;
59};
60
[email protected]d51365e2013-11-27 10:46:5261namespace {
62
[email protected]96868202014-01-09 10:38:0463enum GetHeaderResult {
64 GET_HEADER_OK,
65 GET_HEADER_MISSING,
66 GET_HEADER_MULTIPLE,
67};
68
69std::string MissingHeaderMessage(const std::string& header_name) {
70 return std::string("'") + header_name + "' header is missing";
71}
72
73std::string MultipleHeaderValuesMessage(const std::string& header_name) {
74 return
75 std::string("'") +
76 header_name +
77 "' header must not appear more than once in a response";
78}
79
[email protected]d51365e2013-11-27 10:46:5280std::string GenerateHandshakeChallenge() {
81 std::string raw_challenge(websockets::kRawChallengeLength, '\0');
82 crypto::RandBytes(string_as_array(&raw_challenge), raw_challenge.length());
83 std::string encoded_challenge;
[email protected]33fca122013-12-11 01:48:5084 base::Base64Encode(raw_challenge, &encoded_challenge);
[email protected]d51365e2013-11-27 10:46:5285 return encoded_challenge;
86}
87
88void AddVectorHeaderIfNonEmpty(const char* name,
89 const std::vector<std::string>& value,
90 HttpRequestHeaders* headers) {
91 if (value.empty())
92 return;
93 headers->SetHeader(name, JoinString(value, ", "));
94}
95
[email protected]96868202014-01-09 10:38:0496GetHeaderResult GetSingleHeaderValue(const HttpResponseHeaders* headers,
97 const base::StringPiece& name,
98 std::string* value) {
[email protected]d51365e2013-11-27 10:46:5299 void* state = NULL;
[email protected]96868202014-01-09 10:38:04100 size_t num_values = 0;
101 std::string temp_value;
102 while (headers->EnumerateHeader(&state, name, &temp_value)) {
103 if (++num_values > 1)
104 return GET_HEADER_MULTIPLE;
105 *value = temp_value;
[email protected]d51365e2013-11-27 10:46:52106 }
[email protected]96868202014-01-09 10:38:04107 return num_values > 0 ? GET_HEADER_OK : GET_HEADER_MISSING;
108}
109
110bool ValidateHeaderHasSingleValue(GetHeaderResult result,
111 const std::string& header_name,
112 std::string* failure_message) {
113 if (result == GET_HEADER_MISSING) {
114 *failure_message = MissingHeaderMessage(header_name);
115 return false;
116 }
117 if (result == GET_HEADER_MULTIPLE) {
118 *failure_message = MultipleHeaderValuesMessage(header_name);
119 return false;
120 }
121 DCHECK_EQ(result, GET_HEADER_OK);
122 return true;
123}
124
125bool ValidateUpgrade(const HttpResponseHeaders* headers,
126 std::string* failure_message) {
127 std::string value;
128 GetHeaderResult result =
129 GetSingleHeaderValue(headers, websockets::kUpgrade, &value);
130 if (!ValidateHeaderHasSingleValue(result,
131 websockets::kUpgrade,
132 failure_message)) {
133 return false;
134 }
135
136 if (!LowerCaseEqualsASCII(value, websockets::kWebSocketLowercase)) {
137 *failure_message =
138 "'Upgrade' header value is not 'WebSocket': " + value;
139 return false;
140 }
141 return true;
142}
143
144bool ValidateSecWebSocketAccept(const HttpResponseHeaders* headers,
145 const std::string& expected,
146 std::string* failure_message) {
147 std::string actual;
148 GetHeaderResult result =
149 GetSingleHeaderValue(headers, websockets::kSecWebSocketAccept, &actual);
150 if (!ValidateHeaderHasSingleValue(result,
151 websockets::kSecWebSocketAccept,
152 failure_message)) {
153 return false;
154 }
155
156 if (expected != actual) {
157 *failure_message = "Incorrect 'Sec-WebSocket-Accept' header value";
158 return false;
159 }
160 return true;
161}
162
163bool ValidateConnection(const HttpResponseHeaders* headers,
164 std::string* failure_message) {
165 // Connection header is permitted to contain other tokens.
166 if (!headers->HasHeader(HttpRequestHeaders::kConnection)) {
167 *failure_message = MissingHeaderMessage(HttpRequestHeaders::kConnection);
168 return false;
169 }
170 if (!headers->HasHeaderValue(HttpRequestHeaders::kConnection,
171 websockets::kUpgrade)) {
172 *failure_message = "'Connection' header value must contain 'Upgrade'";
173 return false;
174 }
175 return true;
[email protected]d51365e2013-11-27 10:46:52176}
177
178bool ValidateSubProtocol(
[email protected]96868202014-01-09 10:38:04179 const HttpResponseHeaders* headers,
[email protected]d51365e2013-11-27 10:46:52180 const std::vector<std::string>& requested_sub_protocols,
[email protected]96868202014-01-09 10:38:04181 std::string* sub_protocol,
182 std::string* failure_message) {
[email protected]d51365e2013-11-27 10:46:52183 void* state = NULL;
[email protected]96868202014-01-09 10:38:04184 std::string value;
[email protected]d51365e2013-11-27 10:46:52185 base::hash_set<std::string> requested_set(requested_sub_protocols.begin(),
186 requested_sub_protocols.end());
[email protected]96868202014-01-09 10:38:04187 int count = 0;
188 bool has_multiple_protocols = false;
189 bool has_invalid_protocol = false;
[email protected]d51365e2013-11-27 10:46:52190
[email protected]96868202014-01-09 10:38:04191 while (!has_invalid_protocol || !has_multiple_protocols) {
192 std::string temp_value;
193 if (!headers->EnumerateHeader(
194 &state, websockets::kSecWebSocketProtocol, &temp_value))
195 break;
196 value = temp_value;
197 if (requested_set.count(value) == 0)
198 has_invalid_protocol = true;
199 if (++count > 1)
200 has_multiple_protocols = true;
[email protected]d51365e2013-11-27 10:46:52201 }
[email protected]96868202014-01-09 10:38:04202
203 if (has_multiple_protocols) {
204 *failure_message =
205 MultipleHeaderValuesMessage(websockets::kSecWebSocketProtocol);
206 return false;
207 } else if (count > 0 && requested_sub_protocols.size() == 0) {
208 *failure_message =
209 std::string("Response must not include 'Sec-WebSocket-Protocol' "
210 "header if not present in request: ")
211 + value;
212 return false;
213 } else if (has_invalid_protocol) {
214 *failure_message =
215 "'Sec-WebSocket-Protocol' header value '" +
216 value +
217 "' in response does not match any of sent values";
218 return false;
219 } else if (requested_sub_protocols.size() > 0 && count == 0) {
220 *failure_message =
221 "Sent non-empty 'Sec-WebSocket-Protocol' header "
222 "but no response was received";
223 return false;
224 }
225 *sub_protocol = value;
226 return true;
[email protected]d51365e2013-11-27 10:46:52227}
228
[email protected]69d7a492014-02-19 08:36:32229bool DeflateError(std::string* message, const base::StringPiece& piece) {
230 *message = "Error in permessage-deflate: ";
[email protected]0ecab7892014-03-11 21:15:40231 piece.AppendToString(message);
[email protected]69d7a492014-02-19 08:36:32232 return false;
233}
234
[email protected]0be93922014-01-29 00:42:45235bool ValidatePerMessageDeflateExtension(const WebSocketExtension& extension,
236 std::string* failure_message,
237 WebSocketExtensionParams* params) {
238 static const char kClientPrefix[] = "client_";
239 static const char kServerPrefix[] = "server_";
240 static const char kNoContextTakeover[] = "no_context_takeover";
241 static const char kMaxWindowBits[] = "max_window_bits";
242 const size_t kPrefixLen = arraysize(kClientPrefix) - 1;
243 COMPILE_ASSERT(kPrefixLen == arraysize(kServerPrefix) - 1,
244 the_strings_server_and_client_must_be_the_same_length);
245 typedef std::vector<WebSocketExtension::Parameter> ParameterVector;
246
[email protected]e5760f522014-02-05 12:28:50247 DCHECK_EQ("permessage-deflate", extension.name());
[email protected]0be93922014-01-29 00:42:45248 const ParameterVector& parameters = extension.parameters();
249 std::set<std::string> seen_names;
250 for (ParameterVector::const_iterator it = parameters.begin();
251 it != parameters.end(); ++it) {
252 const std::string& name = it->name();
253 if (seen_names.count(name) != 0) {
[email protected]69d7a492014-02-19 08:36:32254 return DeflateError(
255 failure_message,
256 "Received duplicate permessage-deflate extension parameter " + name);
[email protected]0be93922014-01-29 00:42:45257 }
258 seen_names.insert(name);
259 const std::string client_or_server(name, 0, kPrefixLen);
260 const bool is_client = (client_or_server == kClientPrefix);
261 if (!is_client && client_or_server != kServerPrefix) {
[email protected]69d7a492014-02-19 08:36:32262 return DeflateError(
263 failure_message,
264 "Received an unexpected permessage-deflate extension parameter");
[email protected]0be93922014-01-29 00:42:45265 }
266 const std::string rest(name, kPrefixLen);
267 if (rest == kNoContextTakeover) {
268 if (it->HasValue()) {
[email protected]69d7a492014-02-19 08:36:32269 return DeflateError(failure_message,
270 "Received invalid " + name + " parameter");
[email protected]0be93922014-01-29 00:42:45271 }
272 if (is_client)
273 params->deflate_mode = WebSocketDeflater::DO_NOT_TAKE_OVER_CONTEXT;
274 } else if (rest == kMaxWindowBits) {
[email protected]69d7a492014-02-19 08:36:32275 if (!it->HasValue())
276 return DeflateError(failure_message, name + " must have value");
[email protected]0be93922014-01-29 00:42:45277 int bits = 0;
278 if (!base::StringToInt(it->value(), &bits) || bits < 8 || bits > 15 ||
279 it->value()[0] == '0' ||
280 it->value().find_first_not_of("0123456789") != std::string::npos) {
[email protected]69d7a492014-02-19 08:36:32281 return DeflateError(failure_message,
282 "Received invalid " + name + " parameter");
[email protected]0be93922014-01-29 00:42:45283 }
284 if (is_client)
285 params->client_window_bits = bits;
286 } else {
[email protected]69d7a492014-02-19 08:36:32287 return DeflateError(
288 failure_message,
289 "Received an unexpected permessage-deflate extension parameter");
[email protected]0be93922014-01-29 00:42:45290 }
291 }
292 params->deflate_enabled = true;
293 return true;
294}
295
[email protected]96868202014-01-09 10:38:04296bool ValidateExtensions(const HttpResponseHeaders* headers,
[email protected]d51365e2013-11-27 10:46:52297 const std::vector<std::string>& requested_extensions,
[email protected]96868202014-01-09 10:38:04298 std::string* extensions,
[email protected]0be93922014-01-29 00:42:45299 std::string* failure_message,
300 WebSocketExtensionParams* params) {
[email protected]d51365e2013-11-27 10:46:52301 void* state = NULL;
[email protected]96868202014-01-09 10:38:04302 std::string value;
[email protected]0be93922014-01-29 00:42:45303 std::vector<std::string> accepted_extensions;
304 // TODO(ricea): If adding support for additional extensions, generalise this
305 // code.
306 bool seen_permessage_deflate = false;
[email protected]d51365e2013-11-27 10:46:52307 while (headers->EnumerateHeader(
[email protected]e5760f522014-02-05 12:28:50308 &state, websockets::kSecWebSocketExtensions, &value)) {
[email protected]96868202014-01-09 10:38:04309 WebSocketExtensionParser parser;
310 parser.Parse(value);
311 if (parser.has_error()) {
312 // TODO(yhirano) Set appropriate failure message.
313 *failure_message =
314 "'Sec-WebSocket-Extensions' header value is "
315 "rejected by the parser: " +
316 value;
317 return false;
318 }
[email protected]0be93922014-01-29 00:42:45319 if (parser.extension().name() == "permessage-deflate") {
320 if (seen_permessage_deflate) {
321 *failure_message = "Received duplicate permessage-deflate response";
322 return false;
323 }
324 seen_permessage_deflate = true;
325 if (!ValidatePerMessageDeflateExtension(
[email protected]e5760f522014-02-05 12:28:50326 parser.extension(), failure_message, params))
[email protected]0be93922014-01-29 00:42:45327 return false;
328 } else {
329 *failure_message =
330 "Found an unsupported extension '" +
331 parser.extension().name() +
332 "' in 'Sec-WebSocket-Extensions' header";
333 return false;
334 }
335 accepted_extensions.push_back(value);
[email protected]d51365e2013-11-27 10:46:52336 }
[email protected]0be93922014-01-29 00:42:45337 *extensions = JoinString(accepted_extensions, ", ");
[email protected]d51365e2013-11-27 10:46:52338 return true;
339}
340
341} // namespace
342
343WebSocketBasicHandshakeStream::WebSocketBasicHandshakeStream(
344 scoped_ptr<ClientSocketHandle> connection,
[email protected]cd48ed12014-01-22 14:34:22345 WebSocketStream::ConnectDelegate* connect_delegate,
[email protected]d51365e2013-11-27 10:46:52346 bool using_proxy,
347 std::vector<std::string> requested_sub_protocols,
348 std::vector<std::string> requested_extensions)
349 : state_(connection.release(), using_proxy),
[email protected]cd48ed12014-01-22 14:34:22350 connect_delegate_(connect_delegate),
[email protected]d51365e2013-11-27 10:46:52351 http_response_info_(NULL),
352 requested_sub_protocols_(requested_sub_protocols),
353 requested_extensions_(requested_extensions) {}
354
355WebSocketBasicHandshakeStream::~WebSocketBasicHandshakeStream() {}
356
357int WebSocketBasicHandshakeStream::InitializeStream(
358 const HttpRequestInfo* request_info,
359 RequestPriority priority,
360 const BoundNetLog& net_log,
361 const CompletionCallback& callback) {
[email protected]cd48ed12014-01-22 14:34:22362 url_ = request_info->url;
[email protected]d51365e2013-11-27 10:46:52363 state_.Initialize(request_info, priority, net_log, callback);
364 return OK;
365}
366
367int WebSocketBasicHandshakeStream::SendRequest(
368 const HttpRequestHeaders& headers,
369 HttpResponseInfo* response,
370 const CompletionCallback& callback) {
371 DCHECK(!headers.HasHeader(websockets::kSecWebSocketKey));
372 DCHECK(!headers.HasHeader(websockets::kSecWebSocketProtocol));
373 DCHECK(!headers.HasHeader(websockets::kSecWebSocketExtensions));
374 DCHECK(headers.HasHeader(HttpRequestHeaders::kOrigin));
375 DCHECK(headers.HasHeader(websockets::kUpgrade));
376 DCHECK(headers.HasHeader(HttpRequestHeaders::kConnection));
377 DCHECK(headers.HasHeader(websockets::kSecWebSocketVersion));
378 DCHECK(parser());
379
380 http_response_info_ = response;
381
382 // Create a copy of the headers object, so that we can add the
383 // Sec-WebSockey-Key header.
384 HttpRequestHeaders enriched_headers;
385 enriched_headers.CopyFrom(headers);
[email protected]a31ecc02013-12-05 08:30:55386 std::string handshake_challenge;
387 if (handshake_challenge_for_testing_) {
388 handshake_challenge = *handshake_challenge_for_testing_;
389 handshake_challenge_for_testing_.reset();
390 } else {
391 handshake_challenge = GenerateHandshakeChallenge();
392 }
[email protected]d51365e2013-11-27 10:46:52393 enriched_headers.SetHeader(websockets::kSecWebSocketKey, handshake_challenge);
394
[email protected]d51365e2013-11-27 10:46:52395 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketExtensions,
396 requested_extensions_,
397 &enriched_headers);
[email protected]0be93922014-01-29 00:42:45398 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketProtocol,
399 requested_sub_protocols_,
400 &enriched_headers);
[email protected]d51365e2013-11-27 10:46:52401
402 ComputeSecWebSocketAccept(handshake_challenge,
403 &handshake_challenge_response_);
404
[email protected]cd48ed12014-01-22 14:34:22405 DCHECK(connect_delegate_);
406 scoped_ptr<WebSocketHandshakeRequestInfo> request(
407 new WebSocketHandshakeRequestInfo(url_, base::Time::Now()));
408 request->headers.CopyFrom(enriched_headers);
409 connect_delegate_->OnStartOpeningHandshake(request.Pass());
410
[email protected]d51365e2013-11-27 10:46:52411 return parser()->SendRequest(
412 state_.GenerateRequestLine(), enriched_headers, response, callback);
413}
414
415int WebSocketBasicHandshakeStream::ReadResponseHeaders(
416 const CompletionCallback& callback) {
417 // HttpStreamParser uses a weak pointer when reading from the
418 // socket, so it won't be called back after being destroyed. The
419 // HttpStreamParser is owned by HttpBasicState which is owned by this object,
420 // so this use of base::Unretained() is safe.
421 int rv = parser()->ReadResponseHeaders(
422 base::Bind(&WebSocketBasicHandshakeStream::ReadResponseHeadersCallback,
423 base::Unretained(this),
424 callback));
[email protected]cd48ed12014-01-22 14:34:22425 if (rv == ERR_IO_PENDING)
426 return rv;
[email protected]e5760f522014-02-05 12:28:50427 return ValidateResponse(rv);
[email protected]d51365e2013-11-27 10:46:52428}
429
[email protected]d51365e2013-11-27 10:46:52430int WebSocketBasicHandshakeStream::ReadResponseBody(
431 IOBuffer* buf,
432 int buf_len,
433 const CompletionCallback& callback) {
434 return parser()->ReadResponseBody(buf, buf_len, callback);
435}
436
437void WebSocketBasicHandshakeStream::Close(bool not_reusable) {
438 // This class ignores the value of |not_reusable| and never lets the socket be
439 // re-used.
440 if (parser())
441 parser()->Close(true);
442}
443
444bool WebSocketBasicHandshakeStream::IsResponseBodyComplete() const {
445 return parser()->IsResponseBodyComplete();
446}
447
448bool WebSocketBasicHandshakeStream::CanFindEndOfResponse() const {
449 return parser() && parser()->CanFindEndOfResponse();
450}
451
452bool WebSocketBasicHandshakeStream::IsConnectionReused() const {
453 return parser()->IsConnectionReused();
454}
455
456void WebSocketBasicHandshakeStream::SetConnectionReused() {
457 parser()->SetConnectionReused();
458}
459
460bool WebSocketBasicHandshakeStream::IsConnectionReusable() const {
461 return false;
462}
463
[email protected]bc92bc972013-12-13 08:32:59464int64 WebSocketBasicHandshakeStream::GetTotalReceivedBytes() const {
465 return 0;
466}
467
[email protected]d51365e2013-11-27 10:46:52468bool WebSocketBasicHandshakeStream::GetLoadTimingInfo(
469 LoadTimingInfo* load_timing_info) const {
470 return state_.connection()->GetLoadTimingInfo(IsConnectionReused(),
471 load_timing_info);
472}
473
474void WebSocketBasicHandshakeStream::GetSSLInfo(SSLInfo* ssl_info) {
475 parser()->GetSSLInfo(ssl_info);
476}
477
478void WebSocketBasicHandshakeStream::GetSSLCertRequestInfo(
479 SSLCertRequestInfo* cert_request_info) {
480 parser()->GetSSLCertRequestInfo(cert_request_info);
481}
482
483bool WebSocketBasicHandshakeStream::IsSpdyHttpStream() const { return false; }
484
485void WebSocketBasicHandshakeStream::Drain(HttpNetworkSession* session) {
486 HttpResponseBodyDrainer* drainer = new HttpResponseBodyDrainer(this);
487 drainer->Start(session);
488 // |drainer| will delete itself.
489}
490
491void WebSocketBasicHandshakeStream::SetPriority(RequestPriority priority) {
492 // TODO(ricea): See TODO comment in HttpBasicStream::SetPriority(). If it is
493 // gone, then copy whatever has happened there over here.
494}
495
496scoped_ptr<WebSocketStream> WebSocketBasicHandshakeStream::Upgrade() {
[email protected]d51365e2013-11-27 10:46:52497 // The HttpStreamParser object has a pointer to our ClientSocketHandle. Make
498 // sure it does not touch it again before it is destroyed.
499 state_.DeleteParser();
[email protected]654866142014-06-24 22:53:31500 WebSocketTransportClientSocketPool::UnlockEndpoint(state_.connection());
[email protected]0be93922014-01-29 00:42:45501 scoped_ptr<WebSocketStream> basic_stream(
[email protected]d51365e2013-11-27 10:46:52502 new WebSocketBasicStream(state_.ReleaseConnection(),
503 state_.read_buf(),
504 sub_protocol_,
505 extensions_));
[email protected]0be93922014-01-29 00:42:45506 DCHECK(extension_params_.get());
507 if (extension_params_->deflate_enabled) {
[email protected]9c50b042014-04-28 06:40:15508 UMA_HISTOGRAM_ENUMERATION(
509 "Net.WebSocket.DeflateMode",
510 extension_params_->deflate_mode,
511 WebSocketDeflater::NUM_CONTEXT_TAKEOVER_MODE_TYPES);
512
[email protected]0be93922014-01-29 00:42:45513 return scoped_ptr<WebSocketStream>(
514 new WebSocketDeflateStream(basic_stream.Pass(),
515 extension_params_->deflate_mode,
516 extension_params_->client_window_bits,
517 scoped_ptr<WebSocketDeflatePredictor>(
518 new WebSocketDeflatePredictorImpl)));
519 } else {
520 return basic_stream.Pass();
521 }
[email protected]d51365e2013-11-27 10:46:52522}
523
[email protected]a31ecc02013-12-05 08:30:55524void WebSocketBasicHandshakeStream::SetWebSocketKeyForTesting(
525 const std::string& key) {
526 handshake_challenge_for_testing_.reset(new std::string(key));
527}
528
[email protected]96868202014-01-09 10:38:04529std::string WebSocketBasicHandshakeStream::GetFailureMessage() const {
530 return failure_message_;
531}
532
[email protected]d51365e2013-11-27 10:46:52533void WebSocketBasicHandshakeStream::ReadResponseHeadersCallback(
534 const CompletionCallback& callback,
535 int result) {
[email protected]e5760f522014-02-05 12:28:50536 callback.Run(ValidateResponse(result));
[email protected]d51365e2013-11-27 10:46:52537}
538
[email protected]cd48ed12014-01-22 14:34:22539void WebSocketBasicHandshakeStream::OnFinishOpeningHandshake() {
540 DCHECK(connect_delegate_);
541 DCHECK(http_response_info_);
542 scoped_refptr<HttpResponseHeaders> headers = http_response_info_->headers;
[email protected]94831522014-02-06 12:05:18543 // If the headers are too large, HttpStreamParser will just not parse them at
544 // all.
545 if (headers) {
546 scoped_ptr<WebSocketHandshakeResponseInfo> response(
547 new WebSocketHandshakeResponseInfo(url_,
548 headers->response_code(),
549 headers->GetStatusText(),
550 headers,
551 http_response_info_->response_time));
552 connect_delegate_->OnFinishOpeningHandshake(response.Pass());
553 }
[email protected]cd48ed12014-01-22 14:34:22554}
555
[email protected]e5760f522014-02-05 12:28:50556int WebSocketBasicHandshakeStream::ValidateResponse(int rv) {
[email protected]d51365e2013-11-27 10:46:52557 DCHECK(http_response_info_);
[email protected]f7e98ca2014-06-19 12:05:43558 // Most net errors happen during connection, so they are not seen by this
559 // method. The histogram for error codes is created in
560 // Delegate::OnResponseStarted in websocket_stream.cc instead.
[email protected]e5760f522014-02-05 12:28:50561 if (rv >= 0) {
[email protected]f7e98ca2014-06-19 12:05:43562 const HttpResponseHeaders* headers = http_response_info_->headers.get();
563 const int response_code = headers->response_code();
564 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.WebSocket.ResponseCode", response_code);
565 switch (response_code) {
[email protected]e5760f522014-02-05 12:28:50566 case HTTP_SWITCHING_PROTOCOLS:
567 OnFinishOpeningHandshake();
568 return ValidateUpgradeResponse(headers);
[email protected]d51365e2013-11-27 10:46:52569
[email protected]e5760f522014-02-05 12:28:50570 // We need to pass these through for authentication to work.
571 case HTTP_UNAUTHORIZED:
572 case HTTP_PROXY_AUTHENTICATION_REQUIRED:
573 return OK;
[email protected]d51365e2013-11-27 10:46:52574
[email protected]e5760f522014-02-05 12:28:50575 // Other status codes are potentially risky (see the warnings in the
576 // WHATWG WebSocket API spec) and so are dropped by default.
577 default:
[email protected]aeb640d2014-02-21 11:03:18578 // A WebSocket server cannot be using HTTP/0.9, so if we see version
579 // 0.9, it means the response was garbage.
580 // Reporting "Unexpected response code: 200" in this case is not
581 // helpful, so use a different error message.
582 if (headers->GetHttpVersion() == HttpVersion(0, 9)) {
583 failure_message_ =
584 "Error during WebSocket handshake: Invalid status line";
585 } else {
586 failure_message_ = base::StringPrintf(
587 "Error during WebSocket handshake: Unexpected response code: %d",
588 headers->response_code());
589 }
[email protected]e5760f522014-02-05 12:28:50590 OnFinishOpeningHandshake();
591 return ERR_INVALID_RESPONSE;
592 }
593 } else {
[email protected]3efc08f2014-02-07 09:33:34594 if (rv == ERR_EMPTY_RESPONSE) {
595 failure_message_ =
596 "Connection closed before receiving a handshake response";
597 return rv;
598 }
[email protected]e5760f522014-02-05 12:28:50599 failure_message_ =
600 std::string("Error during WebSocket handshake: ") + ErrorToString(rv);
601 OnFinishOpeningHandshake();
602 return rv;
[email protected]d51365e2013-11-27 10:46:52603 }
604}
605
606int WebSocketBasicHandshakeStream::ValidateUpgradeResponse(
[email protected]e5760f522014-02-05 12:28:50607 const HttpResponseHeaders* headers) {
[email protected]0be93922014-01-29 00:42:45608 extension_params_.reset(new WebSocketExtensionParams);
[email protected]e5760f522014-02-05 12:28:50609 if (ValidateUpgrade(headers, &failure_message_) &&
610 ValidateSecWebSocketAccept(headers,
[email protected]96868202014-01-09 10:38:04611 handshake_challenge_response_,
612 &failure_message_) &&
[email protected]e5760f522014-02-05 12:28:50613 ValidateConnection(headers, &failure_message_) &&
614 ValidateSubProtocol(headers,
[email protected]96868202014-01-09 10:38:04615 requested_sub_protocols_,
616 &sub_protocol_,
617 &failure_message_) &&
[email protected]e5760f522014-02-05 12:28:50618 ValidateExtensions(headers,
[email protected]96868202014-01-09 10:38:04619 requested_extensions_,
620 &extensions_,
[email protected]0be93922014-01-29 00:42:45621 &failure_message_,
622 extension_params_.get())) {
[email protected]d51365e2013-11-27 10:46:52623 return OK;
624 }
[email protected]96868202014-01-09 10:38:04625 failure_message_ = "Error during WebSocket handshake: " + failure_message_;
[email protected]d51365e2013-11-27 10:46:52626 return ERR_INVALID_RESPONSE;
627}
628
629} // namespace net