blob: 005b6c5984cd66ccdee2f74e55804884c08166fe [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) {}
dchengb03027d2014-10-21 12:00:2051 ~Delegate() override {
[email protected]1e0a16a2014-04-04 16:18:0452 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.
dchengb03027d2014-10-21 12:00:2057 void OnReceivedRedirect(URLRequest* request,
58 const RedirectInfo& redirect_info,
59 bool* defer_redirect) override {
[email protected]a62449522014-06-05 11:11:1560 // 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
dchengb03027d2014-10-21 12:00:2068 void OnResponseStarted(URLRequest* request) override;
[email protected]efa9e732013-11-29 02:55:0569
dchengb03027d2014-10-21 12:00:2070 void OnAuthRequired(URLRequest* request,
71 AuthChallengeInfo* auth_info) override;
[email protected]efa9e732013-11-29 02:55:0572
dchengb03027d2014-10-21 12:00:2073 void OnCertificateRequested(URLRequest* request,
74 SSLCertRequestInfo* cert_request_info) override;
[email protected]efa9e732013-11-29 02:55:0575
dchengb03027d2014-10-21 12:00:2076 void OnSSLCertificateError(URLRequest* request,
77 const SSLInfo& ssl_info,
78 bool fatal) override;
[email protected]efa9e732013-11-29 02:55:0579
dchengb03027d2014-10-21 12:00:2080 void OnReadCompleted(URLRequest* request, int bytes_read) override;
[email protected]efa9e732013-11-29 02:55:0581
82 private:
83 StreamRequestImpl* owner_;
[email protected]1e0a16a2014-04-04 16:18:0484 HandshakeResult result_;
[email protected]efa9e732013-11-29 02:55:0585};
86
87class StreamRequestImpl : public WebSocketStreamRequest {
88 public:
89 StreamRequestImpl(
90 const GURL& url,
91 const URLRequestContext* context,
[email protected]490e38f42014-05-26 23:44:1692 const url::Origin& origin,
[email protected]efa9e732013-11-29 02:55:0593 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate,
[email protected]490e38f42014-05-26 23:44:1694 scoped_ptr<WebSocketHandshakeStreamCreateHelper> create_helper)
[email protected]efa9e732013-11-29 02:55:0595 : delegate_(new Delegate(this)),
[email protected]f7022f32014-08-21 16:32:1996 url_request_(context->CreateRequest(url, DEFAULT_PRIORITY,
97 delegate_.get(), NULL)),
[email protected]efa9e732013-11-29 02:55:0598 connect_delegate_(connect_delegate.Pass()),
[email protected]490e38f42014-05-26 23:44:1699 create_helper_(create_helper.release()) {
[email protected]8aba0172014-07-03 12:09:53100 create_helper_->set_failure_message(&failure_message_);
[email protected]490e38f42014-05-26 23:44:16101 HttpRequestHeaders headers;
102 headers.SetHeader(websockets::kUpgrade, websockets::kWebSocketLowercase);
103 headers.SetHeader(HttpRequestHeaders::kConnection, websockets::kUpgrade);
104 headers.SetHeader(HttpRequestHeaders::kOrigin, origin.string());
105 headers.SetHeader(websockets::kSecWebSocketVersion,
106 websockets::kSupportedVersion);
[email protected]f7022f32014-08-21 16:32:19107 url_request_->SetExtraRequestHeaders(headers);
[email protected]490e38f42014-05-26 23:44:16108
109 // This passes the ownership of |create_helper_| to |url_request_|.
[email protected]f7022f32014-08-21 16:32:19110 url_request_->SetUserData(
[email protected]490e38f42014-05-26 23:44:16111 WebSocketHandshakeStreamBase::CreateHelper::DataKey(),
112 create_helper_);
[email protected]f7022f32014-08-21 16:32:19113 url_request_->SetLoadFlags(LOAD_DISABLE_CACHE |
114 LOAD_BYPASS_CACHE |
115 LOAD_DO_NOT_PROMPT_FOR_LOGIN);
[email protected]490e38f42014-05-26 23:44:16116 }
[email protected]efa9e732013-11-29 02:55:05117
118 // Destroying this object destroys the URLRequest, which cancels the request
119 // and so terminates the handshake if it is incomplete.
dchengb03027d2014-10-21 12:00:20120 ~StreamRequestImpl() override {}
[email protected]efa9e732013-11-29 02:55:05121
yhirano569e09ce2014-09-11 12:07:29122 void Start(scoped_ptr<base::Timer> timer) {
123 DCHECK(timer);
124 TimeDelta timeout(TimeDelta::FromSeconds(
125 kHandshakeTimeoutIntervalInSeconds));
126 timer_ = timer.Pass();
127 timer_->Start(FROM_HERE, timeout,
128 base::Bind(&StreamRequestImpl::OnTimeout,
129 base::Unretained(this)));
[email protected]f7022f32014-08-21 16:32:19130 url_request_->Start();
[email protected]490e38f42014-05-26 23:44:16131 }
[email protected]efa9e732013-11-29 02:55:05132
133 void PerformUpgrade() {
yhirano569e09ce2014-09-11 12:07:29134 DCHECK(timer_);
135 timer_->Stop();
[email protected]dfae79982014-07-04 14:03:05136 connect_delegate_->OnSuccess(create_helper_->Upgrade());
[email protected]efa9e732013-11-29 02:55:05137 }
138
139 void ReportFailure() {
yhirano569e09ce2014-09-11 12:07:29140 DCHECK(timer_);
141 timer_->Stop();
[email protected]8aba0172014-07-03 12:09:53142 if (failure_message_.empty()) {
[email protected]f7022f32014-08-21 16:32:19143 switch (url_request_->status().status()) {
[email protected]96868202014-01-09 10:38:04144 case URLRequestStatus::SUCCESS:
145 case URLRequestStatus::IO_PENDING:
146 break;
147 case URLRequestStatus::CANCELED:
yhirano569e09ce2014-09-11 12:07:29148 if (url_request_->status().error() == ERR_TIMED_OUT)
149 failure_message_ = "WebSocket opening handshake timed out";
150 else
151 failure_message_ = "WebSocket opening handshake was canceled";
[email protected]96868202014-01-09 10:38:04152 break;
153 case URLRequestStatus::FAILED:
[email protected]8aba0172014-07-03 12:09:53154 failure_message_ =
[email protected]96868202014-01-09 10:38:04155 std::string("Error in connection establishment: ") +
[email protected]f7022f32014-08-21 16:32:19156 ErrorToString(url_request_->status().error());
[email protected]96868202014-01-09 10:38:04157 break;
158 }
159 }
[email protected]e69c1cd2014-07-29 07:42:29160 ReportFailureWithMessage(failure_message_);
161 }
162
163 void ReportFailureWithMessage(const std::string& failure_message) {
164 connect_delegate_->OnFailure(failure_message);
165 }
166
167 void OnFinishOpeningHandshake() {
168 WebSocketDispatchOnFinishOpeningHandshake(connect_delegate(),
[email protected]f7022f32014-08-21 16:32:19169 url_request_->url(),
170 url_request_->response_headers(),
171 url_request_->response_time());
[email protected]efa9e732013-11-29 02:55:05172 }
173
[email protected]a62449522014-06-05 11:11:15174 WebSocketStream::ConnectDelegate* connect_delegate() const {
175 return connect_delegate_.get();
176 }
177
yhirano569e09ce2014-09-11 12:07:29178 void OnTimeout() {
179 url_request_->CancelWithError(ERR_TIMED_OUT);
180 }
181
[email protected]efa9e732013-11-29 02:55:05182 private:
183 // |delegate_| needs to be declared before |url_request_| so that it gets
184 // initialised first.
185 scoped_ptr<Delegate> delegate_;
186
187 // Deleting the StreamRequestImpl object deletes this URLRequest object,
188 // cancelling the whole connection.
[email protected]f7022f32014-08-21 16:32:19189 scoped_ptr<URLRequest> url_request_;
[email protected]efa9e732013-11-29 02:55:05190
191 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate_;
192
193 // Owned by the URLRequest.
194 WebSocketHandshakeStreamCreateHelper* create_helper_;
[email protected]8aba0172014-07-03 12:09:53195
196 // The failure message supplied by WebSocketBasicHandshakeStream, if any.
197 std::string failure_message_;
yhirano569e09ce2014-09-11 12:07:29198
199 // A timer for handshake timeout.
200 scoped_ptr<base::Timer> timer_;
[email protected]efa9e732013-11-29 02:55:05201};
202
[email protected]a62449522014-06-05 11:11:15203class SSLErrorCallbacks : public WebSocketEventInterface::SSLErrorCallbacks {
204 public:
205 explicit SSLErrorCallbacks(URLRequest* url_request)
206 : url_request_(url_request) {}
207
dchengb03027d2014-10-21 12:00:20208 void CancelSSLRequest(int error, const SSLInfo* ssl_info) override {
[email protected]a62449522014-06-05 11:11:15209 if (ssl_info) {
210 url_request_->CancelWithSSLError(error, *ssl_info);
211 } else {
212 url_request_->CancelWithError(error);
213 }
214 }
215
dchengb03027d2014-10-21 12:00:20216 void ContinueSSLRequest() override {
[email protected]a62449522014-06-05 11:11:15217 url_request_->ContinueDespiteLastError();
218 }
219
220 private:
221 URLRequest* url_request_;
222};
223
[email protected]efa9e732013-11-29 02:55:05224void Delegate::OnResponseStarted(URLRequest* request) {
[email protected]f7e98ca2014-06-19 12:05:43225 // All error codes, including OK and ABORTED, as with
226 // Net.ErrorCodesForMainFrame3
227 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.WebSocket.ErrorCodes",
228 -request->status().error());
[email protected]a62449522014-06-05 11:11:15229 if (!request->status().is_success()) {
230 DVLOG(3) << "OnResponseStarted (request failed)";
231 owner_->ReportFailure();
232 return;
233 }
[email protected]f7e98ca2014-06-19 12:05:43234 const int response_code = request->GetResponseCode();
235 DVLOG(3) << "OnResponseStarted (response code " << response_code << ")";
236 switch (response_code) {
[email protected]efa9e732013-11-29 02:55:05237 case HTTP_SWITCHING_PROTOCOLS:
[email protected]1e0a16a2014-04-04 16:18:04238 result_ = CONNECTED;
[email protected]efa9e732013-11-29 02:55:05239 owner_->PerformUpgrade();
240 return;
241
242 case HTTP_UNAUTHORIZED:
[email protected]e69c1cd2014-07-29 07:42:29243 result_ = FAILED;
244 owner_->OnFinishOpeningHandshake();
245 owner_->ReportFailureWithMessage(
246 "HTTP Authentication failed; no valid credentials available");
247 return;
248
[email protected]efa9e732013-11-29 02:55:05249 case HTTP_PROXY_AUTHENTICATION_REQUIRED:
[email protected]e69c1cd2014-07-29 07:42:29250 result_ = FAILED;
251 owner_->OnFinishOpeningHandshake();
252 owner_->ReportFailureWithMessage("Proxy authentication failed");
[email protected]efa9e732013-11-29 02:55:05253 return;
254
255 default:
[email protected]1e0a16a2014-04-04 16:18:04256 result_ = FAILED;
[email protected]efa9e732013-11-29 02:55:05257 owner_->ReportFailure();
258 }
259}
260
261void Delegate::OnAuthRequired(URLRequest* request,
262 AuthChallengeInfo* auth_info) {
[email protected]a62449522014-06-05 11:11:15263 // This should only be called if credentials are not already stored.
[email protected]efa9e732013-11-29 02:55:05264 request->CancelAuth();
265}
266
267void Delegate::OnCertificateRequested(URLRequest* request,
268 SSLCertRequestInfo* cert_request_info) {
[email protected]a62449522014-06-05 11:11:15269 // This method is called when a client certificate is requested, and the
270 // request context does not already contain a client certificate selection for
271 // the endpoint. In this case, a main frame resource request would pop-up UI
272 // to permit selection of a client certificate, but since WebSockets are
273 // sub-resources they should not pop-up UI and so there is nothing more we can
274 // do.
275 request->Cancel();
[email protected]efa9e732013-11-29 02:55:05276}
277
278void Delegate::OnSSLCertificateError(URLRequest* request,
279 const SSLInfo& ssl_info,
280 bool fatal) {
[email protected]a62449522014-06-05 11:11:15281 owner_->connect_delegate()->OnSSLCertificateError(
282 scoped_ptr<WebSocketEventInterface::SSLErrorCallbacks>(
283 new SSLErrorCallbacks(request)),
284 ssl_info,
285 fatal);
[email protected]efa9e732013-11-29 02:55:05286}
287
288void Delegate::OnReadCompleted(URLRequest* request, int bytes_read) {
289 NOTREACHED();
290}
291
[email protected]efa9e732013-11-29 02:55:05292} // namespace
[email protected]473282d2013-07-02 11:57:07293
294WebSocketStreamRequest::~WebSocketStreamRequest() {}
295
296WebSocketStream::WebSocketStream() {}
297WebSocketStream::~WebSocketStream() {}
298
299WebSocketStream::ConnectDelegate::~ConnectDelegate() {}
300
[email protected]473282d2013-07-02 11:57:07301scoped_ptr<WebSocketStreamRequest> WebSocketStream::CreateAndConnectStream(
302 const GURL& socket_url,
303 const std::vector<std::string>& requested_subprotocols,
[email protected]7824cf82014-03-13 10:22:57304 const url::Origin& origin,
[email protected]473282d2013-07-02 11:57:07305 URLRequestContext* url_request_context,
306 const BoundNetLog& net_log,
307 scoped_ptr<ConnectDelegate> connect_delegate) {
[email protected]efa9e732013-11-29 02:55:05308 scoped_ptr<WebSocketHandshakeStreamCreateHelper> create_helper(
[email protected]cd48ed12014-01-22 14:34:22309 new WebSocketHandshakeStreamCreateHelper(connect_delegate.get(),
310 requested_subprotocols));
[email protected]490e38f42014-05-26 23:44:16311 scoped_ptr<StreamRequestImpl> request(
312 new StreamRequestImpl(socket_url,
313 url_request_context,
314 origin,
315 connect_delegate.Pass(),
316 create_helper.Pass()));
yhirano569e09ce2014-09-11 12:07:29317 request->Start(scoped_ptr<base::Timer>(new base::Timer(false, false)));
dchenge3d1ddc2014-10-15 19:30:51318 return request.Pass();
[email protected]efa9e732013-11-29 02:55:05319}
320
321// This is declared in websocket_test_util.h.
322scoped_ptr<WebSocketStreamRequest> CreateAndConnectStreamForTesting(
[email protected]7824cf82014-03-13 10:22:57323 const GURL& socket_url,
324 scoped_ptr<WebSocketHandshakeStreamCreateHelper> create_helper,
325 const url::Origin& origin,
326 URLRequestContext* url_request_context,
327 const BoundNetLog& net_log,
yhirano569e09ce2014-09-11 12:07:29328 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate,
329 scoped_ptr<base::Timer> timer) {
[email protected]490e38f42014-05-26 23:44:16330 scoped_ptr<StreamRequestImpl> request(
331 new StreamRequestImpl(socket_url,
332 url_request_context,
333 origin,
334 connect_delegate.Pass(),
335 create_helper.Pass()));
yhirano569e09ce2014-09-11 12:07:29336 request->Start(timer.Pass());
dchenge3d1ddc2014-10-15 19:30:51337 return request.Pass();
[email protected]473282d2013-07-02 11:57:07338}
339
[email protected]e69c1cd2014-07-29 07:42:29340void WebSocketDispatchOnFinishOpeningHandshake(
341 WebSocketStream::ConnectDelegate* connect_delegate,
342 const GURL& url,
343 const scoped_refptr<HttpResponseHeaders>& headers,
344 base::Time response_time) {
345 DCHECK(connect_delegate);
dchengb206dc412014-08-26 19:46:23346 if (headers.get()) {
[email protected]e69c1cd2014-07-29 07:42:29347 connect_delegate->OnFinishOpeningHandshake(make_scoped_ptr(
348 new WebSocketHandshakeResponseInfo(url,
349 headers->response_code(),
350 headers->GetStatusText(),
351 headers,
352 response_time)));
353 }
354}
355
[email protected]473282d2013-07-02 11:57:07356} // namespace net