blob: 6c5e849996a36a85725f47ed09e437a40b8c8e70 [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]d51365e2013-11-27 10:46:5218#include "base/stl_util.h"
[email protected]0be93922014-01-29 00:42:4519#include "base/strings/string_number_conversions.h"
[email protected]69d7a492014-02-19 08:36:3220#include "base/strings/string_piece.h"
[email protected]d51365e2013-11-27 10:46:5221#include "base/strings/string_util.h"
[email protected]96868202014-01-09 10:38:0422#include "base/strings/stringprintf.h"
[email protected]cd48ed12014-01-22 14:34:2223#include "base/time/time.h"
[email protected]d51365e2013-11-27 10:46:5224#include "crypto/random.h"
25#include "net/http/http_request_headers.h"
26#include "net/http/http_request_info.h"
27#include "net/http/http_response_body_drainer.h"
28#include "net/http/http_response_headers.h"
29#include "net/http/http_status_code.h"
30#include "net/http/http_stream_parser.h"
31#include "net/socket/client_socket_handle.h"
32#include "net/websockets/websocket_basic_stream.h"
[email protected]0be93922014-01-29 00:42:4533#include "net/websockets/websocket_deflate_predictor.h"
34#include "net/websockets/websocket_deflate_predictor_impl.h"
35#include "net/websockets/websocket_deflate_stream.h"
36#include "net/websockets/websocket_deflater.h"
[email protected]96868202014-01-09 10:38:0437#include "net/websockets/websocket_extension_parser.h"
[email protected]d51365e2013-11-27 10:46:5238#include "net/websockets/websocket_handshake_constants.h"
39#include "net/websockets/websocket_handshake_handler.h"
[email protected]cd48ed12014-01-22 14:34:2240#include "net/websockets/websocket_handshake_request_info.h"
41#include "net/websockets/websocket_handshake_response_info.h"
[email protected]d51365e2013-11-27 10:46:5242#include "net/websockets/websocket_stream.h"
43
44namespace net {
[email protected]0be93922014-01-29 00:42:4545
46// TODO(ricea): If more extensions are added, replace this with a more general
47// mechanism.
48struct WebSocketExtensionParams {
49 WebSocketExtensionParams()
50 : deflate_enabled(false),
51 client_window_bits(15),
52 deflate_mode(WebSocketDeflater::TAKE_OVER_CONTEXT) {}
53
54 bool deflate_enabled;
55 int client_window_bits;
56 WebSocketDeflater::ContextTakeOverMode deflate_mode;
57};
58
[email protected]d51365e2013-11-27 10:46:5259namespace {
60
[email protected]96868202014-01-09 10:38:0461enum GetHeaderResult {
62 GET_HEADER_OK,
63 GET_HEADER_MISSING,
64 GET_HEADER_MULTIPLE,
65};
66
67std::string MissingHeaderMessage(const std::string& header_name) {
68 return std::string("'") + header_name + "' header is missing";
69}
70
71std::string MultipleHeaderValuesMessage(const std::string& header_name) {
72 return
73 std::string("'") +
74 header_name +
75 "' header must not appear more than once in a response";
76}
77
[email protected]d51365e2013-11-27 10:46:5278std::string GenerateHandshakeChallenge() {
79 std::string raw_challenge(websockets::kRawChallengeLength, '\0');
80 crypto::RandBytes(string_as_array(&raw_challenge), raw_challenge.length());
81 std::string encoded_challenge;
[email protected]33fca122013-12-11 01:48:5082 base::Base64Encode(raw_challenge, &encoded_challenge);
[email protected]d51365e2013-11-27 10:46:5283 return encoded_challenge;
84}
85
86void AddVectorHeaderIfNonEmpty(const char* name,
87 const std::vector<std::string>& value,
88 HttpRequestHeaders* headers) {
89 if (value.empty())
90 return;
91 headers->SetHeader(name, JoinString(value, ", "));
92}
93
[email protected]96868202014-01-09 10:38:0494GetHeaderResult GetSingleHeaderValue(const HttpResponseHeaders* headers,
95 const base::StringPiece& name,
96 std::string* value) {
[email protected]d51365e2013-11-27 10:46:5297 void* state = NULL;
[email protected]96868202014-01-09 10:38:0498 size_t num_values = 0;
99 std::string temp_value;
100 while (headers->EnumerateHeader(&state, name, &temp_value)) {
101 if (++num_values > 1)
102 return GET_HEADER_MULTIPLE;
103 *value = temp_value;
[email protected]d51365e2013-11-27 10:46:52104 }
[email protected]96868202014-01-09 10:38:04105 return num_values > 0 ? GET_HEADER_OK : GET_HEADER_MISSING;
106}
107
108bool ValidateHeaderHasSingleValue(GetHeaderResult result,
109 const std::string& header_name,
110 std::string* failure_message) {
111 if (result == GET_HEADER_MISSING) {
112 *failure_message = MissingHeaderMessage(header_name);
113 return false;
114 }
115 if (result == GET_HEADER_MULTIPLE) {
116 *failure_message = MultipleHeaderValuesMessage(header_name);
117 return false;
118 }
119 DCHECK_EQ(result, GET_HEADER_OK);
120 return true;
121}
122
123bool ValidateUpgrade(const HttpResponseHeaders* headers,
124 std::string* failure_message) {
125 std::string value;
126 GetHeaderResult result =
127 GetSingleHeaderValue(headers, websockets::kUpgrade, &value);
128 if (!ValidateHeaderHasSingleValue(result,
129 websockets::kUpgrade,
130 failure_message)) {
131 return false;
132 }
133
134 if (!LowerCaseEqualsASCII(value, websockets::kWebSocketLowercase)) {
135 *failure_message =
136 "'Upgrade' header value is not 'WebSocket': " + value;
137 return false;
138 }
139 return true;
140}
141
142bool ValidateSecWebSocketAccept(const HttpResponseHeaders* headers,
143 const std::string& expected,
144 std::string* failure_message) {
145 std::string actual;
146 GetHeaderResult result =
147 GetSingleHeaderValue(headers, websockets::kSecWebSocketAccept, &actual);
148 if (!ValidateHeaderHasSingleValue(result,
149 websockets::kSecWebSocketAccept,
150 failure_message)) {
151 return false;
152 }
153
154 if (expected != actual) {
155 *failure_message = "Incorrect 'Sec-WebSocket-Accept' header value";
156 return false;
157 }
158 return true;
159}
160
161bool ValidateConnection(const HttpResponseHeaders* headers,
162 std::string* failure_message) {
163 // Connection header is permitted to contain other tokens.
164 if (!headers->HasHeader(HttpRequestHeaders::kConnection)) {
165 *failure_message = MissingHeaderMessage(HttpRequestHeaders::kConnection);
166 return false;
167 }
168 if (!headers->HasHeaderValue(HttpRequestHeaders::kConnection,
169 websockets::kUpgrade)) {
170 *failure_message = "'Connection' header value must contain 'Upgrade'";
171 return false;
172 }
173 return true;
[email protected]d51365e2013-11-27 10:46:52174}
175
176bool ValidateSubProtocol(
[email protected]96868202014-01-09 10:38:04177 const HttpResponseHeaders* headers,
[email protected]d51365e2013-11-27 10:46:52178 const std::vector<std::string>& requested_sub_protocols,
[email protected]96868202014-01-09 10:38:04179 std::string* sub_protocol,
180 std::string* failure_message) {
[email protected]d51365e2013-11-27 10:46:52181 void* state = NULL;
[email protected]96868202014-01-09 10:38:04182 std::string value;
[email protected]d51365e2013-11-27 10:46:52183 base::hash_set<std::string> requested_set(requested_sub_protocols.begin(),
184 requested_sub_protocols.end());
[email protected]96868202014-01-09 10:38:04185 int count = 0;
186 bool has_multiple_protocols = false;
187 bool has_invalid_protocol = false;
[email protected]d51365e2013-11-27 10:46:52188
[email protected]96868202014-01-09 10:38:04189 while (!has_invalid_protocol || !has_multiple_protocols) {
190 std::string temp_value;
191 if (!headers->EnumerateHeader(
192 &state, websockets::kSecWebSocketProtocol, &temp_value))
193 break;
194 value = temp_value;
195 if (requested_set.count(value) == 0)
196 has_invalid_protocol = true;
197 if (++count > 1)
198 has_multiple_protocols = true;
[email protected]d51365e2013-11-27 10:46:52199 }
[email protected]96868202014-01-09 10:38:04200
201 if (has_multiple_protocols) {
202 *failure_message =
203 MultipleHeaderValuesMessage(websockets::kSecWebSocketProtocol);
204 return false;
205 } else if (count > 0 && requested_sub_protocols.size() == 0) {
206 *failure_message =
207 std::string("Response must not include 'Sec-WebSocket-Protocol' "
208 "header if not present in request: ")
209 + value;
210 return false;
211 } else if (has_invalid_protocol) {
212 *failure_message =
213 "'Sec-WebSocket-Protocol' header value '" +
214 value +
215 "' in response does not match any of sent values";
216 return false;
217 } else if (requested_sub_protocols.size() > 0 && count == 0) {
218 *failure_message =
219 "Sent non-empty 'Sec-WebSocket-Protocol' header "
220 "but no response was received";
221 return false;
222 }
223 *sub_protocol = value;
224 return true;
[email protected]d51365e2013-11-27 10:46:52225}
226
[email protected]69d7a492014-02-19 08:36:32227bool DeflateError(std::string* message, const base::StringPiece& piece) {
228 *message = "Error in permessage-deflate: ";
[email protected]0ecab7892014-03-11 21:15:40229 piece.AppendToString(message);
[email protected]69d7a492014-02-19 08:36:32230 return false;
231}
232
[email protected]0be93922014-01-29 00:42:45233bool ValidatePerMessageDeflateExtension(const WebSocketExtension& extension,
234 std::string* failure_message,
235 WebSocketExtensionParams* params) {
236 static const char kClientPrefix[] = "client_";
237 static const char kServerPrefix[] = "server_";
238 static const char kNoContextTakeover[] = "no_context_takeover";
239 static const char kMaxWindowBits[] = "max_window_bits";
240 const size_t kPrefixLen = arraysize(kClientPrefix) - 1;
241 COMPILE_ASSERT(kPrefixLen == arraysize(kServerPrefix) - 1,
242 the_strings_server_and_client_must_be_the_same_length);
243 typedef std::vector<WebSocketExtension::Parameter> ParameterVector;
244
[email protected]e5760f522014-02-05 12:28:50245 DCHECK_EQ("permessage-deflate", extension.name());
[email protected]0be93922014-01-29 00:42:45246 const ParameterVector& parameters = extension.parameters();
247 std::set<std::string> seen_names;
248 for (ParameterVector::const_iterator it = parameters.begin();
249 it != parameters.end(); ++it) {
250 const std::string& name = it->name();
251 if (seen_names.count(name) != 0) {
[email protected]69d7a492014-02-19 08:36:32252 return DeflateError(
253 failure_message,
254 "Received duplicate permessage-deflate extension parameter " + name);
[email protected]0be93922014-01-29 00:42:45255 }
256 seen_names.insert(name);
257 const std::string client_or_server(name, 0, kPrefixLen);
258 const bool is_client = (client_or_server == kClientPrefix);
259 if (!is_client && client_or_server != kServerPrefix) {
[email protected]69d7a492014-02-19 08:36:32260 return DeflateError(
261 failure_message,
262 "Received an unexpected permessage-deflate extension parameter");
[email protected]0be93922014-01-29 00:42:45263 }
264 const std::string rest(name, kPrefixLen);
265 if (rest == kNoContextTakeover) {
266 if (it->HasValue()) {
[email protected]69d7a492014-02-19 08:36:32267 return DeflateError(failure_message,
268 "Received invalid " + name + " parameter");
[email protected]0be93922014-01-29 00:42:45269 }
270 if (is_client)
271 params->deflate_mode = WebSocketDeflater::DO_NOT_TAKE_OVER_CONTEXT;
272 } else if (rest == kMaxWindowBits) {
[email protected]69d7a492014-02-19 08:36:32273 if (!it->HasValue())
274 return DeflateError(failure_message, name + " must have value");
[email protected]0be93922014-01-29 00:42:45275 int bits = 0;
276 if (!base::StringToInt(it->value(), &bits) || bits < 8 || bits > 15 ||
277 it->value()[0] == '0' ||
278 it->value().find_first_not_of("0123456789") != std::string::npos) {
[email protected]69d7a492014-02-19 08:36:32279 return DeflateError(failure_message,
280 "Received invalid " + name + " parameter");
[email protected]0be93922014-01-29 00:42:45281 }
282 if (is_client)
283 params->client_window_bits = bits;
284 } else {
[email protected]69d7a492014-02-19 08:36:32285 return DeflateError(
286 failure_message,
287 "Received an unexpected permessage-deflate extension parameter");
[email protected]0be93922014-01-29 00:42:45288 }
289 }
290 params->deflate_enabled = true;
291 return true;
292}
293
[email protected]96868202014-01-09 10:38:04294bool ValidateExtensions(const HttpResponseHeaders* headers,
[email protected]d51365e2013-11-27 10:46:52295 const std::vector<std::string>& requested_extensions,
[email protected]96868202014-01-09 10:38:04296 std::string* extensions,
[email protected]0be93922014-01-29 00:42:45297 std::string* failure_message,
298 WebSocketExtensionParams* params) {
[email protected]d51365e2013-11-27 10:46:52299 void* state = NULL;
[email protected]96868202014-01-09 10:38:04300 std::string value;
[email protected]0be93922014-01-29 00:42:45301 std::vector<std::string> accepted_extensions;
302 // TODO(ricea): If adding support for additional extensions, generalise this
303 // code.
304 bool seen_permessage_deflate = false;
[email protected]d51365e2013-11-27 10:46:52305 while (headers->EnumerateHeader(
[email protected]e5760f522014-02-05 12:28:50306 &state, websockets::kSecWebSocketExtensions, &value)) {
[email protected]96868202014-01-09 10:38:04307 WebSocketExtensionParser parser;
308 parser.Parse(value);
309 if (parser.has_error()) {
310 // TODO(yhirano) Set appropriate failure message.
311 *failure_message =
312 "'Sec-WebSocket-Extensions' header value is "
313 "rejected by the parser: " +
314 value;
315 return false;
316 }
[email protected]0be93922014-01-29 00:42:45317 if (parser.extension().name() == "permessage-deflate") {
318 if (seen_permessage_deflate) {
319 *failure_message = "Received duplicate permessage-deflate response";
320 return false;
321 }
322 seen_permessage_deflate = true;
323 if (!ValidatePerMessageDeflateExtension(
[email protected]e5760f522014-02-05 12:28:50324 parser.extension(), failure_message, params))
[email protected]0be93922014-01-29 00:42:45325 return false;
326 } else {
327 *failure_message =
328 "Found an unsupported extension '" +
329 parser.extension().name() +
330 "' in 'Sec-WebSocket-Extensions' header";
331 return false;
332 }
333 accepted_extensions.push_back(value);
[email protected]d51365e2013-11-27 10:46:52334 }
[email protected]0be93922014-01-29 00:42:45335 *extensions = JoinString(accepted_extensions, ", ");
[email protected]d51365e2013-11-27 10:46:52336 return true;
337}
338
339} // namespace
340
341WebSocketBasicHandshakeStream::WebSocketBasicHandshakeStream(
342 scoped_ptr<ClientSocketHandle> connection,
[email protected]cd48ed12014-01-22 14:34:22343 WebSocketStream::ConnectDelegate* connect_delegate,
[email protected]d51365e2013-11-27 10:46:52344 bool using_proxy,
345 std::vector<std::string> requested_sub_protocols,
346 std::vector<std::string> requested_extensions)
347 : state_(connection.release(), using_proxy),
[email protected]cd48ed12014-01-22 14:34:22348 connect_delegate_(connect_delegate),
[email protected]d51365e2013-11-27 10:46:52349 http_response_info_(NULL),
350 requested_sub_protocols_(requested_sub_protocols),
351 requested_extensions_(requested_extensions) {}
352
353WebSocketBasicHandshakeStream::~WebSocketBasicHandshakeStream() {}
354
355int WebSocketBasicHandshakeStream::InitializeStream(
356 const HttpRequestInfo* request_info,
357 RequestPriority priority,
358 const BoundNetLog& net_log,
359 const CompletionCallback& callback) {
[email protected]cd48ed12014-01-22 14:34:22360 url_ = request_info->url;
[email protected]d51365e2013-11-27 10:46:52361 state_.Initialize(request_info, priority, net_log, callback);
362 return OK;
363}
364
365int WebSocketBasicHandshakeStream::SendRequest(
366 const HttpRequestHeaders& headers,
367 HttpResponseInfo* response,
368 const CompletionCallback& callback) {
369 DCHECK(!headers.HasHeader(websockets::kSecWebSocketKey));
370 DCHECK(!headers.HasHeader(websockets::kSecWebSocketProtocol));
371 DCHECK(!headers.HasHeader(websockets::kSecWebSocketExtensions));
372 DCHECK(headers.HasHeader(HttpRequestHeaders::kOrigin));
373 DCHECK(headers.HasHeader(websockets::kUpgrade));
374 DCHECK(headers.HasHeader(HttpRequestHeaders::kConnection));
375 DCHECK(headers.HasHeader(websockets::kSecWebSocketVersion));
376 DCHECK(parser());
377
378 http_response_info_ = response;
379
380 // Create a copy of the headers object, so that we can add the
381 // Sec-WebSockey-Key header.
382 HttpRequestHeaders enriched_headers;
383 enriched_headers.CopyFrom(headers);
[email protected]a31ecc02013-12-05 08:30:55384 std::string handshake_challenge;
385 if (handshake_challenge_for_testing_) {
386 handshake_challenge = *handshake_challenge_for_testing_;
387 handshake_challenge_for_testing_.reset();
388 } else {
389 handshake_challenge = GenerateHandshakeChallenge();
390 }
[email protected]d51365e2013-11-27 10:46:52391 enriched_headers.SetHeader(websockets::kSecWebSocketKey, handshake_challenge);
392
[email protected]d51365e2013-11-27 10:46:52393 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketExtensions,
394 requested_extensions_,
395 &enriched_headers);
[email protected]0be93922014-01-29 00:42:45396 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketProtocol,
397 requested_sub_protocols_,
398 &enriched_headers);
[email protected]d51365e2013-11-27 10:46:52399
400 ComputeSecWebSocketAccept(handshake_challenge,
401 &handshake_challenge_response_);
402
[email protected]cd48ed12014-01-22 14:34:22403 DCHECK(connect_delegate_);
404 scoped_ptr<WebSocketHandshakeRequestInfo> request(
405 new WebSocketHandshakeRequestInfo(url_, base::Time::Now()));
406 request->headers.CopyFrom(enriched_headers);
407 connect_delegate_->OnStartOpeningHandshake(request.Pass());
408
[email protected]d51365e2013-11-27 10:46:52409 return parser()->SendRequest(
410 state_.GenerateRequestLine(), enriched_headers, response, callback);
411}
412
413int WebSocketBasicHandshakeStream::ReadResponseHeaders(
414 const CompletionCallback& callback) {
415 // HttpStreamParser uses a weak pointer when reading from the
416 // socket, so it won't be called back after being destroyed. The
417 // HttpStreamParser is owned by HttpBasicState which is owned by this object,
418 // so this use of base::Unretained() is safe.
419 int rv = parser()->ReadResponseHeaders(
420 base::Bind(&WebSocketBasicHandshakeStream::ReadResponseHeadersCallback,
421 base::Unretained(this),
422 callback));
[email protected]cd48ed12014-01-22 14:34:22423 if (rv == ERR_IO_PENDING)
424 return rv;
[email protected]e5760f522014-02-05 12:28:50425 return ValidateResponse(rv);
[email protected]d51365e2013-11-27 10:46:52426}
427
428const HttpResponseInfo* WebSocketBasicHandshakeStream::GetResponseInfo() const {
429 return parser()->GetResponseInfo();
430}
431
432int WebSocketBasicHandshakeStream::ReadResponseBody(
433 IOBuffer* buf,
434 int buf_len,
435 const CompletionCallback& callback) {
436 return parser()->ReadResponseBody(buf, buf_len, callback);
437}
438
439void WebSocketBasicHandshakeStream::Close(bool not_reusable) {
440 // This class ignores the value of |not_reusable| and never lets the socket be
441 // re-used.
442 if (parser())
443 parser()->Close(true);
444}
445
446bool WebSocketBasicHandshakeStream::IsResponseBodyComplete() const {
447 return parser()->IsResponseBodyComplete();
448}
449
450bool WebSocketBasicHandshakeStream::CanFindEndOfResponse() const {
451 return parser() && parser()->CanFindEndOfResponse();
452}
453
454bool WebSocketBasicHandshakeStream::IsConnectionReused() const {
455 return parser()->IsConnectionReused();
456}
457
458void WebSocketBasicHandshakeStream::SetConnectionReused() {
459 parser()->SetConnectionReused();
460}
461
462bool WebSocketBasicHandshakeStream::IsConnectionReusable() const {
463 return false;
464}
465
[email protected]bc92bc972013-12-13 08:32:59466int64 WebSocketBasicHandshakeStream::GetTotalReceivedBytes() const {
467 return 0;
468}
469
[email protected]d51365e2013-11-27 10:46:52470bool WebSocketBasicHandshakeStream::GetLoadTimingInfo(
471 LoadTimingInfo* load_timing_info) const {
472 return state_.connection()->GetLoadTimingInfo(IsConnectionReused(),
473 load_timing_info);
474}
475
476void WebSocketBasicHandshakeStream::GetSSLInfo(SSLInfo* ssl_info) {
477 parser()->GetSSLInfo(ssl_info);
478}
479
480void WebSocketBasicHandshakeStream::GetSSLCertRequestInfo(
481 SSLCertRequestInfo* cert_request_info) {
482 parser()->GetSSLCertRequestInfo(cert_request_info);
483}
484
485bool WebSocketBasicHandshakeStream::IsSpdyHttpStream() const { return false; }
486
487void WebSocketBasicHandshakeStream::Drain(HttpNetworkSession* session) {
488 HttpResponseBodyDrainer* drainer = new HttpResponseBodyDrainer(this);
489 drainer->Start(session);
490 // |drainer| will delete itself.
491}
492
493void WebSocketBasicHandshakeStream::SetPriority(RequestPriority priority) {
494 // TODO(ricea): See TODO comment in HttpBasicStream::SetPriority(). If it is
495 // gone, then copy whatever has happened there over here.
496}
497
498scoped_ptr<WebSocketStream> WebSocketBasicHandshakeStream::Upgrade() {
[email protected]d51365e2013-11-27 10:46:52499 // The HttpStreamParser object has a pointer to our ClientSocketHandle. Make
500 // sure it does not touch it again before it is destroyed.
501 state_.DeleteParser();
[email protected]0be93922014-01-29 00:42:45502 scoped_ptr<WebSocketStream> basic_stream(
[email protected]d51365e2013-11-27 10:46:52503 new WebSocketBasicStream(state_.ReleaseConnection(),
504 state_.read_buf(),
505 sub_protocol_,
506 extensions_));
[email protected]0be93922014-01-29 00:42:45507 DCHECK(extension_params_.get());
508 if (extension_params_->deflate_enabled) {
[email protected]9c50b042014-04-28 06:40:15509 UMA_HISTOGRAM_ENUMERATION(
510 "Net.WebSocket.DeflateMode",
511 extension_params_->deflate_mode,
512 WebSocketDeflater::NUM_CONTEXT_TAKEOVER_MODE_TYPES);
513
[email protected]0be93922014-01-29 00:42:45514 return scoped_ptr<WebSocketStream>(
515 new WebSocketDeflateStream(basic_stream.Pass(),
516 extension_params_->deflate_mode,
517 extension_params_->client_window_bits,
518 scoped_ptr<WebSocketDeflatePredictor>(
519 new WebSocketDeflatePredictorImpl)));
520 } else {
521 return basic_stream.Pass();
522 }
[email protected]d51365e2013-11-27 10:46:52523}
524
[email protected]a31ecc02013-12-05 08:30:55525void WebSocketBasicHandshakeStream::SetWebSocketKeyForTesting(
526 const std::string& key) {
527 handshake_challenge_for_testing_.reset(new std::string(key));
528}
529
[email protected]96868202014-01-09 10:38:04530std::string WebSocketBasicHandshakeStream::GetFailureMessage() const {
531 return failure_message_;
532}
533
[email protected]d51365e2013-11-27 10:46:52534void WebSocketBasicHandshakeStream::ReadResponseHeadersCallback(
535 const CompletionCallback& callback,
536 int result) {
[email protected]e5760f522014-02-05 12:28:50537 callback.Run(ValidateResponse(result));
[email protected]d51365e2013-11-27 10:46:52538}
539
[email protected]cd48ed12014-01-22 14:34:22540void WebSocketBasicHandshakeStream::OnFinishOpeningHandshake() {
541 DCHECK(connect_delegate_);
542 DCHECK(http_response_info_);
543 scoped_refptr<HttpResponseHeaders> headers = http_response_info_->headers;
[email protected]94831522014-02-06 12:05:18544 // If the headers are too large, HttpStreamParser will just not parse them at
545 // all.
546 if (headers) {
547 scoped_ptr<WebSocketHandshakeResponseInfo> response(
548 new WebSocketHandshakeResponseInfo(url_,
549 headers->response_code(),
550 headers->GetStatusText(),
551 headers,
552 http_response_info_->response_time));
553 connect_delegate_->OnFinishOpeningHandshake(response.Pass());
554 }
[email protected]cd48ed12014-01-22 14:34:22555}
556
[email protected]e5760f522014-02-05 12:28:50557int WebSocketBasicHandshakeStream::ValidateResponse(int rv) {
[email protected]d51365e2013-11-27 10:46:52558 DCHECK(http_response_info_);
[email protected]e5760f522014-02-05 12:28:50559 const HttpResponseHeaders* headers = http_response_info_->headers.get();
560 if (rv >= 0) {
561 switch (headers->response_code()) {
562 case HTTP_SWITCHING_PROTOCOLS:
563 OnFinishOpeningHandshake();
564 return ValidateUpgradeResponse(headers);
[email protected]d51365e2013-11-27 10:46:52565
[email protected]e5760f522014-02-05 12:28:50566 // We need to pass these through for authentication to work.
567 case HTTP_UNAUTHORIZED:
568 case HTTP_PROXY_AUTHENTICATION_REQUIRED:
569 return OK;
[email protected]d51365e2013-11-27 10:46:52570
[email protected]e5760f522014-02-05 12:28:50571 // Other status codes are potentially risky (see the warnings in the
572 // WHATWG WebSocket API spec) and so are dropped by default.
573 default:
[email protected]aeb640d2014-02-21 11:03:18574 // A WebSocket server cannot be using HTTP/0.9, so if we see version
575 // 0.9, it means the response was garbage.
576 // Reporting "Unexpected response code: 200" in this case is not
577 // helpful, so use a different error message.
578 if (headers->GetHttpVersion() == HttpVersion(0, 9)) {
579 failure_message_ =
580 "Error during WebSocket handshake: Invalid status line";
581 } else {
582 failure_message_ = base::StringPrintf(
583 "Error during WebSocket handshake: Unexpected response code: %d",
584 headers->response_code());
585 }
[email protected]e5760f522014-02-05 12:28:50586 OnFinishOpeningHandshake();
587 return ERR_INVALID_RESPONSE;
588 }
589 } else {
[email protected]3efc08f2014-02-07 09:33:34590 if (rv == ERR_EMPTY_RESPONSE) {
591 failure_message_ =
592 "Connection closed before receiving a handshake response";
593 return rv;
594 }
[email protected]e5760f522014-02-05 12:28:50595 failure_message_ =
596 std::string("Error during WebSocket handshake: ") + ErrorToString(rv);
597 OnFinishOpeningHandshake();
598 return rv;
[email protected]d51365e2013-11-27 10:46:52599 }
600}
601
602int WebSocketBasicHandshakeStream::ValidateUpgradeResponse(
[email protected]e5760f522014-02-05 12:28:50603 const HttpResponseHeaders* headers) {
[email protected]0be93922014-01-29 00:42:45604 extension_params_.reset(new WebSocketExtensionParams);
[email protected]e5760f522014-02-05 12:28:50605 if (ValidateUpgrade(headers, &failure_message_) &&
606 ValidateSecWebSocketAccept(headers,
[email protected]96868202014-01-09 10:38:04607 handshake_challenge_response_,
608 &failure_message_) &&
[email protected]e5760f522014-02-05 12:28:50609 ValidateConnection(headers, &failure_message_) &&
610 ValidateSubProtocol(headers,
[email protected]96868202014-01-09 10:38:04611 requested_sub_protocols_,
612 &sub_protocol_,
613 &failure_message_) &&
[email protected]e5760f522014-02-05 12:28:50614 ValidateExtensions(headers,
[email protected]96868202014-01-09 10:38:04615 requested_extensions_,
616 &extensions_,
[email protected]0be93922014-01-29 00:42:45617 &failure_message_,
618 extension_params_.get())) {
[email protected]d51365e2013-11-27 10:46:52619 return OK;
620 }
[email protected]96868202014-01-09 10:38:04621 failure_message_ = "Error during WebSocket handshake: " + failure_message_;
[email protected]d51365e2013-11-27 10:46:52622 return ERR_INVALID_RESPONSE;
623}
624
625} // namespace net