blob: be2bc16f6564a0498e0515588c161eb393a1715b [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
7#include "base/logging.h"
[email protected]efa9e732013-11-29 02:55:058#include "base/memory/scoped_ptr.h"
[email protected]1e0a16a2014-04-04 16:18:049#include "base/metrics/histogram.h"
[email protected]f7e98ca2014-06-19 12:05:4310#include "base/metrics/sparse_histogram.h"
yhirano569e09ce2014-09-11 12:07:2911#include "base/time/time.h"
12#include "base/timer/timer.h"
[email protected]d7599122014-05-24 03:37:2313#include "net/base/load_flags.h"
[email protected]efa9e732013-11-29 02:55:0514#include "net/http/http_request_headers.h"
[email protected]e69c1cd2014-07-29 07:42:2915#include "net/http/http_response_headers.h"
[email protected]efa9e732013-11-29 02:55:0516#include "net/http/http_status_code.h"
[email protected]cba24642014-08-15 20:49:5917#include "net/url_request/redirect_info.h"
[email protected]efa9e732013-11-29 02:55:0518#include "net/url_request/url_request.h"
19#include "net/url_request/url_request_context.h"
20#include "net/websockets/websocket_errors.h"
[email protected]a62449522014-06-05 11:11:1521#include "net/websockets/websocket_event_interface.h"
[email protected]efa9e732013-11-29 02:55:0522#include "net/websockets/websocket_handshake_constants.h"
23#include "net/websockets/websocket_handshake_stream_base.h"
24#include "net/websockets/websocket_handshake_stream_create_helper.h"
25#include "net/websockets/websocket_test_util.h"
26#include "url/gurl.h"
[email protected]7824cf82014-03-13 10:22:5727#include "url/origin.h"
[email protected]473282d2013-07-02 11:57:0728
29namespace net {
[email protected]efa9e732013-11-29 02:55:0530namespace {
31
yhirano569e09ce2014-09-11 12:07:2932// The timeout duration of WebSocket handshake.
33// It is defined as the same value as the TCP connection timeout value in
34// net/socket/websocket_transport_client_socket_pool.cc to make it hard for
35// JavaScript programs to recognize the timeout cause.
36const int kHandshakeTimeoutIntervalInSeconds = 240;
37
[email protected]efa9e732013-11-29 02:55:0538class StreamRequestImpl;
39
40class Delegate : public URLRequest::Delegate {
41 public:
[email protected]1e0a16a2014-04-04 16:18:0442 enum HandshakeResult {
43 INCOMPLETE,
44 CONNECTED,
45 FAILED,
46 NUM_HANDSHAKE_RESULT_TYPES,
47 };
48
49 explicit Delegate(StreamRequestImpl* owner)
50 : owner_(owner), result_(INCOMPLETE) {}
51 virtual ~Delegate() {
52 UMA_HISTOGRAM_ENUMERATION(
53 "Net.WebSocket.HandshakeResult", result_, NUM_HANDSHAKE_RESULT_TYPES);
54 }
[email protected]efa9e732013-11-29 02:55:0555
56 // Implementation of URLRequest::Delegate methods.
[email protected]a62449522014-06-05 11:11:1557 virtual void OnReceivedRedirect(URLRequest* request,
[email protected]cba24642014-08-15 20:49:5958 const RedirectInfo& redirect_info,
[email protected]a62449522014-06-05 11:11:1559 bool* defer_redirect) OVERRIDE {
60 // HTTP status codes returned by HttpStreamParser are filtered by
61 // WebSocketBasicHandshakeStream, and only 101, 401 and 407 are permitted
62 // back up the stack to HttpNetworkTransaction. In particular, redirect
63 // codes are never allowed, and so URLRequest never sees a redirect on a
64 // WebSocket request.
65 NOTREACHED();
66 }
67
[email protected]efa9e732013-11-29 02:55:0568 virtual void OnResponseStarted(URLRequest* request) OVERRIDE;
69
70 virtual void OnAuthRequired(URLRequest* request,
71 AuthChallengeInfo* auth_info) OVERRIDE;
72
73 virtual void OnCertificateRequested(URLRequest* request,
74 SSLCertRequestInfo* cert_request_info)
75 OVERRIDE;
76
77 virtual void OnSSLCertificateError(URLRequest* request,
78 const SSLInfo& ssl_info,
79 bool fatal) OVERRIDE;
80
81 virtual void OnReadCompleted(URLRequest* request, int bytes_read) OVERRIDE;
82
83 private:
84 StreamRequestImpl* owner_;
[email protected]1e0a16a2014-04-04 16:18:0485 HandshakeResult result_;
[email protected]efa9e732013-11-29 02:55:0586};
87
88class StreamRequestImpl : public WebSocketStreamRequest {
89 public:
90 StreamRequestImpl(
91 const GURL& url,
92 const URLRequestContext* context,
[email protected]490e38f42014-05-26 23:44:1693 const url::Origin& origin,
[email protected]efa9e732013-11-29 02:55:0594 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate,
[email protected]490e38f42014-05-26 23:44:1695 scoped_ptr<WebSocketHandshakeStreamCreateHelper> create_helper)
[email protected]efa9e732013-11-29 02:55:0596 : delegate_(new Delegate(this)),
[email protected]f7022f32014-08-21 16:32:1997 url_request_(context->CreateRequest(url, DEFAULT_PRIORITY,
98 delegate_.get(), NULL)),
[email protected]efa9e732013-11-29 02:55:0599 connect_delegate_(connect_delegate.Pass()),
[email protected]490e38f42014-05-26 23:44:16100 create_helper_(create_helper.release()) {
[email protected]8aba0172014-07-03 12:09:53101 create_helper_->set_failure_message(&failure_message_);
[email protected]490e38f42014-05-26 23:44:16102 HttpRequestHeaders headers;
103 headers.SetHeader(websockets::kUpgrade, websockets::kWebSocketLowercase);
104 headers.SetHeader(HttpRequestHeaders::kConnection, websockets::kUpgrade);
105 headers.SetHeader(HttpRequestHeaders::kOrigin, origin.string());
106 headers.SetHeader(websockets::kSecWebSocketVersion,
107 websockets::kSupportedVersion);
[email protected]f7022f32014-08-21 16:32:19108 url_request_->SetExtraRequestHeaders(headers);
[email protected]490e38f42014-05-26 23:44:16109
110 // This passes the ownership of |create_helper_| to |url_request_|.
[email protected]f7022f32014-08-21 16:32:19111 url_request_->SetUserData(
[email protected]490e38f42014-05-26 23:44:16112 WebSocketHandshakeStreamBase::CreateHelper::DataKey(),
113 create_helper_);
[email protected]f7022f32014-08-21 16:32:19114 url_request_->SetLoadFlags(LOAD_DISABLE_CACHE |
115 LOAD_BYPASS_CACHE |
116 LOAD_DO_NOT_PROMPT_FOR_LOGIN);
[email protected]490e38f42014-05-26 23:44:16117 }
[email protected]efa9e732013-11-29 02:55:05118
119 // Destroying this object destroys the URLRequest, which cancels the request
120 // and so terminates the handshake if it is incomplete.
121 virtual ~StreamRequestImpl() {}
122
yhirano569e09ce2014-09-11 12:07:29123 void Start(scoped_ptr<base::Timer> timer) {
124 DCHECK(timer);
125 TimeDelta timeout(TimeDelta::FromSeconds(
126 kHandshakeTimeoutIntervalInSeconds));
127 timer_ = timer.Pass();
128 timer_->Start(FROM_HERE, timeout,
129 base::Bind(&StreamRequestImpl::OnTimeout,
130 base::Unretained(this)));
[email protected]f7022f32014-08-21 16:32:19131 url_request_->Start();
[email protected]490e38f42014-05-26 23:44:16132 }
[email protected]efa9e732013-11-29 02:55:05133
134 void PerformUpgrade() {
yhirano569e09ce2014-09-11 12:07:29135 DCHECK(timer_);
136 timer_->Stop();
[email protected]dfae79982014-07-04 14:03:05137 connect_delegate_->OnSuccess(create_helper_->Upgrade());
[email protected]efa9e732013-11-29 02:55:05138 }
139
140 void ReportFailure() {
yhirano569e09ce2014-09-11 12:07:29141 DCHECK(timer_);
142 timer_->Stop();
[email protected]8aba0172014-07-03 12:09:53143 if (failure_message_.empty()) {
[email protected]f7022f32014-08-21 16:32:19144 switch (url_request_->status().status()) {
[email protected]96868202014-01-09 10:38:04145 case URLRequestStatus::SUCCESS:
146 case URLRequestStatus::IO_PENDING:
147 break;
148 case URLRequestStatus::CANCELED:
yhirano569e09ce2014-09-11 12:07:29149 if (url_request_->status().error() == ERR_TIMED_OUT)
150 failure_message_ = "WebSocket opening handshake timed out";
151 else
152 failure_message_ = "WebSocket opening handshake was canceled";
[email protected]96868202014-01-09 10:38:04153 break;
154 case URLRequestStatus::FAILED:
[email protected]8aba0172014-07-03 12:09:53155 failure_message_ =
[email protected]96868202014-01-09 10:38:04156 std::string("Error in connection establishment: ") +
[email protected]f7022f32014-08-21 16:32:19157 ErrorToString(url_request_->status().error());
[email protected]96868202014-01-09 10:38:04158 break;
159 }
160 }
[email protected]e69c1cd2014-07-29 07:42:29161 ReportFailureWithMessage(failure_message_);
162 }
163
164 void ReportFailureWithMessage(const std::string& failure_message) {
165 connect_delegate_->OnFailure(failure_message);
166 }
167
168 void OnFinishOpeningHandshake() {
169 WebSocketDispatchOnFinishOpeningHandshake(connect_delegate(),
[email protected]f7022f32014-08-21 16:32:19170 url_request_->url(),
171 url_request_->response_headers(),
172 url_request_->response_time());
[email protected]efa9e732013-11-29 02:55:05173 }
174
[email protected]a62449522014-06-05 11:11:15175 WebSocketStream::ConnectDelegate* connect_delegate() const {
176 return connect_delegate_.get();
177 }
178
yhirano569e09ce2014-09-11 12:07:29179 void OnTimeout() {
180 url_request_->CancelWithError(ERR_TIMED_OUT);
181 }
182
[email protected]efa9e732013-11-29 02:55:05183 private:
184 // |delegate_| needs to be declared before |url_request_| so that it gets
185 // initialised first.
186 scoped_ptr<Delegate> delegate_;
187
188 // Deleting the StreamRequestImpl object deletes this URLRequest object,
189 // cancelling the whole connection.
[email protected]f7022f32014-08-21 16:32:19190 scoped_ptr<URLRequest> url_request_;
[email protected]efa9e732013-11-29 02:55:05191
192 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate_;
193
194 // Owned by the URLRequest.
195 WebSocketHandshakeStreamCreateHelper* create_helper_;
[email protected]8aba0172014-07-03 12:09:53196
197 // The failure message supplied by WebSocketBasicHandshakeStream, if any.
198 std::string failure_message_;
yhirano569e09ce2014-09-11 12:07:29199
200 // A timer for handshake timeout.
201 scoped_ptr<base::Timer> timer_;
[email protected]efa9e732013-11-29 02:55:05202};
203
[email protected]a62449522014-06-05 11:11:15204class SSLErrorCallbacks : public WebSocketEventInterface::SSLErrorCallbacks {
205 public:
206 explicit SSLErrorCallbacks(URLRequest* url_request)
207 : url_request_(url_request) {}
208
209 virtual void CancelSSLRequest(int error, const SSLInfo* ssl_info) OVERRIDE {
210 if (ssl_info) {
211 url_request_->CancelWithSSLError(error, *ssl_info);
212 } else {
213 url_request_->CancelWithError(error);
214 }
215 }
216
217 virtual void ContinueSSLRequest() OVERRIDE {
218 url_request_->ContinueDespiteLastError();
219 }
220
221 private:
222 URLRequest* url_request_;
223};
224
[email protected]efa9e732013-11-29 02:55:05225void Delegate::OnResponseStarted(URLRequest* request) {
[email protected]f7e98ca2014-06-19 12:05:43226 // All error codes, including OK and ABORTED, as with
227 // Net.ErrorCodesForMainFrame3
228 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.WebSocket.ErrorCodes",
229 -request->status().error());
[email protected]a62449522014-06-05 11:11:15230 if (!request->status().is_success()) {
231 DVLOG(3) << "OnResponseStarted (request failed)";
232 owner_->ReportFailure();
233 return;
234 }
[email protected]f7e98ca2014-06-19 12:05:43235 const int response_code = request->GetResponseCode();
236 DVLOG(3) << "OnResponseStarted (response code " << response_code << ")";
237 switch (response_code) {
[email protected]efa9e732013-11-29 02:55:05238 case HTTP_SWITCHING_PROTOCOLS:
[email protected]1e0a16a2014-04-04 16:18:04239 result_ = CONNECTED;
[email protected]efa9e732013-11-29 02:55:05240 owner_->PerformUpgrade();
241 return;
242
243 case HTTP_UNAUTHORIZED:
[email protected]e69c1cd2014-07-29 07:42:29244 result_ = FAILED;
245 owner_->OnFinishOpeningHandshake();
246 owner_->ReportFailureWithMessage(
247 "HTTP Authentication failed; no valid credentials available");
248 return;
249
[email protected]efa9e732013-11-29 02:55:05250 case HTTP_PROXY_AUTHENTICATION_REQUIRED:
[email protected]e69c1cd2014-07-29 07:42:29251 result_ = FAILED;
252 owner_->OnFinishOpeningHandshake();
253 owner_->ReportFailureWithMessage("Proxy authentication failed");
[email protected]efa9e732013-11-29 02:55:05254 return;
255
256 default:
[email protected]1e0a16a2014-04-04 16:18:04257 result_ = FAILED;
[email protected]efa9e732013-11-29 02:55:05258 owner_->ReportFailure();
259 }
260}
261
262void Delegate::OnAuthRequired(URLRequest* request,
263 AuthChallengeInfo* auth_info) {
[email protected]a62449522014-06-05 11:11:15264 // This should only be called if credentials are not already stored.
[email protected]efa9e732013-11-29 02:55:05265 request->CancelAuth();
266}
267
268void Delegate::OnCertificateRequested(URLRequest* request,
269 SSLCertRequestInfo* cert_request_info) {
[email protected]a62449522014-06-05 11:11:15270 // This method is called when a client certificate is requested, and the
271 // request context does not already contain a client certificate selection for
272 // the endpoint. In this case, a main frame resource request would pop-up UI
273 // to permit selection of a client certificate, but since WebSockets are
274 // sub-resources they should not pop-up UI and so there is nothing more we can
275 // do.
276 request->Cancel();
[email protected]efa9e732013-11-29 02:55:05277}
278
279void Delegate::OnSSLCertificateError(URLRequest* request,
280 const SSLInfo& ssl_info,
281 bool fatal) {
[email protected]a62449522014-06-05 11:11:15282 owner_->connect_delegate()->OnSSLCertificateError(
283 scoped_ptr<WebSocketEventInterface::SSLErrorCallbacks>(
284 new SSLErrorCallbacks(request)),
285 ssl_info,
286 fatal);
[email protected]efa9e732013-11-29 02:55:05287}
288
289void Delegate::OnReadCompleted(URLRequest* request, int bytes_read) {
290 NOTREACHED();
291}
292
[email protected]efa9e732013-11-29 02:55:05293} // namespace
[email protected]473282d2013-07-02 11:57:07294
295WebSocketStreamRequest::~WebSocketStreamRequest() {}
296
297WebSocketStream::WebSocketStream() {}
298WebSocketStream::~WebSocketStream() {}
299
300WebSocketStream::ConnectDelegate::~ConnectDelegate() {}
301
[email protected]473282d2013-07-02 11:57:07302scoped_ptr<WebSocketStreamRequest> WebSocketStream::CreateAndConnectStream(
303 const GURL& socket_url,
304 const std::vector<std::string>& requested_subprotocols,
[email protected]7824cf82014-03-13 10:22:57305 const url::Origin& origin,
[email protected]473282d2013-07-02 11:57:07306 URLRequestContext* url_request_context,
307 const BoundNetLog& net_log,
308 scoped_ptr<ConnectDelegate> connect_delegate) {
[email protected]efa9e732013-11-29 02:55:05309 scoped_ptr<WebSocketHandshakeStreamCreateHelper> create_helper(
[email protected]cd48ed12014-01-22 14:34:22310 new WebSocketHandshakeStreamCreateHelper(connect_delegate.get(),
311 requested_subprotocols));
[email protected]490e38f42014-05-26 23:44:16312 scoped_ptr<StreamRequestImpl> request(
313 new StreamRequestImpl(socket_url,
314 url_request_context,
315 origin,
316 connect_delegate.Pass(),
317 create_helper.Pass()));
yhirano569e09ce2014-09-11 12:07:29318 request->Start(scoped_ptr<base::Timer>(new base::Timer(false, false)));
[email protected]490e38f42014-05-26 23:44:16319 return request.PassAs<WebSocketStreamRequest>();
[email protected]efa9e732013-11-29 02:55:05320}
321
322// This is declared in websocket_test_util.h.
323scoped_ptr<WebSocketStreamRequest> CreateAndConnectStreamForTesting(
[email protected]7824cf82014-03-13 10:22:57324 const GURL& socket_url,
325 scoped_ptr<WebSocketHandshakeStreamCreateHelper> create_helper,
326 const url::Origin& origin,
327 URLRequestContext* url_request_context,
328 const BoundNetLog& net_log,
yhirano569e09ce2014-09-11 12:07:29329 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate,
330 scoped_ptr<base::Timer> timer) {
[email protected]490e38f42014-05-26 23:44:16331 scoped_ptr<StreamRequestImpl> request(
332 new StreamRequestImpl(socket_url,
333 url_request_context,
334 origin,
335 connect_delegate.Pass(),
336 create_helper.Pass()));
yhirano569e09ce2014-09-11 12:07:29337 request->Start(timer.Pass());
[email protected]490e38f42014-05-26 23:44:16338 return request.PassAs<WebSocketStreamRequest>();
[email protected]473282d2013-07-02 11:57:07339}
340
[email protected]e69c1cd2014-07-29 07:42:29341void WebSocketDispatchOnFinishOpeningHandshake(
342 WebSocketStream::ConnectDelegate* connect_delegate,
343 const GURL& url,
344 const scoped_refptr<HttpResponseHeaders>& headers,
345 base::Time response_time) {
346 DCHECK(connect_delegate);
dchengb206dc412014-08-26 19:46:23347 if (headers.get()) {
[email protected]e69c1cd2014-07-29 07:42:29348 connect_delegate->OnFinishOpeningHandshake(make_scoped_ptr(
349 new WebSocketHandshakeResponseInfo(url,
350 headers->response_code(),
351 headers->GetStatusText(),
352 headers,
353 response_time)));
354 }
355}
356
[email protected]473282d2013-07-02 11:57:07357} // namespace net