1 // 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"
8 #include "base/memory/scoped_ptr.h"
9 #include "base/metrics/histogram.h"
10 #include "base/metrics/sparse_histogram.h"
11 #include "base/time/time.h"
12 #include "base/timer/timer.h"
13 #include "net/base/load_flags.h"
14 #include "net/http/http_request_headers.h"
15 #include "net/http/http_response_headers.h"
16 #include "net/http/http_status_code.h"
17 #include "net/url_request/redirect_info.h"
18 #include "net/url_request/url_request.h"
19 #include "net/url_request/url_request_context.h"
20 #include "net/websockets/websocket_errors.h"
21 #include "net/websockets/websocket_event_interface.h"
22 #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"
27 #include "url/origin.h"
28
29 namespace net {
30 namespace {
31
32 // 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.
36 const int kHandshakeTimeoutIntervalInSeconds = 240;
37
38 class StreamRequestImpl;
39
40 class Delegate : public URLRequest::Delegate {
41 public:
42 enum HandshakeResult {
43 INCOMPLETE,
44 CONNECTED,
45 FAILED,
46 NUM_HANDSHAKE_RESULT_TYPES,
47 };
48
Delegate(StreamRequestImpl * owner)49 explicit Delegate(StreamRequestImpl* owner)
50 : owner_(owner), result_(INCOMPLETE) {}
~Delegate()51 virtual ~Delegate() {
52 UMA_HISTOGRAM_ENUMERATION(
53 "Net.WebSocket.HandshakeResult", result_, NUM_HANDSHAKE_RESULT_TYPES);
54 }
55
56 // Implementation of URLRequest::Delegate methods.
OnReceivedRedirect(URLRequest * request,const RedirectInfo & redirect_info,bool * defer_redirect)57 virtual void OnReceivedRedirect(URLRequest* request,
58 const RedirectInfo& redirect_info,
59 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
68 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_;
85 HandshakeResult result_;
86 };
87
88 class StreamRequestImpl : public WebSocketStreamRequest {
89 public:
StreamRequestImpl(const GURL & url,const URLRequestContext * context,const url::Origin & origin,scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate,scoped_ptr<WebSocketHandshakeStreamCreateHelper> create_helper)90 StreamRequestImpl(
91 const GURL& url,
92 const URLRequestContext* context,
93 const url::Origin& origin,
94 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate,
95 scoped_ptr<WebSocketHandshakeStreamCreateHelper> create_helper)
96 : delegate_(new Delegate(this)),
97 url_request_(context->CreateRequest(url, DEFAULT_PRIORITY,
98 delegate_.get(), NULL)),
99 connect_delegate_(connect_delegate.Pass()),
100 create_helper_(create_helper.release()) {
101 create_helper_->set_failure_message(&failure_message_);
102 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);
108 url_request_->SetExtraRequestHeaders(headers);
109
110 // This passes the ownership of |create_helper_| to |url_request_|.
111 url_request_->SetUserData(
112 WebSocketHandshakeStreamBase::CreateHelper::DataKey(),
113 create_helper_);
114 url_request_->SetLoadFlags(LOAD_DISABLE_CACHE |
115 LOAD_BYPASS_CACHE |
116 LOAD_DO_NOT_PROMPT_FOR_LOGIN);
117 }
118
119 // Destroying this object destroys the URLRequest, which cancels the request
120 // and so terminates the handshake if it is incomplete.
~StreamRequestImpl()121 virtual ~StreamRequestImpl() {}
122
Start(scoped_ptr<base::Timer> timer)123 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)));
131 url_request_->Start();
132 }
133
PerformUpgrade()134 void PerformUpgrade() {
135 DCHECK(timer_);
136 timer_->Stop();
137 connect_delegate_->OnSuccess(create_helper_->Upgrade());
138 }
139
ReportFailure()140 void ReportFailure() {
141 DCHECK(timer_);
142 timer_->Stop();
143 if (failure_message_.empty()) {
144 switch (url_request_->status().status()) {
145 case URLRequestStatus::SUCCESS:
146 case URLRequestStatus::IO_PENDING:
147 break;
148 case URLRequestStatus::CANCELED:
149 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";
153 break;
154 case URLRequestStatus::FAILED:
155 failure_message_ =
156 std::string("Error in connection establishment: ") +
157 ErrorToString(url_request_->status().error());
158 break;
159 }
160 }
161 ReportFailureWithMessage(failure_message_);
162 }
163
ReportFailureWithMessage(const std::string & failure_message)164 void ReportFailureWithMessage(const std::string& failure_message) {
165 connect_delegate_->OnFailure(failure_message);
166 }
167
OnFinishOpeningHandshake()168 void OnFinishOpeningHandshake() {
169 WebSocketDispatchOnFinishOpeningHandshake(connect_delegate(),
170 url_request_->url(),
171 url_request_->response_headers(),
172 url_request_->response_time());
173 }
174
connect_delegate() const175 WebSocketStream::ConnectDelegate* connect_delegate() const {
176 return connect_delegate_.get();
177 }
178
OnTimeout()179 void OnTimeout() {
180 url_request_->CancelWithError(ERR_TIMED_OUT);
181 }
182
183 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.
190 scoped_ptr<URLRequest> url_request_;
191
192 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate_;
193
194 // Owned by the URLRequest.
195 WebSocketHandshakeStreamCreateHelper* create_helper_;
196
197 // The failure message supplied by WebSocketBasicHandshakeStream, if any.
198 std::string failure_message_;
199
200 // A timer for handshake timeout.
201 scoped_ptr<base::Timer> timer_;
202 };
203
204 class SSLErrorCallbacks : public WebSocketEventInterface::SSLErrorCallbacks {
205 public:
SSLErrorCallbacks(URLRequest * url_request)206 explicit SSLErrorCallbacks(URLRequest* url_request)
207 : url_request_(url_request) {}
208
CancelSSLRequest(int error,const SSLInfo * ssl_info)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
ContinueSSLRequest()217 virtual void ContinueSSLRequest() OVERRIDE {
218 url_request_->ContinueDespiteLastError();
219 }
220
221 private:
222 URLRequest* url_request_;
223 };
224
OnResponseStarted(URLRequest * request)225 void Delegate::OnResponseStarted(URLRequest* request) {
226 // All error codes, including OK and ABORTED, as with
227 // Net.ErrorCodesForMainFrame3
228 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.WebSocket.ErrorCodes",
229 -request->status().error());
230 if (!request->status().is_success()) {
231 DVLOG(3) << "OnResponseStarted (request failed)";
232 owner_->ReportFailure();
233 return;
234 }
235 const int response_code = request->GetResponseCode();
236 DVLOG(3) << "OnResponseStarted (response code " << response_code << ")";
237 switch (response_code) {
238 case HTTP_SWITCHING_PROTOCOLS:
239 result_ = CONNECTED;
240 owner_->PerformUpgrade();
241 return;
242
243 case HTTP_UNAUTHORIZED:
244 result_ = FAILED;
245 owner_->OnFinishOpeningHandshake();
246 owner_->ReportFailureWithMessage(
247 "HTTP Authentication failed; no valid credentials available");
248 return;
249
250 case HTTP_PROXY_AUTHENTICATION_REQUIRED:
251 result_ = FAILED;
252 owner_->OnFinishOpeningHandshake();
253 owner_->ReportFailureWithMessage("Proxy authentication failed");
254 return;
255
256 default:
257 result_ = FAILED;
258 owner_->ReportFailure();
259 }
260 }
261
OnAuthRequired(URLRequest * request,AuthChallengeInfo * auth_info)262 void Delegate::OnAuthRequired(URLRequest* request,
263 AuthChallengeInfo* auth_info) {
264 // This should only be called if credentials are not already stored.
265 request->CancelAuth();
266 }
267
OnCertificateRequested(URLRequest * request,SSLCertRequestInfo * cert_request_info)268 void Delegate::OnCertificateRequested(URLRequest* request,
269 SSLCertRequestInfo* cert_request_info) {
270 // 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();
277 }
278
OnSSLCertificateError(URLRequest * request,const SSLInfo & ssl_info,bool fatal)279 void Delegate::OnSSLCertificateError(URLRequest* request,
280 const SSLInfo& ssl_info,
281 bool fatal) {
282 owner_->connect_delegate()->OnSSLCertificateError(
283 scoped_ptr<WebSocketEventInterface::SSLErrorCallbacks>(
284 new SSLErrorCallbacks(request)),
285 ssl_info,
286 fatal);
287 }
288
OnReadCompleted(URLRequest * request,int bytes_read)289 void Delegate::OnReadCompleted(URLRequest* request, int bytes_read) {
290 NOTREACHED();
291 }
292
293 } // namespace
294
~WebSocketStreamRequest()295 WebSocketStreamRequest::~WebSocketStreamRequest() {}
296
WebSocketStream()297 WebSocketStream::WebSocketStream() {}
~WebSocketStream()298 WebSocketStream::~WebSocketStream() {}
299
~ConnectDelegate()300 WebSocketStream::ConnectDelegate::~ConnectDelegate() {}
301
CreateAndConnectStream(const GURL & socket_url,const std::vector<std::string> & requested_subprotocols,const url::Origin & origin,URLRequestContext * url_request_context,const BoundNetLog & net_log,scoped_ptr<ConnectDelegate> connect_delegate)302 scoped_ptr<WebSocketStreamRequest> WebSocketStream::CreateAndConnectStream(
303 const GURL& socket_url,
304 const std::vector<std::string>& requested_subprotocols,
305 const url::Origin& origin,
306 URLRequestContext* url_request_context,
307 const BoundNetLog& net_log,
308 scoped_ptr<ConnectDelegate> connect_delegate) {
309 scoped_ptr<WebSocketHandshakeStreamCreateHelper> create_helper(
310 new WebSocketHandshakeStreamCreateHelper(connect_delegate.get(),
311 requested_subprotocols));
312 scoped_ptr<StreamRequestImpl> request(
313 new StreamRequestImpl(socket_url,
314 url_request_context,
315 origin,
316 connect_delegate.Pass(),
317 create_helper.Pass()));
318 request->Start(scoped_ptr<base::Timer>(new base::Timer(false, false)));
319 return request.PassAs<WebSocketStreamRequest>();
320 }
321
322 // This is declared in websocket_test_util.h.
CreateAndConnectStreamForTesting(const GURL & socket_url,scoped_ptr<WebSocketHandshakeStreamCreateHelper> create_helper,const url::Origin & origin,URLRequestContext * url_request_context,const BoundNetLog & net_log,scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate,scoped_ptr<base::Timer> timer)323 scoped_ptr<WebSocketStreamRequest> CreateAndConnectStreamForTesting(
324 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,
329 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate,
330 scoped_ptr<base::Timer> timer) {
331 scoped_ptr<StreamRequestImpl> request(
332 new StreamRequestImpl(socket_url,
333 url_request_context,
334 origin,
335 connect_delegate.Pass(),
336 create_helper.Pass()));
337 request->Start(timer.Pass());
338 return request.PassAs<WebSocketStreamRequest>();
339 }
340
WebSocketDispatchOnFinishOpeningHandshake(WebSocketStream::ConnectDelegate * connect_delegate,const GURL & url,const scoped_refptr<HttpResponseHeaders> & headers,base::Time response_time)341 void 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);
347 if (headers.get()) {
348 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
357 } // namespace net
358