blob: 6e6ae09d9b8149bd7b06eb52380ca8b72c359665 [file] [log] [blame]
[email protected]473282d2013-07-02 11:57:071// 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_stream.h"
6
dchengc7eeda422015-12-26 03:56:487#include <utility>
8
[email protected]473282d2013-07-02 11:57:079#include "base/logging.h"
[email protected]efa9e732013-11-29 02:55:0510#include "base/memory/scoped_ptr.h"
asvitkinec3c93722015-06-17 14:48:3711#include "base/metrics/histogram_macros.h"
[email protected]f7e98ca2014-06-19 12:05:4312#include "base/metrics/sparse_histogram.h"
ricea38fc268c2015-02-09 02:41:2913#include "base/strings/stringprintf.h"
yhirano569e09ce2014-09-11 12:07:2914#include "base/time/time.h"
15#include "base/timer/timer.h"
[email protected]d7599122014-05-24 03:37:2316#include "net/base/load_flags.h"
[email protected]efa9e732013-11-29 02:55:0517#include "net/http/http_request_headers.h"
[email protected]e69c1cd2014-07-29 07:42:2918#include "net/http/http_response_headers.h"
[email protected]efa9e732013-11-29 02:55:0519#include "net/http/http_status_code.h"
[email protected]cba24642014-08-15 20:49:5920#include "net/url_request/redirect_info.h"
[email protected]efa9e732013-11-29 02:55:0521#include "net/url_request/url_request.h"
22#include "net/url_request/url_request_context.h"
23#include "net/websockets/websocket_errors.h"
[email protected]a62449522014-06-05 11:11:1524#include "net/websockets/websocket_event_interface.h"
[email protected]efa9e732013-11-29 02:55:0525#include "net/websockets/websocket_handshake_constants.h"
26#include "net/websockets/websocket_handshake_stream_base.h"
27#include "net/websockets/websocket_handshake_stream_create_helper.h"
[email protected]efa9e732013-11-29 02:55:0528#include "url/gurl.h"
mkwst4997ce82015-07-25 12:00:0529#include "url/origin.h"
[email protected]473282d2013-07-02 11:57:0730
31namespace net {
[email protected]efa9e732013-11-29 02:55:0532namespace {
33
yhirano569e09ce2014-09-11 12:07:2934// The timeout duration of WebSocket handshake.
35// It is defined as the same value as the TCP connection timeout value in
36// net/socket/websocket_transport_client_socket_pool.cc to make it hard for
37// JavaScript programs to recognize the timeout cause.
38const int kHandshakeTimeoutIntervalInSeconds = 240;
39
[email protected]efa9e732013-11-29 02:55:0540class StreamRequestImpl;
41
42class Delegate : public URLRequest::Delegate {
43 public:
[email protected]1e0a16a2014-04-04 16:18:0444 enum HandshakeResult {
45 INCOMPLETE,
46 CONNECTED,
47 FAILED,
48 NUM_HANDSHAKE_RESULT_TYPES,
49 };
50
51 explicit Delegate(StreamRequestImpl* owner)
52 : owner_(owner), result_(INCOMPLETE) {}
dchengb03027d2014-10-21 12:00:2053 ~Delegate() override {
[email protected]1e0a16a2014-04-04 16:18:0454 UMA_HISTOGRAM_ENUMERATION(
55 "Net.WebSocket.HandshakeResult", result_, NUM_HANDSHAKE_RESULT_TYPES);
56 }
[email protected]efa9e732013-11-29 02:55:0557
58 // Implementation of URLRequest::Delegate methods.
dchengb03027d2014-10-21 12:00:2059 void OnReceivedRedirect(URLRequest* request,
60 const RedirectInfo& redirect_info,
Adam Ricecb76ac62015-02-20 05:33:2561 bool* defer_redirect) override;
[email protected]a62449522014-06-05 11:11:1562
dchengb03027d2014-10-21 12:00:2063 void OnResponseStarted(URLRequest* request) override;
[email protected]efa9e732013-11-29 02:55:0564
dchengb03027d2014-10-21 12:00:2065 void OnAuthRequired(URLRequest* request,
66 AuthChallengeInfo* auth_info) override;
[email protected]efa9e732013-11-29 02:55:0567
dchengb03027d2014-10-21 12:00:2068 void OnCertificateRequested(URLRequest* request,
69 SSLCertRequestInfo* cert_request_info) override;
[email protected]efa9e732013-11-29 02:55:0570
dchengb03027d2014-10-21 12:00:2071 void OnSSLCertificateError(URLRequest* request,
72 const SSLInfo& ssl_info,
73 bool fatal) override;
[email protected]efa9e732013-11-29 02:55:0574
dchengb03027d2014-10-21 12:00:2075 void OnReadCompleted(URLRequest* request, int bytes_read) override;
[email protected]efa9e732013-11-29 02:55:0576
77 private:
78 StreamRequestImpl* owner_;
[email protected]1e0a16a2014-04-04 16:18:0479 HandshakeResult result_;
[email protected]efa9e732013-11-29 02:55:0580};
81
82class StreamRequestImpl : public WebSocketStreamRequest {
83 public:
84 StreamRequestImpl(
85 const GURL& url,
86 const URLRequestContext* context,
mkwst4997ce82015-07-25 12:00:0587 const url::Origin& origin,
[email protected]efa9e732013-11-29 02:55:0588 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate,
[email protected]490e38f42014-05-26 23:44:1689 scoped_ptr<WebSocketHandshakeStreamCreateHelper> create_helper)
[email protected]efa9e732013-11-29 02:55:0590 : delegate_(new Delegate(this)),
davidben151423e2015-03-23 18:48:3691 url_request_(
92 context->CreateRequest(url, DEFAULT_PRIORITY, delegate_.get())),
dchengc7eeda422015-12-26 03:56:4893 connect_delegate_(std::move(connect_delegate)),
[email protected]490e38f42014-05-26 23:44:1694 create_helper_(create_helper.release()) {
[email protected]8aba0172014-07-03 12:09:5395 create_helper_->set_failure_message(&failure_message_);
[email protected]490e38f42014-05-26 23:44:1696 HttpRequestHeaders headers;
97 headers.SetHeader(websockets::kUpgrade, websockets::kWebSocketLowercase);
98 headers.SetHeader(HttpRequestHeaders::kConnection, websockets::kUpgrade);
mkwst4997ce82015-07-25 12:00:0599 headers.SetHeader(HttpRequestHeaders::kOrigin, origin.Serialize());
[email protected]490e38f42014-05-26 23:44:16100 headers.SetHeader(websockets::kSecWebSocketVersion,
101 websockets::kSupportedVersion);
[email protected]f7022f32014-08-21 16:32:19102 url_request_->SetExtraRequestHeaders(headers);
[email protected]490e38f42014-05-26 23:44:16103
104 // This passes the ownership of |create_helper_| to |url_request_|.
[email protected]f7022f32014-08-21 16:32:19105 url_request_->SetUserData(
[email protected]490e38f42014-05-26 23:44:16106 WebSocketHandshakeStreamBase::CreateHelper::DataKey(),
107 create_helper_);
baranovich1b32ffb2015-01-15 14:44:52108 url_request_->SetLoadFlags(LOAD_DISABLE_CACHE | LOAD_BYPASS_CACHE);
[email protected]490e38f42014-05-26 23:44:16109 }
[email protected]efa9e732013-11-29 02:55:05110
111 // Destroying this object destroys the URLRequest, which cancels the request
112 // and so terminates the handshake if it is incomplete.
dchengb03027d2014-10-21 12:00:20113 ~StreamRequestImpl() override {}
[email protected]efa9e732013-11-29 02:55:05114
yhirano569e09ce2014-09-11 12:07:29115 void Start(scoped_ptr<base::Timer> timer) {
116 DCHECK(timer);
brettwbc44c0a92015-02-20 22:30:39117 base::TimeDelta timeout(base::TimeDelta::FromSeconds(
yhirano569e09ce2014-09-11 12:07:29118 kHandshakeTimeoutIntervalInSeconds));
dchengc7eeda422015-12-26 03:56:48119 timer_ = std::move(timer);
yhirano569e09ce2014-09-11 12:07:29120 timer_->Start(FROM_HERE, timeout,
121 base::Bind(&StreamRequestImpl::OnTimeout,
122 base::Unretained(this)));
[email protected]f7022f32014-08-21 16:32:19123 url_request_->Start();
[email protected]490e38f42014-05-26 23:44:16124 }
[email protected]efa9e732013-11-29 02:55:05125
126 void PerformUpgrade() {
yhirano569e09ce2014-09-11 12:07:29127 DCHECK(timer_);
128 timer_->Stop();
[email protected]dfae79982014-07-04 14:03:05129 connect_delegate_->OnSuccess(create_helper_->Upgrade());
[email protected]efa9e732013-11-29 02:55:05130 }
131
ricea38fc268c2015-02-09 02:41:29132 std::string FailureMessageFromNetError() {
133 int error = url_request_->status().error();
134 if (error == ERR_TUNNEL_CONNECTION_FAILED) {
135 // This error is common and confusing, so special-case it.
136 // TODO(ricea): Include the HostPortPair of the selected proxy server in
137 // the error message. This is not currently possible because it isn't set
138 // in HttpResponseInfo when a ERR_TUNNEL_CONNECTION_FAILED error happens.
139 return "Establishing a tunnel via proxy server failed.";
140 } else {
141 return std::string("Error in connection establishment: ") +
142 ErrorToString(url_request_->status().error());
143 }
144 }
145
[email protected]efa9e732013-11-29 02:55:05146 void ReportFailure() {
yhirano569e09ce2014-09-11 12:07:29147 DCHECK(timer_);
148 timer_->Stop();
[email protected]8aba0172014-07-03 12:09:53149 if (failure_message_.empty()) {
[email protected]f7022f32014-08-21 16:32:19150 switch (url_request_->status().status()) {
[email protected]96868202014-01-09 10:38:04151 case URLRequestStatus::SUCCESS:
152 case URLRequestStatus::IO_PENDING:
153 break;
154 case URLRequestStatus::CANCELED:
yhirano569e09ce2014-09-11 12:07:29155 if (url_request_->status().error() == ERR_TIMED_OUT)
156 failure_message_ = "WebSocket opening handshake timed out";
157 else
158 failure_message_ = "WebSocket opening handshake was canceled";
[email protected]96868202014-01-09 10:38:04159 break;
160 case URLRequestStatus::FAILED:
ricea38fc268c2015-02-09 02:41:29161 failure_message_ = FailureMessageFromNetError();
[email protected]96868202014-01-09 10:38:04162 break;
163 }
164 }
[email protected]e69c1cd2014-07-29 07:42:29165 ReportFailureWithMessage(failure_message_);
166 }
167
168 void ReportFailureWithMessage(const std::string& failure_message) {
169 connect_delegate_->OnFailure(failure_message);
170 }
171
172 void OnFinishOpeningHandshake() {
173 WebSocketDispatchOnFinishOpeningHandshake(connect_delegate(),
[email protected]f7022f32014-08-21 16:32:19174 url_request_->url(),
175 url_request_->response_headers(),
176 url_request_->response_time());
[email protected]efa9e732013-11-29 02:55:05177 }
178
[email protected]a62449522014-06-05 11:11:15179 WebSocketStream::ConnectDelegate* connect_delegate() const {
180 return connect_delegate_.get();
181 }
182
yhirano569e09ce2014-09-11 12:07:29183 void OnTimeout() {
184 url_request_->CancelWithError(ERR_TIMED_OUT);
185 }
186
[email protected]efa9e732013-11-29 02:55:05187 private:
188 // |delegate_| needs to be declared before |url_request_| so that it gets
189 // initialised first.
190 scoped_ptr<Delegate> delegate_;
191
192 // Deleting the StreamRequestImpl object deletes this URLRequest object,
193 // cancelling the whole connection.
[email protected]f7022f32014-08-21 16:32:19194 scoped_ptr<URLRequest> url_request_;
[email protected]efa9e732013-11-29 02:55:05195
196 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate_;
197
198 // Owned by the URLRequest.
199 WebSocketHandshakeStreamCreateHelper* create_helper_;
[email protected]8aba0172014-07-03 12:09:53200
201 // The failure message supplied by WebSocketBasicHandshakeStream, if any.
202 std::string failure_message_;
yhirano569e09ce2014-09-11 12:07:29203
204 // A timer for handshake timeout.
205 scoped_ptr<base::Timer> timer_;
[email protected]efa9e732013-11-29 02:55:05206};
207
[email protected]a62449522014-06-05 11:11:15208class SSLErrorCallbacks : public WebSocketEventInterface::SSLErrorCallbacks {
209 public:
210 explicit SSLErrorCallbacks(URLRequest* url_request)
211 : url_request_(url_request) {}
212
dchengb03027d2014-10-21 12:00:20213 void CancelSSLRequest(int error, const SSLInfo* ssl_info) override {
[email protected]a62449522014-06-05 11:11:15214 if (ssl_info) {
215 url_request_->CancelWithSSLError(error, *ssl_info);
216 } else {
217 url_request_->CancelWithError(error);
218 }
219 }
220
dchengb03027d2014-10-21 12:00:20221 void ContinueSSLRequest() override {
[email protected]a62449522014-06-05 11:11:15222 url_request_->ContinueDespiteLastError();
223 }
224
225 private:
226 URLRequest* url_request_;
227};
228
Adam Ricecb76ac62015-02-20 05:33:25229void Delegate::OnReceivedRedirect(URLRequest* request,
230 const RedirectInfo& redirect_info,
231 bool* defer_redirect) {
232 // This code should never be reached for externally generated redirects,
233 // as WebSocketBasicHandshakeStream is responsible for filtering out
234 // all response codes besides 101, 401, and 407. As such, the URLRequest
235 // should never see a redirect sent over the network. However, internal
236 // redirects also result in this method being called, such as those
237 // caused by HSTS.
238 // Because it's security critical to prevent externally-generated
239 // redirects in WebSockets, perform additional checks to ensure this
240 // is only internal.
241 GURL::Replacements replacements;
242 replacements.SetSchemeStr("wss");
243 GURL expected_url = request->original_url().ReplaceComponents(replacements);
244 if (redirect_info.new_method != "GET" ||
245 redirect_info.new_url != expected_url) {
246 // This should not happen.
247 DLOG(FATAL) << "Unauthorized WebSocket redirect to "
248 << redirect_info.new_method << " "
249 << redirect_info.new_url.spec();
250 request->Cancel();
251 }
252}
253
[email protected]efa9e732013-11-29 02:55:05254void Delegate::OnResponseStarted(URLRequest* request) {
[email protected]f7e98ca2014-06-19 12:05:43255 // All error codes, including OK and ABORTED, as with
256 // Net.ErrorCodesForMainFrame3
257 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.WebSocket.ErrorCodes",
258 -request->status().error());
[email protected]a62449522014-06-05 11:11:15259 if (!request->status().is_success()) {
260 DVLOG(3) << "OnResponseStarted (request failed)";
261 owner_->ReportFailure();
262 return;
263 }
[email protected]f7e98ca2014-06-19 12:05:43264 const int response_code = request->GetResponseCode();
265 DVLOG(3) << "OnResponseStarted (response code " << response_code << ")";
266 switch (response_code) {
[email protected]efa9e732013-11-29 02:55:05267 case HTTP_SWITCHING_PROTOCOLS:
[email protected]1e0a16a2014-04-04 16:18:04268 result_ = CONNECTED;
[email protected]efa9e732013-11-29 02:55:05269 owner_->PerformUpgrade();
270 return;
271
272 case HTTP_UNAUTHORIZED:
[email protected]e69c1cd2014-07-29 07:42:29273 result_ = FAILED;
274 owner_->OnFinishOpeningHandshake();
275 owner_->ReportFailureWithMessage(
276 "HTTP Authentication failed; no valid credentials available");
277 return;
278
[email protected]efa9e732013-11-29 02:55:05279 case HTTP_PROXY_AUTHENTICATION_REQUIRED:
[email protected]e69c1cd2014-07-29 07:42:29280 result_ = FAILED;
281 owner_->OnFinishOpeningHandshake();
282 owner_->ReportFailureWithMessage("Proxy authentication failed");
[email protected]efa9e732013-11-29 02:55:05283 return;
284
285 default:
[email protected]1e0a16a2014-04-04 16:18:04286 result_ = FAILED;
[email protected]efa9e732013-11-29 02:55:05287 owner_->ReportFailure();
288 }
289}
290
291void Delegate::OnAuthRequired(URLRequest* request,
292 AuthChallengeInfo* auth_info) {
[email protected]a62449522014-06-05 11:11:15293 // This should only be called if credentials are not already stored.
[email protected]efa9e732013-11-29 02:55:05294 request->CancelAuth();
295}
296
297void Delegate::OnCertificateRequested(URLRequest* request,
298 SSLCertRequestInfo* cert_request_info) {
[email protected]a62449522014-06-05 11:11:15299 // This method is called when a client certificate is requested, and the
300 // request context does not already contain a client certificate selection for
301 // the endpoint. In this case, a main frame resource request would pop-up UI
302 // to permit selection of a client certificate, but since WebSockets are
303 // sub-resources they should not pop-up UI and so there is nothing more we can
304 // do.
305 request->Cancel();
[email protected]efa9e732013-11-29 02:55:05306}
307
308void Delegate::OnSSLCertificateError(URLRequest* request,
309 const SSLInfo& ssl_info,
310 bool fatal) {
[email protected]a62449522014-06-05 11:11:15311 owner_->connect_delegate()->OnSSLCertificateError(
312 scoped_ptr<WebSocketEventInterface::SSLErrorCallbacks>(
313 new SSLErrorCallbacks(request)),
314 ssl_info,
315 fatal);
[email protected]efa9e732013-11-29 02:55:05316}
317
318void Delegate::OnReadCompleted(URLRequest* request, int bytes_read) {
319 NOTREACHED();
320}
321
[email protected]efa9e732013-11-29 02:55:05322} // namespace
[email protected]473282d2013-07-02 11:57:07323
324WebSocketStreamRequest::~WebSocketStreamRequest() {}
325
326WebSocketStream::WebSocketStream() {}
327WebSocketStream::~WebSocketStream() {}
328
329WebSocketStream::ConnectDelegate::~ConnectDelegate() {}
330
[email protected]473282d2013-07-02 11:57:07331scoped_ptr<WebSocketStreamRequest> WebSocketStream::CreateAndConnectStream(
332 const GURL& socket_url,
333 const std::vector<std::string>& requested_subprotocols,
mkwst4997ce82015-07-25 12:00:05334 const url::Origin& origin,
[email protected]473282d2013-07-02 11:57:07335 URLRequestContext* url_request_context,
336 const BoundNetLog& net_log,
337 scoped_ptr<ConnectDelegate> connect_delegate) {
[email protected]efa9e732013-11-29 02:55:05338 scoped_ptr<WebSocketHandshakeStreamCreateHelper> create_helper(
[email protected]cd48ed12014-01-22 14:34:22339 new WebSocketHandshakeStreamCreateHelper(connect_delegate.get(),
340 requested_subprotocols));
dchengc7eeda422015-12-26 03:56:48341 scoped_ptr<StreamRequestImpl> request(new StreamRequestImpl(
342 socket_url, url_request_context, origin, std::move(connect_delegate),
343 std::move(create_helper)));
yhirano569e09ce2014-09-11 12:07:29344 request->Start(scoped_ptr<base::Timer>(new base::Timer(false, false)));
dchengc7eeda422015-12-26 03:56:48345 return std::move(request);
[email protected]efa9e732013-11-29 02:55:05346}
347
348// This is declared in websocket_test_util.h.
349scoped_ptr<WebSocketStreamRequest> CreateAndConnectStreamForTesting(
[email protected]7824cf82014-03-13 10:22:57350 const GURL& socket_url,
351 scoped_ptr<WebSocketHandshakeStreamCreateHelper> create_helper,
mkwst4997ce82015-07-25 12:00:05352 const url::Origin& origin,
[email protected]7824cf82014-03-13 10:22:57353 URLRequestContext* url_request_context,
354 const BoundNetLog& net_log,
yhirano569e09ce2014-09-11 12:07:29355 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate,
356 scoped_ptr<base::Timer> timer) {
dchengc7eeda422015-12-26 03:56:48357 scoped_ptr<StreamRequestImpl> request(new StreamRequestImpl(
358 socket_url, url_request_context, origin, std::move(connect_delegate),
359 std::move(create_helper)));
360 request->Start(std::move(timer));
361 return std::move(request);
[email protected]473282d2013-07-02 11:57:07362}
363
[email protected]e69c1cd2014-07-29 07:42:29364void WebSocketDispatchOnFinishOpeningHandshake(
365 WebSocketStream::ConnectDelegate* connect_delegate,
366 const GURL& url,
367 const scoped_refptr<HttpResponseHeaders>& headers,
368 base::Time response_time) {
369 DCHECK(connect_delegate);
dchengb206dc412014-08-26 19:46:23370 if (headers.get()) {
[email protected]e69c1cd2014-07-29 07:42:29371 connect_delegate->OnFinishOpeningHandshake(make_scoped_ptr(
372 new WebSocketHandshakeResponseInfo(url,
373 headers->response_code(),
374 headers->GetStatusText(),
375 headers,
376 response_time)));
377 }
378}
379
[email protected]473282d2013-07-02 11:57:07380} // namespace net