Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(150)

Side by Side Diff: content/browser/websockets/websocket_impl.cc

Issue 2119973002: Port WebSockets to Mojo IPC (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Remove unused code Created 4 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
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 "content/browser/websockets/websocket_impl.h"
6
7 #include <inttypes.h>
8
9 #include <utility>
10
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/location.h"
14 #include "base/logging.h"
15 #include "base/macros.h"
16 #include "base/memory/ptr_util.h"
17 #include "base/single_thread_task_runner.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/threading/thread_task_runner_handle.h"
21 #include "content/browser/bad_message.h"
22 #include "content/browser/child_process_security_policy_impl.h"
23 #include "content/browser/ssl/ssl_error_handler.h"
24 #include "content/browser/ssl/ssl_manager.h"
25 #include "content/public/browser/browser_thread.h"
26 #include "content/public/browser/render_frame_host.h"
27 #include "content/public/browser/storage_partition.h"
28 #include "net/base/net_errors.h"
29 #include "net/http/http_request_headers.h"
30 #include "net/http/http_response_headers.h"
31 #include "net/http/http_util.h"
32 #include "net/ssl/ssl_info.h"
33 #include "net/url_request/url_request_context_getter.h"
34 #include "net/websockets/websocket_channel.h"
35 #include "net/websockets/websocket_errors.h"
36 #include "net/websockets/websocket_event_interface.h"
37 #include "net/websockets/websocket_frame.h" // for WebSocketFrameHeader::OpCode
38 #include "net/websockets/websocket_handshake_request_info.h"
39 #include "net/websockets/websocket_handshake_response_info.h"
40 #include "url/origin.h"
41
42 namespace content {
43 namespace {
44
45 typedef net::WebSocketEventInterface::ChannelState ChannelState;
46
47 // Convert a content::WebSocketMessageType to a
Adam Rice 2016/07/08 04:03:11 s/content/mojom/
48 // net::WebSocketFrameHeader::OpCode
49 net::WebSocketFrameHeader::OpCode MessageTypeToOpCode(
50 mojom::WebSocketMessageType type) {
51 DCHECK(type == mojom::WebSocketMessageType::CONTINUATION ||
52 type == mojom::WebSocketMessageType::TEXT ||
53 type == mojom::WebSocketMessageType::BINARY);
54 typedef net::WebSocketFrameHeader::OpCode OpCode;
55 // These compile asserts verify that the same underlying values are used for
56 // both types, so we can simply cast between them.
57 static_assert(
58 static_cast<OpCode>(mojom::WebSocketMessageType::CONTINUATION) ==
59 net::WebSocketFrameHeader::kOpCodeContinuation,
60 "enum values must match for opcode continuation");
61 static_assert(
62 static_cast<OpCode>(mojom::WebSocketMessageType::TEXT) ==
63 net::WebSocketFrameHeader::kOpCodeText,
64 "enum values must match for opcode text");
65 static_assert(
66 static_cast<OpCode>(mojom::WebSocketMessageType::BINARY) ==
67 net::WebSocketFrameHeader::kOpCodeBinary,
68 "enum values must match for opcode binary");
69 return static_cast<OpCode>(type);
70 }
71
72 mojom::WebSocketMessageType OpCodeToMessageType(
73 net::WebSocketFrameHeader::OpCode opCode) {
74 DCHECK(opCode == net::WebSocketFrameHeader::kOpCodeContinuation ||
75 opCode == net::WebSocketFrameHeader::kOpCodeText ||
76 opCode == net::WebSocketFrameHeader::kOpCodeBinary);
77 // This cast is guaranteed valid by the static_assert() statements above.
78 return static_cast<mojom::WebSocketMessageType>(opCode);
79 }
80
81 } // namespace
82
83 // Implementation of net::WebSocketEventInterface. Receives events from our
84 // WebSocketChannel object. Each event is translated to an IPC and sent to the
85 // renderer or child process via WebSocketDispatcherHost.
86 class WebSocketImpl::WebSocketEventHandler final
87 : public net::WebSocketEventInterface {
88 public:
89 explicit WebSocketEventHandler(WebSocketImpl* impl);
90 ~WebSocketEventHandler() override;
91
92 // net::WebSocketEventInterface implementation
93
94 ChannelState OnAddChannelResponse(const std::string& selected_subprotocol,
95 const std::string& extensions) override;
96 ChannelState OnDataFrame(bool fin,
97 WebSocketMessageType type,
98 const std::vector<char>& data) override;
99 ChannelState OnClosingHandshake() override;
100 ChannelState OnFlowControl(int64_t quota) override;
101 ChannelState OnDropChannel(bool was_clean,
102 uint16_t code,
103 const std::string& reason) override;
104 ChannelState OnFailChannel(const std::string& message) override;
105 ChannelState OnStartOpeningHandshake(
106 std::unique_ptr<net::WebSocketHandshakeRequestInfo> request) override;
107 ChannelState OnFinishOpeningHandshake(
108 std::unique_ptr<net::WebSocketHandshakeResponseInfo> response) override;
109 ChannelState OnSSLCertificateError(
110 std::unique_ptr<net::WebSocketEventInterface::SSLErrorCallbacks>
111 callbacks,
112 const GURL& url,
113 const net::SSLInfo& ssl_info,
114 bool fatal) override;
115
116 private:
117 class SSLErrorHandlerDelegate final : public SSLErrorHandler::Delegate {
118 public:
119 SSLErrorHandlerDelegate(
120 std::unique_ptr<net::WebSocketEventInterface::SSLErrorCallbacks>
121 callbacks);
122 ~SSLErrorHandlerDelegate() override;
123
124 base::WeakPtr<SSLErrorHandler::Delegate> GetWeakPtr();
125
126 // SSLErrorHandler::Delegate methods
127 void CancelSSLRequest(int error, const net::SSLInfo* ssl_info) override;
128 void ContinueSSLRequest() override;
129
130 private:
131 std::unique_ptr<net::WebSocketEventInterface::SSLErrorCallbacks> callbacks_;
132 base::WeakPtrFactory<SSLErrorHandlerDelegate> weak_ptr_factory_;
133
134 DISALLOW_COPY_AND_ASSIGN(SSLErrorHandlerDelegate);
135 };
136
137 WebSocketImpl* const impl_;
138 std::unique_ptr<SSLErrorHandlerDelegate> ssl_error_handler_delegate_;
139
140 DISALLOW_COPY_AND_ASSIGN(WebSocketEventHandler);
141 };
142
143 WebSocketImpl::WebSocketEventHandler::WebSocketEventHandler(WebSocketImpl* impl)
144 : impl_(impl) {
145 DVLOG(1) << "WebSocketEventHandler created @"
146 << reinterpret_cast<void*>(this);
147 }
148
149 WebSocketImpl::WebSocketEventHandler::~WebSocketEventHandler() {
150 DVLOG(1) << "WebSocketEventHandler destroyed @"
151 << reinterpret_cast<void*>(this);
152 }
153
154 ChannelState WebSocketImpl::WebSocketEventHandler::OnAddChannelResponse(
155 const std::string& selected_protocol,
156 const std::string& extensions) {
157 DVLOG(3) << "WebSocketEventHandler::OnAddChannelResponse @"
158 << reinterpret_cast<void*>(this)
159 << " selected_protocol=\"" << selected_protocol << "\""
160 << " extensions=\"" << extensions << "\"";
161
162 impl_->delegate_->OnReceivedResponseFromServer(impl_);
163
164 impl_->client_->OnAddChannelResponse(selected_protocol, extensions);
165
166 return net::WebSocketEventInterface::CHANNEL_ALIVE;
167 }
168
169 ChannelState WebSocketImpl::WebSocketEventHandler::OnDataFrame(
170 bool fin,
171 net::WebSocketFrameHeader::OpCode type,
172 const std::vector<char>& data) {
173 DVLOG(3) << "WebSocketEventHandler::OnDataFrame @"
174 << reinterpret_cast<void*>(this)
175 << " fin=" << fin
176 << " type=" << type << " data is " << data.size() << " bytes";
177
178 // TODO(darin): Avoid this copy.
179 mojo::Array<uint8_t> data_to_pass(data.size());
180 std::copy(data.begin(), data.end(), data_to_pass.begin());
181
182 impl_->client_->OnDataFrame(fin, OpCodeToMessageType(type),
183 std::move(data_to_pass));
184
185 return net::WebSocketEventInterface::CHANNEL_ALIVE;
186 }
187
188 ChannelState WebSocketImpl::WebSocketEventHandler::OnClosingHandshake() {
189 DVLOG(3) << "WebSocketEventHandler::OnClosingHandshake @"
190 << reinterpret_cast<void*>(this);
191
192 impl_->client_->OnClosingHandshake();
193
194 return net::WebSocketEventInterface::CHANNEL_ALIVE;
195 }
196
197 ChannelState WebSocketImpl::WebSocketEventHandler::OnFlowControl(
198 int64_t quota) {
199 DVLOG(3) << "WebSocketEventHandler::OnFlowControl @"
200 << reinterpret_cast<void*>(this)
201 << " quota=" << quota;
202
203 impl_->client_->OnFlowControl(quota);
204
205 return net::WebSocketEventInterface::CHANNEL_ALIVE;
206 }
207
208 ChannelState WebSocketImpl::WebSocketEventHandler::OnDropChannel(
209 bool was_clean,
210 uint16_t code,
211 const std::string& reason) {
212 DVLOG(3) << "WebSocketEventHandler::OnDropChannel @"
213 << reinterpret_cast<void*>(this)
214 << " was_clean=" << was_clean << " code=" << code
215 << " reason=\"" << reason << "\"";
216
217 impl_->client_->OnDropChannel(was_clean, code, reason);
218
219 // net::WebSocketChannel requires that we delete it at this point.
220 impl_->channel_.reset();
221
222 return net::WebSocketEventInterface::CHANNEL_DELETED;
223 }
224
225 ChannelState WebSocketImpl::WebSocketEventHandler::OnFailChannel(
226 const std::string& message) {
227 DVLOG(3) << "WebSocketEventHandler::OnFailChannel @"
228 << reinterpret_cast<void*>(this) << " message=\"" << message << "\"";
229
230 impl_->client_->OnFailChannel(message);
231
232 // net::WebSocketChannel requires that we delete it at this point.
233 impl_->channel_.reset();
234
235 return net::WebSocketEventInterface::CHANNEL_DELETED;
236 }
237
238 ChannelState WebSocketImpl::WebSocketEventHandler::OnStartOpeningHandshake(
239 std::unique_ptr<net::WebSocketHandshakeRequestInfo> request) {
240 bool should_send =
241 ChildProcessSecurityPolicyImpl::GetInstance()->CanReadRawCookies(
242 impl_->delegate_->GetClientProcessId());
243
244 DVLOG(3) << "WebSocketEventHandler::OnStartOpeningHandshake @"
245 << reinterpret_cast<void*>(this) << " should_send=" << should_send;
246
247 if (!should_send)
248 return WebSocketEventInterface::CHANNEL_ALIVE;
249
250 mojom::WebSocketHandshakeRequestPtr request_to_pass(
251 mojom::WebSocketHandshakeRequest::New());
252 request_to_pass->url.Swap(&request->url);
253 net::HttpRequestHeaders::Iterator it(request->headers);
254 while (it.GetNext()) {
255 mojom::HttpHeaderPtr header(mojom::HttpHeader::New());
256 header->name = it.name();
257 header->value = it.value();
258 request_to_pass->headers.push_back(std::move(header));
259 }
260 request_to_pass->headers_text =
261 base::StringPrintf("GET %s HTTP/1.1\r\n",
262 request_to_pass->url.spec().c_str()) +
263 request->headers.ToString();
264
265 impl_->client_->OnStartOpeningHandshake(std::move(request_to_pass));
266
267 return WebSocketEventInterface::CHANNEL_ALIVE;
268 }
269
270 ChannelState WebSocketImpl::WebSocketEventHandler::OnFinishOpeningHandshake(
271 std::unique_ptr<net::WebSocketHandshakeResponseInfo> response) {
272 bool should_send =
273 ChildProcessSecurityPolicyImpl::GetInstance()->CanReadRawCookies(
274 impl_->delegate_->GetClientProcessId());
275
276 DVLOG(3) << "WebSocketEventHandler::OnFinishOpeningHandshake "
277 << reinterpret_cast<void*>(this) << " should_send=" << should_send;
278
279 if (!should_send)
280 return WebSocketEventInterface::CHANNEL_ALIVE;
281
282 mojom::WebSocketHandshakeResponsePtr response_to_pass(
283 mojom::WebSocketHandshakeResponse::New());
284 response_to_pass->url.Swap(&response->url);
285 response_to_pass->status_code = response->status_code;
286 response_to_pass->status_text = response->status_text;
287 size_t iter = 0;
288 std::string name, value;
289 while (response->headers->EnumerateHeaderLines(&iter, &name, &value)) {
290 mojom::HttpHeaderPtr header(mojom::HttpHeader::New());
291 header->name = name;
292 header->value = value;
293 response_to_pass->headers.push_back(std::move(header));
294 }
295 response_to_pass->headers_text =
296 net::HttpUtil::ConvertHeadersBackToHTTPResponse(
297 response->headers->raw_headers());
298
299 impl_->client_->OnFinishOpeningHandshake(std::move(response_to_pass));
300
301 return WebSocketEventInterface::CHANNEL_ALIVE;
302 }
303
304 ChannelState WebSocketImpl::WebSocketEventHandler::OnSSLCertificateError(
305 std::unique_ptr<net::WebSocketEventInterface::SSLErrorCallbacks> callbacks,
306 const GURL& url,
307 const net::SSLInfo& ssl_info,
308 bool fatal) {
309 DVLOG(3) << "WebSocketEventHandler::OnSSLCertificateError"
310 << reinterpret_cast<void*>(this) << " url=" << url.spec()
311 << " cert_status=" << ssl_info.cert_status << " fatal=" << fatal;
312 ssl_error_handler_delegate_.reset(
313 new SSLErrorHandlerDelegate(std::move(callbacks)));
314 SSLManager::OnSSLCertificateSubresourceError(
315 ssl_error_handler_delegate_->GetWeakPtr(),
316 url,
317 impl_->delegate_->GetClientProcessId(),
318 impl_->render_frame_id_,
319 ssl_info,
320 fatal);
321 // The above method is always asynchronous.
322 return WebSocketEventInterface::CHANNEL_ALIVE;
323 }
324
325 WebSocketImpl::WebSocketEventHandler::SSLErrorHandlerDelegate::
326 SSLErrorHandlerDelegate(
327 std::unique_ptr<net::WebSocketEventInterface::SSLErrorCallbacks>
328 callbacks)
329 : callbacks_(std::move(callbacks)), weak_ptr_factory_(this) {}
330
331 WebSocketImpl::WebSocketEventHandler::SSLErrorHandlerDelegate::
332 ~SSLErrorHandlerDelegate() {}
333
334 base::WeakPtr<SSLErrorHandler::Delegate>
335 WebSocketImpl::WebSocketEventHandler::SSLErrorHandlerDelegate::GetWeakPtr() {
336 return weak_ptr_factory_.GetWeakPtr();
337 }
338
339 void WebSocketImpl::WebSocketEventHandler::SSLErrorHandlerDelegate::
340 CancelSSLRequest(int error, const net::SSLInfo* ssl_info) {
341 DVLOG(3) << "SSLErrorHandlerDelegate::CancelSSLRequest"
342 << " error=" << error
343 << " cert_status=" << (ssl_info ? ssl_info->cert_status
344 : static_cast<net::CertStatus>(-1));
345 callbacks_->CancelSSLRequest(error, ssl_info);
346 }
347
348 void WebSocketImpl::WebSocketEventHandler::SSLErrorHandlerDelegate::
349 ContinueSSLRequest() {
350 DVLOG(3) << "SSLErrorHandlerDelegate::ContinueSSLRequest";
351 callbacks_->ContinueSSLRequest();
352 }
353
354 WebSocketImpl::WebSocketImpl(
355 Delegate* delegate,
356 mojom::WebSocketRequest request,
357 int render_frame_id,
358 base::TimeDelta delay)
359 : delegate_(delegate),
360 binding_(this, std::move(request)),
361 render_frame_id_(render_frame_id),
362 delay_(delay),
363 pending_flow_control_quota_(0),
364 handshake_succeeded_(false),
365 weak_ptr_factory_(this) {
366 binding_.set_connection_error_handler(
367 base::Bind(&WebSocketImpl::OnConnectionError, base::Unretained(this)));
368 }
369
370 WebSocketImpl::~WebSocketImpl() {}
371
372 void WebSocketImpl::GoAway() {
373 StartClosingHandshake(static_cast<uint16_t>(net::kWebSocketErrorGoingAway),
374 "");
375 }
376
377 void WebSocketImpl::Initialize(mojom::WebSocketClientPtr client) {
378 client_ = std::move(client);
379 }
380
381 void WebSocketImpl::AddChannelRequest(
382 const GURL& socket_url,
383 mojo::Array<mojo::String> requested_protocols_mojo,
384 const url::Origin& origin,
385 const mojo::String& user_agent_override) {
386 // Convert to STL types.
387 std::vector<std::string> requested_protocols(
388 requested_protocols_mojo.begin(),
389 requested_protocols_mojo.end());
390
391 DVLOG(3) << "WebSocketImpl::AddChannelRequest @"
392 << reinterpret_cast<void*>(this)
393 << " socket_url=\"" << socket_url << "\" requested_protocols=\""
394 << base::JoinString(requested_protocols, ", ") << "\" origin=\""
395 << origin << "\" user_agent_override=\"" << user_agent_override
396 << "\"";
397
398 DCHECK(!channel_);
399 if (delay_ > base::TimeDelta()) {
400 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
401 FROM_HERE,
402 base::Bind(&WebSocketImpl::AddChannel,
403 weak_ptr_factory_.GetWeakPtr(),
404 socket_url,
405 requested_protocols,
406 origin,
407 user_agent_override),
408 delay_);
409 } else {
410 AddChannel(socket_url, requested_protocols, origin, user_agent_override);
411 }
412 // |this| may have been deleted here.
413 }
414
415 void WebSocketImpl::SendFrame(bool fin, mojom::WebSocketMessageType type,
416 mojo::Array<uint8_t> data) {
417 DVLOG(3) << "WebSocketImpl::OnSendFrame @"
418 << reinterpret_cast<void*>(this) << " fin=" << fin
419 << " type=" << type << " data is " << data.size() << " bytes";
420
421 DCHECK(channel_);
422
423 // TODO(darin): Avoid this copy.
424 std::vector<char> data_to_pass(data.size());
425 std::copy(data.begin(), data.end(), data_to_pass.begin());
426
427 channel_->SendFrame(fin, MessageTypeToOpCode(type), data_to_pass);
428 }
429
430 void WebSocketImpl::SendFlowControl(int64_t quota) {
431 DVLOG(3) << "WebSocketImpl::OnFlowControl @"
432 << reinterpret_cast<void*>(this) << " quota=" << quota;
433
434 if (!channel_) {
435 // WebSocketChannel is not yet created due to the delay introduced by
436 // per-renderer WebSocket throttling.
437 // SendFlowControl() is called after WebSocketChannel is created.
438 pending_flow_control_quota_ += quota;
439 return;
440 }
441
442 ignore_result(channel_->SendFlowControl(quota));
443 }
444
445 void WebSocketImpl::StartClosingHandshake(uint16_t code,
446 const mojo::String& reason) {
447 DVLOG(3) << "WebSocketImpl::StartClosingHandshake @"
448 << reinterpret_cast<void*>(this)
449 << " code=" << code << " reason=\"" << reason << "\"";
450
451 if (!channel_) {
452 // WebSocketChannel is not yet created due to the delay introduced by
453 // per-renderer WebSocket throttling.
454 #if 0
455 WebSocketDispatcherHost::WebSocketHostState result =
456 dispatcher_->DoDropChannel(routing_id_, false,
457 net::kWebSocketErrorAbnormalClosure, "");
458 DCHECK_EQ(WebSocketDispatcherHost::WEBSOCKET_HOST_DELETED, result);
459 #endif
460 client_->OnDropChannel(false, net::kWebSocketErrorAbnormalClosure, "");
461
462 // XXX need to break connection
463 // XXX -- No, we will observe the client dropping the connection
464
465 return;
466 }
467
468 // TODO(yhirano): Handle |was_clean| appropriately.
469 ignore_result(channel_->StartClosingHandshake(code, reason));
470 }
471
472 void WebSocketImpl::OnConnectionError() {
473 delegate_->OnLostConnectionToClient(this);
474 }
475
476 void WebSocketImpl::AddChannel(
477 const GURL& socket_url,
478 const std::vector<std::string>& requested_protocols,
479 const url::Origin& origin,
480 const std::string& user_agent_override) {
481 DVLOG(3) << "WebSocketImpl::AddChannel @"
482 << reinterpret_cast<void*>(this)
483 << " socket_url=\"" << socket_url
484 << "\" requested_protocols=\""
485 << base::JoinString(requested_protocols, ", ") << "\" origin=\""
486 << origin << "\" user_agent_override=\""
487 << user_agent_override << "\"";
488
489 DCHECK(!channel_);
490
491 StoragePartition* partition = delegate_->GetStoragePartition();
492
493 std::unique_ptr<net::WebSocketEventInterface> event_interface(
494 new WebSocketEventHandler(this));
495 channel_.reset(
496 new net::WebSocketChannel(
497 std::move(event_interface),
498 partition->GetURLRequestContext()->GetURLRequestContext()));
499
500 if (pending_flow_control_quota_ > 0) {
501 // channel_->SendFlowControl(pending_flow_control_quota_) must be called
502 // after channel_->SendAddChannelRequest() below.
503 // We post SendFlowControl() here using |weak_ptr_factory_| instead of
504 // calling SendFlowControl directly, because |this| may have been deleted
505 // after channel_->SendAddChannelRequest().
506 // XXX we should be able to call this after SendAddChannelRequest now
507 // as connection errors are observed asynchronously.
508 base::ThreadTaskRunnerHandle::Get()->PostTask(
509 FROM_HERE, base::Bind(&WebSocketImpl::SendFlowControl,
510 weak_ptr_factory_.GetWeakPtr(),
511 pending_flow_control_quota_));
512 pending_flow_control_quota_ = 0;
513 }
514
515 std::string additional_headers;
516 if (!user_agent_override.empty()) {
517 if (!net::HttpUtil::IsValidHeaderValue(user_agent_override)) {
518 bad_message::ReceivedBadMessage(
519 delegate_->GetClientProcessId(),
520 bad_message::WSI_INVALID_HEADER_VALUE);
521 return;
522 }
523 additional_headers = base::StringPrintf("%s:%s",
524 net::HttpRequestHeaders::kUserAgent,
525 user_agent_override.c_str());
526 }
527 channel_->SendAddChannelRequest(socket_url, requested_protocols, origin,
528 additional_headers);
529 }
530
531 } // namespace content
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698