blob: 7d993114034836a3f92d0f153ece8e340cb953fd [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"
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// TODO(yhirano): Remove these functions once http://crbug.com/399535 is fixed.
56NOINLINE void RunCallbackWithOk(const CompletionCallback& callback,
57 int result) {
58 DCHECK_EQ(result, OK);
59 callback.Run(OK);
60}
61
62NOINLINE void RunCallbackWithInvalidResponseCausedByRedirect(
63 const CompletionCallback& callback,
64 int result) {
65 DCHECK_EQ(result, ERR_INVALID_RESPONSE);
66 callback.Run(ERR_INVALID_RESPONSE);
67}
68
69NOINLINE void RunCallbackWithInvalidResponse(
70 const CompletionCallback& callback,
71 int result) {
72 DCHECK_EQ(result, ERR_INVALID_RESPONSE);
73 callback.Run(ERR_INVALID_RESPONSE);
74}
75
76NOINLINE void RunCallback(const CompletionCallback& callback, int result) {
77 callback.Run(result);
78}
79
80} // namespace
81
[email protected]0be93922014-01-29 00:42:4582// TODO(ricea): If more extensions are added, replace this with a more general
83// mechanism.
84struct WebSocketExtensionParams {
85 WebSocketExtensionParams()
86 : deflate_enabled(false),
87 client_window_bits(15),
88 deflate_mode(WebSocketDeflater::TAKE_OVER_CONTEXT) {}
89
90 bool deflate_enabled;
91 int client_window_bits;
92 WebSocketDeflater::ContextTakeOverMode deflate_mode;
93};
94
[email protected]d51365e2013-11-27 10:46:5295namespace {
96
[email protected]96868202014-01-09 10:38:0497enum GetHeaderResult {
98 GET_HEADER_OK,
99 GET_HEADER_MISSING,
100 GET_HEADER_MULTIPLE,
101};
102
103std::string MissingHeaderMessage(const std::string& header_name) {
104 return std::string("'") + header_name + "' header is missing";
105}
106
107std::string MultipleHeaderValuesMessage(const std::string& header_name) {
108 return
109 std::string("'") +
110 header_name +
111 "' header must not appear more than once in a response";
112}
113
[email protected]d51365e2013-11-27 10:46:52114std::string GenerateHandshakeChallenge() {
115 std::string raw_challenge(websockets::kRawChallengeLength, '\0');
116 crypto::RandBytes(string_as_array(&raw_challenge), raw_challenge.length());
117 std::string encoded_challenge;
[email protected]33fca122013-12-11 01:48:50118 base::Base64Encode(raw_challenge, &encoded_challenge);
[email protected]d51365e2013-11-27 10:46:52119 return encoded_challenge;
120}
121
122void AddVectorHeaderIfNonEmpty(const char* name,
123 const std::vector<std::string>& value,
124 HttpRequestHeaders* headers) {
125 if (value.empty())
126 return;
127 headers->SetHeader(name, JoinString(value, ", "));
128}
129
[email protected]96868202014-01-09 10:38:04130GetHeaderResult GetSingleHeaderValue(const HttpResponseHeaders* headers,
131 const base::StringPiece& name,
132 std::string* value) {
yhiranoa7e05bb2014-11-06 05:40:39133 void* state = nullptr;
[email protected]96868202014-01-09 10:38:04134 size_t num_values = 0;
135 std::string temp_value;
136 while (headers->EnumerateHeader(&state, name, &temp_value)) {
137 if (++num_values > 1)
138 return GET_HEADER_MULTIPLE;
139 *value = temp_value;
[email protected]d51365e2013-11-27 10:46:52140 }
[email protected]96868202014-01-09 10:38:04141 return num_values > 0 ? GET_HEADER_OK : GET_HEADER_MISSING;
142}
143
144bool ValidateHeaderHasSingleValue(GetHeaderResult result,
145 const std::string& header_name,
146 std::string* failure_message) {
147 if (result == GET_HEADER_MISSING) {
148 *failure_message = MissingHeaderMessage(header_name);
149 return false;
150 }
151 if (result == GET_HEADER_MULTIPLE) {
152 *failure_message = MultipleHeaderValuesMessage(header_name);
153 return false;
154 }
155 DCHECK_EQ(result, GET_HEADER_OK);
156 return true;
157}
158
159bool ValidateUpgrade(const HttpResponseHeaders* headers,
160 std::string* failure_message) {
161 std::string value;
162 GetHeaderResult result =
163 GetSingleHeaderValue(headers, websockets::kUpgrade, &value);
164 if (!ValidateHeaderHasSingleValue(result,
165 websockets::kUpgrade,
166 failure_message)) {
167 return false;
168 }
169
[email protected]df807042014-08-13 16:48:41170 if (!LowerCaseEqualsASCII(value, websockets::kWebSocketLowercase)) {
[email protected]96868202014-01-09 10:38:04171 *failure_message =
172 "'Upgrade' header value is not 'WebSocket': " + value;
173 return false;
174 }
175 return true;
176}
177
178bool ValidateSecWebSocketAccept(const HttpResponseHeaders* headers,
179 const std::string& expected,
180 std::string* failure_message) {
181 std::string actual;
182 GetHeaderResult result =
183 GetSingleHeaderValue(headers, websockets::kSecWebSocketAccept, &actual);
184 if (!ValidateHeaderHasSingleValue(result,
185 websockets::kSecWebSocketAccept,
186 failure_message)) {
187 return false;
188 }
189
190 if (expected != actual) {
191 *failure_message = "Incorrect 'Sec-WebSocket-Accept' header value";
192 return false;
193 }
194 return true;
195}
196
197bool ValidateConnection(const HttpResponseHeaders* headers,
198 std::string* failure_message) {
199 // Connection header is permitted to contain other tokens.
200 if (!headers->HasHeader(HttpRequestHeaders::kConnection)) {
201 *failure_message = MissingHeaderMessage(HttpRequestHeaders::kConnection);
202 return false;
203 }
204 if (!headers->HasHeaderValue(HttpRequestHeaders::kConnection,
205 websockets::kUpgrade)) {
206 *failure_message = "'Connection' header value must contain 'Upgrade'";
207 return false;
208 }
209 return true;
[email protected]d51365e2013-11-27 10:46:52210}
211
212bool ValidateSubProtocol(
[email protected]96868202014-01-09 10:38:04213 const HttpResponseHeaders* headers,
[email protected]d51365e2013-11-27 10:46:52214 const std::vector<std::string>& requested_sub_protocols,
[email protected]96868202014-01-09 10:38:04215 std::string* sub_protocol,
216 std::string* failure_message) {
yhiranoa7e05bb2014-11-06 05:40:39217 void* state = nullptr;
[email protected]96868202014-01-09 10:38:04218 std::string value;
[email protected]d51365e2013-11-27 10:46:52219 base::hash_set<std::string> requested_set(requested_sub_protocols.begin(),
220 requested_sub_protocols.end());
[email protected]96868202014-01-09 10:38:04221 int count = 0;
222 bool has_multiple_protocols = false;
223 bool has_invalid_protocol = false;
[email protected]d51365e2013-11-27 10:46:52224
[email protected]96868202014-01-09 10:38:04225 while (!has_invalid_protocol || !has_multiple_protocols) {
226 std::string temp_value;
227 if (!headers->EnumerateHeader(
228 &state, websockets::kSecWebSocketProtocol, &temp_value))
229 break;
230 value = temp_value;
231 if (requested_set.count(value) == 0)
232 has_invalid_protocol = true;
233 if (++count > 1)
234 has_multiple_protocols = true;
[email protected]d51365e2013-11-27 10:46:52235 }
[email protected]96868202014-01-09 10:38:04236
237 if (has_multiple_protocols) {
238 *failure_message =
239 MultipleHeaderValuesMessage(websockets::kSecWebSocketProtocol);
240 return false;
241 } else if (count > 0 && requested_sub_protocols.size() == 0) {
242 *failure_message =
243 std::string("Response must not include 'Sec-WebSocket-Protocol' "
244 "header if not present in request: ")
245 + value;
246 return false;
247 } else if (has_invalid_protocol) {
248 *failure_message =
249 "'Sec-WebSocket-Protocol' header value '" +
250 value +
251 "' in response does not match any of sent values";
252 return false;
253 } else if (requested_sub_protocols.size() > 0 && count == 0) {
254 *failure_message =
255 "Sent non-empty 'Sec-WebSocket-Protocol' header "
256 "but no response was received";
257 return false;
258 }
259 *sub_protocol = value;
260 return true;
[email protected]d51365e2013-11-27 10:46:52261}
262
[email protected]69d7a492014-02-19 08:36:32263bool DeflateError(std::string* message, const base::StringPiece& piece) {
264 *message = "Error in permessage-deflate: ";
[email protected]0ecab7892014-03-11 21:15:40265 piece.AppendToString(message);
[email protected]69d7a492014-02-19 08:36:32266 return false;
267}
268
[email protected]0be93922014-01-29 00:42:45269bool ValidatePerMessageDeflateExtension(const WebSocketExtension& extension,
270 std::string* failure_message,
271 WebSocketExtensionParams* params) {
272 static const char kClientPrefix[] = "client_";
273 static const char kServerPrefix[] = "server_";
274 static const char kNoContextTakeover[] = "no_context_takeover";
275 static const char kMaxWindowBits[] = "max_window_bits";
276 const size_t kPrefixLen = arraysize(kClientPrefix) - 1;
mostynb91e0da982015-01-20 19:17:27277 static_assert(kPrefixLen == arraysize(kServerPrefix) - 1,
278 "the strings server and client must be the same length");
[email protected]0be93922014-01-29 00:42:45279 typedef std::vector<WebSocketExtension::Parameter> ParameterVector;
280
[email protected]e5760f522014-02-05 12:28:50281 DCHECK_EQ("permessage-deflate", extension.name());
[email protected]0be93922014-01-29 00:42:45282 const ParameterVector& parameters = extension.parameters();
283 std::set<std::string> seen_names;
284 for (ParameterVector::const_iterator it = parameters.begin();
285 it != parameters.end(); ++it) {
286 const std::string& name = it->name();
287 if (seen_names.count(name) != 0) {
[email protected]69d7a492014-02-19 08:36:32288 return DeflateError(
289 failure_message,
290 "Received duplicate permessage-deflate extension parameter " + name);
[email protected]0be93922014-01-29 00:42:45291 }
292 seen_names.insert(name);
293 const std::string client_or_server(name, 0, kPrefixLen);
294 const bool is_client = (client_or_server == kClientPrefix);
295 if (!is_client && client_or_server != kServerPrefix) {
[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 const std::string rest(name, kPrefixLen);
301 if (rest == kNoContextTakeover) {
302 if (it->HasValue()) {
[email protected]69d7a492014-02-19 08:36:32303 return DeflateError(failure_message,
304 "Received invalid " + name + " parameter");
[email protected]0be93922014-01-29 00:42:45305 }
306 if (is_client)
307 params->deflate_mode = WebSocketDeflater::DO_NOT_TAKE_OVER_CONTEXT;
308 } else if (rest == kMaxWindowBits) {
[email protected]69d7a492014-02-19 08:36:32309 if (!it->HasValue())
310 return DeflateError(failure_message, name + " must have value");
[email protected]0be93922014-01-29 00:42:45311 int bits = 0;
312 if (!base::StringToInt(it->value(), &bits) || bits < 8 || bits > 15 ||
313 it->value()[0] == '0' ||
314 it->value().find_first_not_of("0123456789") != std::string::npos) {
[email protected]69d7a492014-02-19 08:36:32315 return DeflateError(failure_message,
316 "Received invalid " + name + " parameter");
[email protected]0be93922014-01-29 00:42:45317 }
318 if (is_client)
319 params->client_window_bits = bits;
320 } else {
[email protected]69d7a492014-02-19 08:36:32321 return DeflateError(
322 failure_message,
323 "Received an unexpected permessage-deflate extension parameter");
[email protected]0be93922014-01-29 00:42:45324 }
325 }
326 params->deflate_enabled = true;
327 return true;
328}
329
[email protected]96868202014-01-09 10:38:04330bool ValidateExtensions(const HttpResponseHeaders* headers,
[email protected]d51365e2013-11-27 10:46:52331 const std::vector<std::string>& requested_extensions,
[email protected]96868202014-01-09 10:38:04332 std::string* extensions,
[email protected]0be93922014-01-29 00:42:45333 std::string* failure_message,
334 WebSocketExtensionParams* params) {
yhiranoa7e05bb2014-11-06 05:40:39335 void* state = nullptr;
[email protected]96868202014-01-09 10:38:04336 std::string value;
[email protected]0be93922014-01-29 00:42:45337 std::vector<std::string> accepted_extensions;
338 // TODO(ricea): If adding support for additional extensions, generalise this
339 // code.
340 bool seen_permessage_deflate = false;
[email protected]d51365e2013-11-27 10:46:52341 while (headers->EnumerateHeader(
[email protected]e5760f522014-02-05 12:28:50342 &state, websockets::kSecWebSocketExtensions, &value)) {
[email protected]96868202014-01-09 10:38:04343 WebSocketExtensionParser parser;
344 parser.Parse(value);
345 if (parser.has_error()) {
346 // TODO(yhirano) Set appropriate failure message.
347 *failure_message =
348 "'Sec-WebSocket-Extensions' header value is "
349 "rejected by the parser: " +
350 value;
351 return false;
352 }
[email protected]0be93922014-01-29 00:42:45353 if (parser.extension().name() == "permessage-deflate") {
354 if (seen_permessage_deflate) {
355 *failure_message = "Received duplicate permessage-deflate response";
356 return false;
357 }
358 seen_permessage_deflate = true;
359 if (!ValidatePerMessageDeflateExtension(
[email protected]e5760f522014-02-05 12:28:50360 parser.extension(), failure_message, params))
[email protected]0be93922014-01-29 00:42:45361 return false;
362 } else {
363 *failure_message =
364 "Found an unsupported extension '" +
365 parser.extension().name() +
366 "' in 'Sec-WebSocket-Extensions' header";
367 return false;
368 }
369 accepted_extensions.push_back(value);
[email protected]d51365e2013-11-27 10:46:52370 }
[email protected]0be93922014-01-29 00:42:45371 *extensions = JoinString(accepted_extensions, ", ");
[email protected]d51365e2013-11-27 10:46:52372 return true;
373}
374
375} // namespace
376
377WebSocketBasicHandshakeStream::WebSocketBasicHandshakeStream(
378 scoped_ptr<ClientSocketHandle> connection,
[email protected]cd48ed12014-01-22 14:34:22379 WebSocketStream::ConnectDelegate* connect_delegate,
[email protected]d51365e2013-11-27 10:46:52380 bool using_proxy,
381 std::vector<std::string> requested_sub_protocols,
[email protected]8aba0172014-07-03 12:09:53382 std::vector<std::string> requested_extensions,
383 std::string* failure_message)
[email protected]d51365e2013-11-27 10:46:52384 : state_(connection.release(), using_proxy),
[email protected]cd48ed12014-01-22 14:34:22385 connect_delegate_(connect_delegate),
yhiranoa7e05bb2014-11-06 05:40:39386 http_response_info_(nullptr),
[email protected]d51365e2013-11-27 10:46:52387 requested_sub_protocols_(requested_sub_protocols),
[email protected]8aba0172014-07-03 12:09:53388 requested_extensions_(requested_extensions),
389 failure_message_(failure_message) {
390 DCHECK(connect_delegate);
391 DCHECK(failure_message);
392}
[email protected]d51365e2013-11-27 10:46:52393
394WebSocketBasicHandshakeStream::~WebSocketBasicHandshakeStream() {}
395
396int WebSocketBasicHandshakeStream::InitializeStream(
397 const HttpRequestInfo* request_info,
398 RequestPriority priority,
399 const BoundNetLog& net_log,
400 const CompletionCallback& callback) {
[email protected]cd48ed12014-01-22 14:34:22401 url_ = request_info->url;
[email protected]d51365e2013-11-27 10:46:52402 state_.Initialize(request_info, priority, net_log, callback);
403 return OK;
404}
405
406int WebSocketBasicHandshakeStream::SendRequest(
407 const HttpRequestHeaders& headers,
408 HttpResponseInfo* response,
409 const CompletionCallback& callback) {
410 DCHECK(!headers.HasHeader(websockets::kSecWebSocketKey));
411 DCHECK(!headers.HasHeader(websockets::kSecWebSocketProtocol));
412 DCHECK(!headers.HasHeader(websockets::kSecWebSocketExtensions));
413 DCHECK(headers.HasHeader(HttpRequestHeaders::kOrigin));
414 DCHECK(headers.HasHeader(websockets::kUpgrade));
415 DCHECK(headers.HasHeader(HttpRequestHeaders::kConnection));
416 DCHECK(headers.HasHeader(websockets::kSecWebSocketVersion));
417 DCHECK(parser());
418
419 http_response_info_ = response;
420
421 // Create a copy of the headers object, so that we can add the
422 // Sec-WebSockey-Key header.
423 HttpRequestHeaders enriched_headers;
424 enriched_headers.CopyFrom(headers);
[email protected]a31ecc02013-12-05 08:30:55425 std::string handshake_challenge;
426 if (handshake_challenge_for_testing_) {
427 handshake_challenge = *handshake_challenge_for_testing_;
428 handshake_challenge_for_testing_.reset();
429 } else {
430 handshake_challenge = GenerateHandshakeChallenge();
431 }
[email protected]d51365e2013-11-27 10:46:52432 enriched_headers.SetHeader(websockets::kSecWebSocketKey, handshake_challenge);
433
[email protected]d51365e2013-11-27 10:46:52434 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketExtensions,
435 requested_extensions_,
436 &enriched_headers);
[email protected]0be93922014-01-29 00:42:45437 AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketProtocol,
438 requested_sub_protocols_,
439 &enriched_headers);
[email protected]d51365e2013-11-27 10:46:52440
ricea11bdcd02014-11-20 09:57:07441 handshake_challenge_response_ =
442 ComputeSecWebSocketAccept(handshake_challenge);
[email protected]d51365e2013-11-27 10:46:52443
[email protected]cd48ed12014-01-22 14:34:22444 DCHECK(connect_delegate_);
445 scoped_ptr<WebSocketHandshakeRequestInfo> request(
446 new WebSocketHandshakeRequestInfo(url_, base::Time::Now()));
447 request->headers.CopyFrom(enriched_headers);
448 connect_delegate_->OnStartOpeningHandshake(request.Pass());
449
[email protected]d51365e2013-11-27 10:46:52450 return parser()->SendRequest(
451 state_.GenerateRequestLine(), enriched_headers, response, callback);
452}
453
454int WebSocketBasicHandshakeStream::ReadResponseHeaders(
455 const CompletionCallback& callback) {
456 // HttpStreamParser uses a weak pointer when reading from the
457 // socket, so it won't be called back after being destroyed. The
458 // HttpStreamParser is owned by HttpBasicState which is owned by this object,
459 // so this use of base::Unretained() is safe.
460 int rv = parser()->ReadResponseHeaders(
461 base::Bind(&WebSocketBasicHandshakeStream::ReadResponseHeadersCallback,
462 base::Unretained(this),
463 callback));
[email protected]cd48ed12014-01-22 14:34:22464 if (rv == ERR_IO_PENDING)
465 return rv;
yhirano27b2b572014-10-30 11:23:44466 bool is_redirect = false;
467 return ValidateResponse(rv, &is_redirect);
[email protected]d51365e2013-11-27 10:46:52468}
469
[email protected]d51365e2013-11-27 10:46:52470int WebSocketBasicHandshakeStream::ReadResponseBody(
471 IOBuffer* buf,
472 int buf_len,
473 const CompletionCallback& callback) {
474 return parser()->ReadResponseBody(buf, buf_len, callback);
475}
476
477void WebSocketBasicHandshakeStream::Close(bool not_reusable) {
478 // This class ignores the value of |not_reusable| and never lets the socket be
479 // re-used.
480 if (parser())
481 parser()->Close(true);
482}
483
484bool WebSocketBasicHandshakeStream::IsResponseBodyComplete() const {
485 return parser()->IsResponseBodyComplete();
486}
487
488bool WebSocketBasicHandshakeStream::CanFindEndOfResponse() const {
489 return parser() && parser()->CanFindEndOfResponse();
490}
491
492bool WebSocketBasicHandshakeStream::IsConnectionReused() const {
493 return parser()->IsConnectionReused();
494}
495
496void WebSocketBasicHandshakeStream::SetConnectionReused() {
497 parser()->SetConnectionReused();
498}
499
500bool WebSocketBasicHandshakeStream::IsConnectionReusable() const {
501 return false;
502}
503
[email protected]bc92bc972013-12-13 08:32:59504int64 WebSocketBasicHandshakeStream::GetTotalReceivedBytes() const {
505 return 0;
506}
507
[email protected]d51365e2013-11-27 10:46:52508bool WebSocketBasicHandshakeStream::GetLoadTimingInfo(
509 LoadTimingInfo* load_timing_info) const {
510 return state_.connection()->GetLoadTimingInfo(IsConnectionReused(),
511 load_timing_info);
512}
513
514void WebSocketBasicHandshakeStream::GetSSLInfo(SSLInfo* ssl_info) {
515 parser()->GetSSLInfo(ssl_info);
516}
517
518void WebSocketBasicHandshakeStream::GetSSLCertRequestInfo(
519 SSLCertRequestInfo* cert_request_info) {
520 parser()->GetSSLCertRequestInfo(cert_request_info);
521}
522
523bool WebSocketBasicHandshakeStream::IsSpdyHttpStream() const { return false; }
524
525void WebSocketBasicHandshakeStream::Drain(HttpNetworkSession* session) {
526 HttpResponseBodyDrainer* drainer = new HttpResponseBodyDrainer(this);
527 drainer->Start(session);
528 // |drainer| will delete itself.
529}
530
531void WebSocketBasicHandshakeStream::SetPriority(RequestPriority priority) {
532 // TODO(ricea): See TODO comment in HttpBasicStream::SetPriority(). If it is
533 // gone, then copy whatever has happened there over here.
534}
535
yhiranoa7e05bb2014-11-06 05:40:39536UploadProgress WebSocketBasicHandshakeStream::GetUploadProgress() const {
537 return UploadProgress();
538}
539
540HttpStream* WebSocketBasicHandshakeStream::RenewStreamForAuth() {
541 // Return null because we don't support renewing the stream.
542 return nullptr;
543}
544
[email protected]d51365e2013-11-27 10:46:52545scoped_ptr<WebSocketStream> WebSocketBasicHandshakeStream::Upgrade() {
[email protected]d51365e2013-11-27 10:46:52546 // The HttpStreamParser object has a pointer to our ClientSocketHandle. Make
547 // sure it does not touch it again before it is destroyed.
548 state_.DeleteParser();
[email protected]654866142014-06-24 22:53:31549 WebSocketTransportClientSocketPool::UnlockEndpoint(state_.connection());
[email protected]0be93922014-01-29 00:42:45550 scoped_ptr<WebSocketStream> basic_stream(
[email protected]d51365e2013-11-27 10:46:52551 new WebSocketBasicStream(state_.ReleaseConnection(),
552 state_.read_buf(),
553 sub_protocol_,
554 extensions_));
[email protected]0be93922014-01-29 00:42:45555 DCHECK(extension_params_.get());
556 if (extension_params_->deflate_enabled) {
[email protected]9c50b042014-04-28 06:40:15557 UMA_HISTOGRAM_ENUMERATION(
558 "Net.WebSocket.DeflateMode",
559 extension_params_->deflate_mode,
560 WebSocketDeflater::NUM_CONTEXT_TAKEOVER_MODE_TYPES);
561
[email protected]0be93922014-01-29 00:42:45562 return scoped_ptr<WebSocketStream>(
563 new WebSocketDeflateStream(basic_stream.Pass(),
564 extension_params_->deflate_mode,
565 extension_params_->client_window_bits,
566 scoped_ptr<WebSocketDeflatePredictor>(
567 new WebSocketDeflatePredictorImpl)));
568 } else {
569 return basic_stream.Pass();
570 }
[email protected]d51365e2013-11-27 10:46:52571}
572
[email protected]a31ecc02013-12-05 08:30:55573void WebSocketBasicHandshakeStream::SetWebSocketKeyForTesting(
574 const std::string& key) {
575 handshake_challenge_for_testing_.reset(new std::string(key));
576}
577
[email protected]d51365e2013-11-27 10:46:52578void WebSocketBasicHandshakeStream::ReadResponseHeadersCallback(
579 const CompletionCallback& callback,
580 int result) {
yhirano27b2b572014-10-30 11:23:44581 bool is_redirect = false;
582 int rv = ValidateResponse(result, &is_redirect);
583
584 // TODO(yhirano): Simplify this statement once http://crbug.com/399535 is
585 // fixed.
586 switch (rv) {
587 case OK:
588 RunCallbackWithOk(callback, rv);
589 break;
590 case ERR_INVALID_RESPONSE:
591 if (is_redirect)
592 RunCallbackWithInvalidResponseCausedByRedirect(callback, rv);
593 else
594 RunCallbackWithInvalidResponse(callback, rv);
595 break;
596 default:
597 RunCallback(callback, rv);
598 break;
599 }
[email protected]d51365e2013-11-27 10:46:52600}
601
[email protected]cd48ed12014-01-22 14:34:22602void WebSocketBasicHandshakeStream::OnFinishOpeningHandshake() {
[email protected]cd48ed12014-01-22 14:34:22603 DCHECK(http_response_info_);
[email protected]e69c1cd2014-07-29 07:42:29604 WebSocketDispatchOnFinishOpeningHandshake(connect_delegate_,
605 url_,
606 http_response_info_->headers,
607 http_response_info_->response_time);
[email protected]cd48ed12014-01-22 14:34:22608}
609
yhirano27b2b572014-10-30 11:23:44610int WebSocketBasicHandshakeStream::ValidateResponse(int rv,
611 bool* is_redirect) {
[email protected]d51365e2013-11-27 10:46:52612 DCHECK(http_response_info_);
yhirano27b2b572014-10-30 11:23:44613 *is_redirect = false;
[email protected]f7e98ca2014-06-19 12:05:43614 // Most net errors happen during connection, so they are not seen by this
615 // method. The histogram for error codes is created in
616 // Delegate::OnResponseStarted in websocket_stream.cc instead.
[email protected]e5760f522014-02-05 12:28:50617 if (rv >= 0) {
[email protected]f7e98ca2014-06-19 12:05:43618 const HttpResponseHeaders* headers = http_response_info_->headers.get();
619 const int response_code = headers->response_code();
yhirano27b2b572014-10-30 11:23:44620 *is_redirect = HttpResponseHeaders::IsRedirectResponseCode(response_code);
[email protected]f7e98ca2014-06-19 12:05:43621 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.WebSocket.ResponseCode", response_code);
622 switch (response_code) {
[email protected]e5760f522014-02-05 12:28:50623 case HTTP_SWITCHING_PROTOCOLS:
624 OnFinishOpeningHandshake();
625 return ValidateUpgradeResponse(headers);
[email protected]d51365e2013-11-27 10:46:52626
[email protected]e5760f522014-02-05 12:28:50627 // We need to pass these through for authentication to work.
628 case HTTP_UNAUTHORIZED:
629 case HTTP_PROXY_AUTHENTICATION_REQUIRED:
630 return OK;
[email protected]d51365e2013-11-27 10:46:52631
[email protected]e5760f522014-02-05 12:28:50632 // Other status codes are potentially risky (see the warnings in the
633 // WHATWG WebSocket API spec) and so are dropped by default.
634 default:
[email protected]aeb640d2014-02-21 11:03:18635 // A WebSocket server cannot be using HTTP/0.9, so if we see version
636 // 0.9, it means the response was garbage.
637 // Reporting "Unexpected response code: 200" in this case is not
638 // helpful, so use a different error message.
639 if (headers->GetHttpVersion() == HttpVersion(0, 9)) {
[email protected]8aba0172014-07-03 12:09:53640 set_failure_message(
641 "Error during WebSocket handshake: Invalid status line");
[email protected]aeb640d2014-02-21 11:03:18642 } else {
[email protected]8aba0172014-07-03 12:09:53643 set_failure_message(base::StringPrintf(
[email protected]aeb640d2014-02-21 11:03:18644 "Error during WebSocket handshake: Unexpected response code: %d",
[email protected]8aba0172014-07-03 12:09:53645 headers->response_code()));
[email protected]aeb640d2014-02-21 11:03:18646 }
[email protected]e5760f522014-02-05 12:28:50647 OnFinishOpeningHandshake();
648 return ERR_INVALID_RESPONSE;
649 }
650 } else {
[email protected]3efc08f2014-02-07 09:33:34651 if (rv == ERR_EMPTY_RESPONSE) {
[email protected]8aba0172014-07-03 12:09:53652 set_failure_message(
653 "Connection closed before receiving a handshake response");
[email protected]3efc08f2014-02-07 09:33:34654 return rv;
655 }
[email protected]8aba0172014-07-03 12:09:53656 set_failure_message(std::string("Error during WebSocket handshake: ") +
657 ErrorToString(rv));
[email protected]e5760f522014-02-05 12:28:50658 OnFinishOpeningHandshake();
ricea23c3f942015-02-02 13:35:13659 // Some error codes (for example ERR_CONNECTION_CLOSED) get changed to OK at
660 // higher levels. To prevent an unvalidated connection getting erroneously
661 // upgraded, don't pass through the status code unchanged if it is
662 // HTTP_SWITCHING_PROTOCOLS.
663 if (http_response_info_->headers &&
664 http_response_info_->headers->response_code() ==
665 HTTP_SWITCHING_PROTOCOLS) {
666 http_response_info_->headers->ReplaceStatusLine(
667 kConnectionErrorStatusLine);
668 }
[email protected]e5760f522014-02-05 12:28:50669 return rv;
[email protected]d51365e2013-11-27 10:46:52670 }
671}
672
673int WebSocketBasicHandshakeStream::ValidateUpgradeResponse(
[email protected]e5760f522014-02-05 12:28:50674 const HttpResponseHeaders* headers) {
[email protected]0be93922014-01-29 00:42:45675 extension_params_.reset(new WebSocketExtensionParams);
[email protected]8aba0172014-07-03 12:09:53676 std::string failure_message;
677 if (ValidateUpgrade(headers, &failure_message) &&
678 ValidateSecWebSocketAccept(
679 headers, handshake_challenge_response_, &failure_message) &&
680 ValidateConnection(headers, &failure_message) &&
[email protected]e5760f522014-02-05 12:28:50681 ValidateSubProtocol(headers,
[email protected]96868202014-01-09 10:38:04682 requested_sub_protocols_,
683 &sub_protocol_,
[email protected]8aba0172014-07-03 12:09:53684 &failure_message) &&
[email protected]e5760f522014-02-05 12:28:50685 ValidateExtensions(headers,
[email protected]96868202014-01-09 10:38:04686 requested_extensions_,
687 &extensions_,
[email protected]8aba0172014-07-03 12:09:53688 &failure_message,
[email protected]0be93922014-01-29 00:42:45689 extension_params_.get())) {
[email protected]d51365e2013-11-27 10:46:52690 return OK;
691 }
[email protected]8aba0172014-07-03 12:09:53692 set_failure_message("Error during WebSocket handshake: " + failure_message);
[email protected]d51365e2013-11-27 10:46:52693 return ERR_INVALID_RESPONSE;
694}
695
[email protected]8aba0172014-07-03 12:09:53696void WebSocketBasicHandshakeStream::set_failure_message(
697 const std::string& failure_message) {
698 *failure_message_ = failure_message;
699}
700
[email protected]d51365e2013-11-27 10:46:52701} // namespace net