IndexedDBFactory now ForceCloses databases.
[chromium-blink-merge.git] / content / browser / renderer_host / pepper / pepper_tcp_socket.cc
blobc5b752aa7f5f058f247d2a3098aba6a3409a3c3e
1 // Copyright (c) 2012 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.
5 #include "content/browser/renderer_host/pepper/pepper_tcp_socket.h"
7 #include <string.h>
9 #include "base/bind.h"
10 #include "base/bind_helpers.h"
11 #include "base/compiler_specific.h"
12 #include "base/logging.h"
13 #include "base/strings/string_util.h"
14 #include "content/browser/renderer_host/pepper/pepper_message_filter.h"
15 #include "content/public/browser/browser_thread.h"
16 #include "net/base/host_port_pair.h"
17 #include "net/base/io_buffer.h"
18 #include "net/base/ip_endpoint.h"
19 #include "net/base/net_errors.h"
20 #include "net/cert/cert_verifier.h"
21 #include "net/cert/x509_certificate.h"
22 #include "net/dns/host_resolver.h"
23 #include "net/dns/single_request_host_resolver.h"
24 #include "net/socket/client_socket_factory.h"
25 #include "net/socket/client_socket_handle.h"
26 #include "net/socket/ssl_client_socket.h"
27 #include "net/socket/tcp_client_socket.h"
28 #include "ppapi/host/error_conversion.h"
29 #include "ppapi/proxy/ppapi_messages.h"
30 #include "ppapi/shared_impl/private/net_address_private_impl.h"
31 #include "ppapi/shared_impl/private/ppb_x509_certificate_private_shared.h"
32 #include "ppapi/shared_impl/socket_option_data.h"
33 #include "ppapi/shared_impl/tcp_socket_shared.h"
35 using ppapi::host::NetErrorToPepperError;
36 using ppapi::NetAddressPrivateImpl;
38 namespace content {
40 PepperTCPSocket::PepperTCPSocket(
41 PepperMessageFilter* manager,
42 int32 routing_id,
43 uint32 plugin_dispatcher_id,
44 uint32 socket_id,
45 bool private_api)
46 : manager_(manager),
47 routing_id_(routing_id),
48 plugin_dispatcher_id_(plugin_dispatcher_id),
49 socket_id_(socket_id),
50 private_api_(private_api),
51 connection_state_(BEFORE_CONNECT),
52 end_of_file_reached_(false) {
53 DCHECK(manager);
56 PepperTCPSocket::PepperTCPSocket(
57 PepperMessageFilter* manager,
58 int32 routing_id,
59 uint32 plugin_dispatcher_id,
60 uint32 socket_id,
61 net::StreamSocket* socket,
62 bool private_api)
63 : manager_(manager),
64 routing_id_(routing_id),
65 plugin_dispatcher_id_(plugin_dispatcher_id),
66 socket_id_(socket_id),
67 private_api_(private_api),
68 connection_state_(CONNECTED),
69 end_of_file_reached_(false),
70 socket_(socket) {
71 DCHECK(manager);
74 PepperTCPSocket::~PepperTCPSocket() {
75 // Make sure no further callbacks from socket_.
76 if (socket_)
77 socket_->Disconnect();
80 void PepperTCPSocket::Connect(const std::string& host, uint16_t port) {
81 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
83 if (connection_state_ != BEFORE_CONNECT) {
84 SendConnectACKError(PP_ERROR_FAILED);
85 return;
88 connection_state_ = CONNECT_IN_PROGRESS;
89 net::HostResolver::RequestInfo request_info(net::HostPortPair(host, port));
90 resolver_.reset(
91 new net::SingleRequestHostResolver(manager_->GetHostResolver()));
92 int net_result = resolver_->Resolve(
93 request_info,
94 net::DEFAULT_PRIORITY,
95 &address_list_,
96 base::Bind(&PepperTCPSocket::OnResolveCompleted, base::Unretained(this)),
97 net::BoundNetLog());
98 if (net_result != net::ERR_IO_PENDING)
99 OnResolveCompleted(net_result);
102 void PepperTCPSocket::ConnectWithNetAddress(
103 const PP_NetAddress_Private& net_addr) {
104 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
106 if (connection_state_ != BEFORE_CONNECT) {
107 SendConnectACKError(PP_ERROR_FAILED);
108 return;
111 net::IPAddressNumber address;
112 int port;
113 if (!NetAddressPrivateImpl::NetAddressToIPEndPoint(net_addr, &address,
114 &port)) {
115 SendConnectACKError(PP_ERROR_ADDRESS_INVALID);
116 return;
119 // Copy the single IPEndPoint to address_list_.
120 address_list_.clear();
121 address_list_.push_back(net::IPEndPoint(address, port));
122 connection_state_ = CONNECT_IN_PROGRESS;
123 StartConnect(address_list_);
126 void PepperTCPSocket::SSLHandshake(
127 const std::string& server_name,
128 uint16_t server_port,
129 const std::vector<std::vector<char> >& trusted_certs,
130 const std::vector<std::vector<char> >& untrusted_certs) {
131 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
133 // Allow to do SSL handshake only if currently the socket has been connected
134 // and there isn't pending read or write.
135 // IsConnected() includes the state that SSL handshake has been finished and
136 // therefore isn't suitable here.
137 if (connection_state_ != CONNECTED || read_buffer_.get() ||
138 write_buffer_base_.get() || write_buffer_.get()) {
139 SendSSLHandshakeACK(false);
140 return;
143 connection_state_ = SSL_HANDSHAKE_IN_PROGRESS;
144 // TODO(raymes,rsleevi): Use trusted/untrusted certificates when connecting.
146 scoped_ptr<net::ClientSocketHandle> handle(new net::ClientSocketHandle());
147 handle->SetSocket(socket_.Pass());
148 net::ClientSocketFactory* factory =
149 net::ClientSocketFactory::GetDefaultFactory();
150 net::HostPortPair host_port_pair(server_name, server_port);
151 net::SSLClientSocketContext ssl_context;
152 ssl_context.cert_verifier = manager_->GetCertVerifier();
153 ssl_context.transport_security_state = manager_->GetTransportSecurityState();
154 socket_ = factory->CreateSSLClientSocket(
155 handle.Pass(), host_port_pair, manager_->ssl_config(), ssl_context);
156 if (!socket_) {
157 LOG(WARNING) << "Failed to create an SSL client socket.";
158 OnSSLHandshakeCompleted(net::ERR_UNEXPECTED);
159 return;
162 int net_result = socket_->Connect(
163 base::Bind(&PepperTCPSocket::OnSSLHandshakeCompleted,
164 base::Unretained(this)));
165 if (net_result != net::ERR_IO_PENDING)
166 OnSSLHandshakeCompleted(net_result);
169 void PepperTCPSocket::Read(int32 bytes_to_read) {
170 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
172 if (!IsConnected() || end_of_file_reached_) {
173 SendReadACKError(PP_ERROR_FAILED);
174 return;
177 if (read_buffer_.get()) {
178 SendReadACKError(PP_ERROR_INPROGRESS);
179 return;
182 if (bytes_to_read <= 0 ||
183 bytes_to_read > ppapi::TCPSocketShared::kMaxReadSize) {
184 SendReadACKError(PP_ERROR_BADARGUMENT);
185 return;
188 read_buffer_ = new net::IOBuffer(bytes_to_read);
189 int net_result = socket_->Read(
190 read_buffer_.get(),
191 bytes_to_read,
192 base::Bind(&PepperTCPSocket::OnReadCompleted, base::Unretained(this)));
193 if (net_result != net::ERR_IO_PENDING)
194 OnReadCompleted(net_result);
197 void PepperTCPSocket::Write(const std::string& data) {
198 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
200 if (!IsConnected()) {
201 SendWriteACKError(PP_ERROR_FAILED);
202 return;
205 if (write_buffer_base_.get() || write_buffer_.get()) {
206 SendWriteACKError(PP_ERROR_INPROGRESS);
207 return;
210 size_t data_size = data.size();
211 if (data_size == 0 ||
212 data_size > static_cast<size_t>(ppapi::TCPSocketShared::kMaxWriteSize)) {
213 SendWriteACKError(PP_ERROR_BADARGUMENT);
214 return;
217 write_buffer_base_ = new net::IOBuffer(data_size);
218 memcpy(write_buffer_base_->data(), data.data(), data_size);
219 write_buffer_ =
220 new net::DrainableIOBuffer(write_buffer_base_.get(), data_size);
221 DoWrite();
224 void PepperTCPSocket::SetOption(PP_TCPSocket_Option name,
225 const ppapi::SocketOptionData& value) {
226 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
228 if (!IsConnected() || IsSsl()) {
229 SendSetOptionACK(PP_ERROR_FAILED);
230 return;
233 net::TCPClientSocket* tcp_socket =
234 static_cast<net::TCPClientSocket*>(socket_.get());
235 DCHECK(tcp_socket);
237 switch (name) {
238 case PP_TCPSOCKET_OPTION_NO_DELAY: {
239 bool boolean_value = false;
240 if (!value.GetBool(&boolean_value)) {
241 SendSetOptionACK(PP_ERROR_BADARGUMENT);
242 return;
245 SendSetOptionACK(
246 tcp_socket->SetNoDelay(boolean_value) ? PP_OK : PP_ERROR_FAILED);
247 return;
249 case PP_TCPSOCKET_OPTION_SEND_BUFFER_SIZE:
250 case PP_TCPSOCKET_OPTION_RECV_BUFFER_SIZE: {
251 int32_t integer_value = 0;
252 if (!value.GetInt32(&integer_value) || integer_value <= 0) {
253 SendSetOptionACK(PP_ERROR_BADARGUMENT);
254 return;
257 bool result = false;
258 if (name == PP_TCPSOCKET_OPTION_SEND_BUFFER_SIZE) {
259 if (integer_value > ppapi::TCPSocketShared::kMaxSendBufferSize) {
260 SendSetOptionACK(PP_ERROR_BADARGUMENT);
261 return;
263 result = tcp_socket->SetSendBufferSize(integer_value);
264 } else {
265 if (integer_value > ppapi::TCPSocketShared::kMaxReceiveBufferSize) {
266 SendSetOptionACK(PP_ERROR_BADARGUMENT);
267 return;
269 result = tcp_socket->SetReceiveBufferSize(integer_value);
271 SendSetOptionACK(result ? PP_OK : PP_ERROR_FAILED);
272 return;
274 default: {
275 NOTREACHED();
276 SendSetOptionACK(PP_ERROR_BADARGUMENT);
277 return;
282 void PepperTCPSocket::StartConnect(const net::AddressList& addresses) {
283 DCHECK(connection_state_ == CONNECT_IN_PROGRESS);
285 socket_.reset(new net::TCPClientSocket(addresses, NULL,
286 net::NetLog::Source()));
287 int net_result = socket_->Connect(
288 base::Bind(&PepperTCPSocket::OnConnectCompleted,
289 base::Unretained(this)));
290 if (net_result != net::ERR_IO_PENDING)
291 OnConnectCompleted(net_result);
294 void PepperTCPSocket::SendConnectACKError(int32_t error) {
295 manager_->Send(new PpapiMsg_PPBTCPSocket_ConnectACK(
296 routing_id_, plugin_dispatcher_id_, socket_id_, error,
297 NetAddressPrivateImpl::kInvalidNetAddress,
298 NetAddressPrivateImpl::kInvalidNetAddress));
301 // static
302 bool PepperTCPSocket::GetCertificateFields(
303 const net::X509Certificate& cert,
304 ppapi::PPB_X509Certificate_Fields* fields) {
305 const net::CertPrincipal& issuer = cert.issuer();
306 fields->SetField(PP_X509CERTIFICATE_PRIVATE_ISSUER_COMMON_NAME,
307 new base::StringValue(issuer.common_name));
308 fields->SetField(PP_X509CERTIFICATE_PRIVATE_ISSUER_LOCALITY_NAME,
309 new base::StringValue(issuer.locality_name));
310 fields->SetField(PP_X509CERTIFICATE_PRIVATE_ISSUER_STATE_OR_PROVINCE_NAME,
311 new base::StringValue(issuer.state_or_province_name));
312 fields->SetField(PP_X509CERTIFICATE_PRIVATE_ISSUER_COUNTRY_NAME,
313 new base::StringValue(issuer.country_name));
314 fields->SetField(PP_X509CERTIFICATE_PRIVATE_ISSUER_ORGANIZATION_NAME,
315 new base::StringValue(JoinString(issuer.organization_names, '\n')));
316 fields->SetField(PP_X509CERTIFICATE_PRIVATE_ISSUER_ORGANIZATION_UNIT_NAME,
317 new base::StringValue(JoinString(issuer.organization_unit_names, '\n')));
319 const net::CertPrincipal& subject = cert.subject();
320 fields->SetField(PP_X509CERTIFICATE_PRIVATE_SUBJECT_COMMON_NAME,
321 new base::StringValue(subject.common_name));
322 fields->SetField(PP_X509CERTIFICATE_PRIVATE_SUBJECT_LOCALITY_NAME,
323 new base::StringValue(subject.locality_name));
324 fields->SetField(PP_X509CERTIFICATE_PRIVATE_SUBJECT_STATE_OR_PROVINCE_NAME,
325 new base::StringValue(subject.state_or_province_name));
326 fields->SetField(PP_X509CERTIFICATE_PRIVATE_SUBJECT_COUNTRY_NAME,
327 new base::StringValue(subject.country_name));
328 fields->SetField(PP_X509CERTIFICATE_PRIVATE_SUBJECT_ORGANIZATION_NAME,
329 new base::StringValue(JoinString(subject.organization_names, '\n')));
330 fields->SetField(PP_X509CERTIFICATE_PRIVATE_SUBJECT_ORGANIZATION_UNIT_NAME,
331 new base::StringValue(JoinString(subject.organization_unit_names, '\n')));
333 const std::string& serial_number = cert.serial_number();
334 fields->SetField(PP_X509CERTIFICATE_PRIVATE_SERIAL_NUMBER,
335 base::BinaryValue::CreateWithCopiedBuffer(serial_number.data(),
336 serial_number.length()));
337 fields->SetField(PP_X509CERTIFICATE_PRIVATE_VALIDITY_NOT_BEFORE,
338 new base::FundamentalValue(cert.valid_start().ToDoubleT()));
339 fields->SetField(PP_X509CERTIFICATE_PRIVATE_VALIDITY_NOT_AFTER,
340 new base::FundamentalValue(cert.valid_expiry().ToDoubleT()));
341 std::string der;
342 net::X509Certificate::GetDEREncoded(cert.os_cert_handle(), &der);
343 fields->SetField(PP_X509CERTIFICATE_PRIVATE_RAW,
344 base::BinaryValue::CreateWithCopiedBuffer(der.data(), der.length()));
345 return true;
348 // static
349 bool PepperTCPSocket::GetCertificateFields(
350 const char* der,
351 uint32_t length,
352 ppapi::PPB_X509Certificate_Fields* fields) {
353 scoped_refptr<net::X509Certificate> cert =
354 net::X509Certificate::CreateFromBytes(der, length);
355 if (!cert.get())
356 return false;
357 return GetCertificateFields(*cert.get(), fields);
360 void PepperTCPSocket::SendReadACKError(int32_t error) {
361 manager_->Send(new PpapiMsg_PPBTCPSocket_ReadACK(
362 routing_id_, plugin_dispatcher_id_, socket_id_, error, std::string()));
365 void PepperTCPSocket::SendWriteACKError(int32_t error) {
366 DCHECK_GT(0, error);
367 manager_->Send(new PpapiMsg_PPBTCPSocket_WriteACK(
368 routing_id_, plugin_dispatcher_id_, socket_id_, error));
371 void PepperTCPSocket::SendSSLHandshakeACK(bool succeeded) {
372 ppapi::PPB_X509Certificate_Fields certificate_fields;
373 if (succeeded) {
374 // Our socket is guaranteed to be an SSL socket if we get here.
375 net::SSLClientSocket* ssl_socket =
376 static_cast<net::SSLClientSocket*>(socket_.get());
377 net::SSLInfo ssl_info;
378 ssl_socket->GetSSLInfo(&ssl_info);
379 if (ssl_info.cert.get())
380 GetCertificateFields(*ssl_info.cert.get(), &certificate_fields);
382 manager_->Send(new PpapiMsg_PPBTCPSocket_SSLHandshakeACK(
383 routing_id_,
384 plugin_dispatcher_id_,
385 socket_id_,
386 succeeded,
387 certificate_fields));
390 void PepperTCPSocket::SendSetOptionACK(int32_t result) {
391 manager_->Send(new PpapiMsg_PPBTCPSocket_SetOptionACK(
392 routing_id_, plugin_dispatcher_id_, socket_id_, result));
395 void PepperTCPSocket::OnResolveCompleted(int net_result) {
396 DCHECK(connection_state_ == CONNECT_IN_PROGRESS);
398 if (net_result != net::OK) {
399 SendConnectACKError(NetErrorToPepperError(net_result));
400 connection_state_ = BEFORE_CONNECT;
401 return;
404 StartConnect(address_list_);
407 void PepperTCPSocket::OnConnectCompleted(int net_result) {
408 DCHECK(connection_state_ == CONNECT_IN_PROGRESS && socket_.get());
410 int32_t pp_result = NetErrorToPepperError(net_result);
411 do {
412 if (pp_result != PP_OK)
413 break;
415 net::IPEndPoint ip_end_point_local;
416 net::IPEndPoint ip_end_point_remote;
417 pp_result = NetErrorToPepperError(
418 socket_->GetLocalAddress(&ip_end_point_local));
419 if (pp_result != PP_OK)
420 break;
421 pp_result = NetErrorToPepperError(
422 socket_->GetPeerAddress(&ip_end_point_remote));
423 if (pp_result != PP_OK)
424 break;
426 PP_NetAddress_Private local_addr =
427 NetAddressPrivateImpl::kInvalidNetAddress;
428 PP_NetAddress_Private remote_addr =
429 NetAddressPrivateImpl::kInvalidNetAddress;
430 if (!NetAddressPrivateImpl::IPEndPointToNetAddress(
431 ip_end_point_local.address(),
432 ip_end_point_local.port(),
433 &local_addr) ||
434 !NetAddressPrivateImpl::IPEndPointToNetAddress(
435 ip_end_point_remote.address(),
436 ip_end_point_remote.port(),
437 &remote_addr)) {
438 pp_result = PP_ERROR_ADDRESS_INVALID;
439 break;
442 manager_->Send(new PpapiMsg_PPBTCPSocket_ConnectACK(
443 routing_id_, plugin_dispatcher_id_, socket_id_, PP_OK,
444 local_addr, remote_addr));
445 connection_state_ = CONNECTED;
446 return;
447 } while (false);
449 SendConnectACKError(pp_result);
450 connection_state_ = BEFORE_CONNECT;
453 void PepperTCPSocket::OnSSLHandshakeCompleted(int net_result) {
454 DCHECK(connection_state_ == SSL_HANDSHAKE_IN_PROGRESS);
456 bool succeeded = net_result == net::OK;
457 SendSSLHandshakeACK(succeeded);
458 connection_state_ = succeeded ? SSL_CONNECTED : SSL_HANDSHAKE_FAILED;
461 void PepperTCPSocket::OnReadCompleted(int net_result) {
462 DCHECK(read_buffer_.get());
464 if (net_result > 0) {
465 manager_->Send(new PpapiMsg_PPBTCPSocket_ReadACK(
466 routing_id_, plugin_dispatcher_id_, socket_id_, PP_OK,
467 std::string(read_buffer_->data(), net_result)));
468 } else if (net_result == 0) {
469 end_of_file_reached_ = true;
470 manager_->Send(new PpapiMsg_PPBTCPSocket_ReadACK(
471 routing_id_, plugin_dispatcher_id_, socket_id_, PP_OK, std::string()));
472 } else {
473 SendReadACKError(NetErrorToPepperError(net_result));
475 read_buffer_ = NULL;
478 void PepperTCPSocket::OnWriteCompleted(int net_result) {
479 DCHECK(write_buffer_base_.get());
480 DCHECK(write_buffer_.get());
482 // Note: For partial writes of 0 bytes, don't continue writing to avoid a
483 // likely infinite loop.
484 if (net_result > 0) {
485 write_buffer_->DidConsume(net_result);
486 if (write_buffer_->BytesRemaining() > 0) {
487 DoWrite();
488 return;
492 if (net_result >= 0) {
493 manager_->Send(new PpapiMsg_PPBTCPSocket_WriteACK(
494 routing_id_, plugin_dispatcher_id_, socket_id_,
495 write_buffer_->BytesConsumed()));
496 } else {
497 SendWriteACKError(NetErrorToPepperError(net_result));
500 write_buffer_ = NULL;
501 write_buffer_base_ = NULL;
504 bool PepperTCPSocket::IsConnected() const {
505 return connection_state_ == CONNECTED || connection_state_ == SSL_CONNECTED;
508 bool PepperTCPSocket::IsSsl() const {
509 return connection_state_ == SSL_HANDSHAKE_IN_PROGRESS ||
510 connection_state_ == SSL_CONNECTED ||
511 connection_state_ == SSL_HANDSHAKE_FAILED;
514 void PepperTCPSocket::DoWrite() {
515 DCHECK(write_buffer_base_.get());
516 DCHECK(write_buffer_.get());
517 DCHECK_GT(write_buffer_->BytesRemaining(), 0);
519 int net_result = socket_->Write(
520 write_buffer_.get(),
521 write_buffer_->BytesRemaining(),
522 base::Bind(&PepperTCPSocket::OnWriteCompleted, base::Unretained(this)));
523 if (net_result != net::ERR_IO_PENDING)
524 OnWriteCompleted(net_result);
527 } // namespace content