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"
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
;
40 PepperTCPSocket::PepperTCPSocket(PepperMessageFilter
* manager
,
42 uint32 plugin_dispatcher_id
,
46 routing_id_(routing_id
),
47 plugin_dispatcher_id_(plugin_dispatcher_id
),
48 socket_id_(socket_id
),
49 private_api_(private_api
),
50 connection_state_(BEFORE_CONNECT
),
51 end_of_file_reached_(false) {
55 PepperTCPSocket::PepperTCPSocket(PepperMessageFilter
* manager
,
57 uint32 plugin_dispatcher_id
,
59 net::StreamSocket
* socket
,
62 routing_id_(routing_id
),
63 plugin_dispatcher_id_(plugin_dispatcher_id
),
64 socket_id_(socket_id
),
65 private_api_(private_api
),
66 connection_state_(CONNECTED
),
67 end_of_file_reached_(false),
72 PepperTCPSocket::~PepperTCPSocket() {
73 // Make sure no further callbacks from socket_.
75 socket_
->Disconnect();
78 void PepperTCPSocket::Connect(const std::string
& host
, uint16_t port
) {
79 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
81 if (connection_state_
!= BEFORE_CONNECT
) {
82 SendConnectACKError(PP_ERROR_FAILED
);
86 connection_state_
= CONNECT_IN_PROGRESS
;
87 net::HostResolver::RequestInfo
request_info(net::HostPortPair(host
, port
));
89 new net::SingleRequestHostResolver(manager_
->GetHostResolver()));
90 int net_result
= resolver_
->Resolve(
92 net::DEFAULT_PRIORITY
,
94 base::Bind(&PepperTCPSocket::OnResolveCompleted
, base::Unretained(this)),
96 if (net_result
!= net::ERR_IO_PENDING
)
97 OnResolveCompleted(net_result
);
100 void PepperTCPSocket::ConnectWithNetAddress(
101 const PP_NetAddress_Private
& net_addr
) {
102 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
104 if (connection_state_
!= BEFORE_CONNECT
) {
105 SendConnectACKError(PP_ERROR_FAILED
);
109 net::IPAddressNumber address
;
111 if (!NetAddressPrivateImpl::NetAddressToIPEndPoint(
112 net_addr
, &address
, &port
)) {
113 SendConnectACKError(PP_ERROR_ADDRESS_INVALID
);
117 // Copy the single IPEndPoint to address_list_.
118 address_list_
.clear();
119 address_list_
.push_back(net::IPEndPoint(address
, port
));
120 connection_state_
= CONNECT_IN_PROGRESS
;
121 StartConnect(address_list_
);
124 void PepperTCPSocket::SSLHandshake(
125 const std::string
& server_name
,
126 uint16_t server_port
,
127 const std::vector
<std::vector
<char> >& trusted_certs
,
128 const std::vector
<std::vector
<char> >& untrusted_certs
) {
129 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
131 // Allow to do SSL handshake only if currently the socket has been connected
132 // and there isn't pending read or write.
133 // IsConnected() includes the state that SSL handshake has been finished and
134 // therefore isn't suitable here.
135 if (connection_state_
!= CONNECTED
|| read_buffer_
.get() ||
136 write_buffer_base_
.get() || write_buffer_
.get()) {
137 SendSSLHandshakeACK(false);
141 connection_state_
= SSL_HANDSHAKE_IN_PROGRESS
;
142 // TODO(raymes,rsleevi): Use trusted/untrusted certificates when connecting.
144 scoped_ptr
<net::ClientSocketHandle
> handle(new net::ClientSocketHandle());
145 handle
->SetSocket(socket_
.Pass());
146 net::ClientSocketFactory
* factory
=
147 net::ClientSocketFactory::GetDefaultFactory();
148 net::HostPortPair
host_port_pair(server_name
, server_port
);
149 net::SSLClientSocketContext ssl_context
;
150 ssl_context
.cert_verifier
= manager_
->GetCertVerifier();
151 ssl_context
.transport_security_state
= manager_
->GetTransportSecurityState();
152 socket_
= factory
->CreateSSLClientSocket(
153 handle
.Pass(), host_port_pair
, manager_
->ssl_config(), ssl_context
);
155 LOG(WARNING
) << "Failed to create an SSL client socket.";
156 OnSSLHandshakeCompleted(net::ERR_UNEXPECTED
);
160 int net_result
= socket_
->Connect(base::Bind(
161 &PepperTCPSocket::OnSSLHandshakeCompleted
, base::Unretained(this)));
162 if (net_result
!= net::ERR_IO_PENDING
)
163 OnSSLHandshakeCompleted(net_result
);
166 void PepperTCPSocket::Read(int32 bytes_to_read
) {
167 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
169 if (!IsConnected() || end_of_file_reached_
) {
170 SendReadACKError(PP_ERROR_FAILED
);
174 if (read_buffer_
.get()) {
175 SendReadACKError(PP_ERROR_INPROGRESS
);
179 if (bytes_to_read
<= 0 ||
180 bytes_to_read
> ppapi::TCPSocketShared::kMaxReadSize
) {
181 SendReadACKError(PP_ERROR_BADARGUMENT
);
185 read_buffer_
= new net::IOBuffer(bytes_to_read
);
186 int net_result
= socket_
->Read(
189 base::Bind(&PepperTCPSocket::OnReadCompleted
, base::Unretained(this)));
190 if (net_result
!= net::ERR_IO_PENDING
)
191 OnReadCompleted(net_result
);
194 void PepperTCPSocket::Write(const std::string
& data
) {
195 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
197 if (!IsConnected()) {
198 SendWriteACKError(PP_ERROR_FAILED
);
202 if (write_buffer_base_
.get() || write_buffer_
.get()) {
203 SendWriteACKError(PP_ERROR_INPROGRESS
);
207 size_t data_size
= data
.size();
208 if (data_size
== 0 ||
209 data_size
> static_cast<size_t>(ppapi::TCPSocketShared::kMaxWriteSize
)) {
210 SendWriteACKError(PP_ERROR_BADARGUMENT
);
214 write_buffer_base_
= new net::IOBuffer(data_size
);
215 memcpy(write_buffer_base_
->data(), data
.data(), data_size
);
217 new net::DrainableIOBuffer(write_buffer_base_
.get(), data_size
);
221 void PepperTCPSocket::SetOption(PP_TCPSocket_Option name
,
222 const ppapi::SocketOptionData
& value
) {
223 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
225 if (!IsConnected() || IsSsl()) {
226 SendSetOptionACK(PP_ERROR_FAILED
);
230 net::TCPClientSocket
* tcp_socket
=
231 static_cast<net::TCPClientSocket
*>(socket_
.get());
235 case PP_TCPSOCKET_OPTION_NO_DELAY
: {
236 bool boolean_value
= false;
237 if (!value
.GetBool(&boolean_value
)) {
238 SendSetOptionACK(PP_ERROR_BADARGUMENT
);
242 SendSetOptionACK(tcp_socket
->SetNoDelay(boolean_value
) ? PP_OK
246 case PP_TCPSOCKET_OPTION_SEND_BUFFER_SIZE
:
247 case PP_TCPSOCKET_OPTION_RECV_BUFFER_SIZE
: {
248 int32_t integer_value
= 0;
249 if (!value
.GetInt32(&integer_value
) || integer_value
<= 0) {
250 SendSetOptionACK(PP_ERROR_BADARGUMENT
);
254 int net_result
= net::OK
;
255 if (name
== PP_TCPSOCKET_OPTION_SEND_BUFFER_SIZE
) {
256 if (integer_value
> ppapi::TCPSocketShared::kMaxSendBufferSize
) {
257 SendSetOptionACK(PP_ERROR_BADARGUMENT
);
260 net_result
= tcp_socket
->SetSendBufferSize(integer_value
);
262 if (integer_value
> ppapi::TCPSocketShared::kMaxReceiveBufferSize
) {
263 SendSetOptionACK(PP_ERROR_BADARGUMENT
);
266 net_result
= tcp_socket
->SetReceiveBufferSize(integer_value
);
268 // TODO(wtc): Add error mapping.
269 SendSetOptionACK((net_result
== net::OK
) ? PP_OK
: PP_ERROR_FAILED
);
274 SendSetOptionACK(PP_ERROR_BADARGUMENT
);
280 void PepperTCPSocket::StartConnect(const net::AddressList
& addresses
) {
281 DCHECK(connection_state_
== CONNECT_IN_PROGRESS
);
284 new net::TCPClientSocket(addresses
, NULL
, net::NetLog::Source()));
285 int net_result
= socket_
->Connect(
286 base::Bind(&PepperTCPSocket::OnConnectCompleted
, base::Unretained(this)));
287 if (net_result
!= net::ERR_IO_PENDING
)
288 OnConnectCompleted(net_result
);
291 void PepperTCPSocket::SendConnectACKError(int32_t error
) {
292 manager_
->Send(new PpapiMsg_PPBTCPSocket_ConnectACK(
294 plugin_dispatcher_id_
,
297 NetAddressPrivateImpl::kInvalidNetAddress
,
298 NetAddressPrivateImpl::kInvalidNetAddress
));
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
));
315 PP_X509CERTIFICATE_PRIVATE_ISSUER_ORGANIZATION_NAME
,
316 new base::StringValue(base::JoinString(issuer
.organization_names
, "\n")));
318 PP_X509CERTIFICATE_PRIVATE_ISSUER_ORGANIZATION_UNIT_NAME
,
319 new base::StringValue(
320 base::JoinString(issuer
.organization_unit_names
, "\n")));
322 const net::CertPrincipal
& subject
= cert
.subject();
323 fields
->SetField(PP_X509CERTIFICATE_PRIVATE_SUBJECT_COMMON_NAME
,
324 new base::StringValue(subject
.common_name
));
325 fields
->SetField(PP_X509CERTIFICATE_PRIVATE_SUBJECT_LOCALITY_NAME
,
326 new base::StringValue(subject
.locality_name
));
327 fields
->SetField(PP_X509CERTIFICATE_PRIVATE_SUBJECT_STATE_OR_PROVINCE_NAME
,
328 new base::StringValue(subject
.state_or_province_name
));
329 fields
->SetField(PP_X509CERTIFICATE_PRIVATE_SUBJECT_COUNTRY_NAME
,
330 new base::StringValue(subject
.country_name
));
332 PP_X509CERTIFICATE_PRIVATE_SUBJECT_ORGANIZATION_NAME
,
333 new base::StringValue(
334 base::JoinString(subject
.organization_names
, "\n")));
336 PP_X509CERTIFICATE_PRIVATE_SUBJECT_ORGANIZATION_UNIT_NAME
,
337 new base::StringValue(
338 base::JoinString(subject
.organization_unit_names
, "\n")));
340 const std::string
& serial_number
= cert
.serial_number();
341 fields
->SetField(PP_X509CERTIFICATE_PRIVATE_SERIAL_NUMBER
,
342 base::BinaryValue::CreateWithCopiedBuffer(
343 serial_number
.data(), serial_number
.length()));
344 fields
->SetField(PP_X509CERTIFICATE_PRIVATE_VALIDITY_NOT_BEFORE
,
345 new base::FundamentalValue(cert
.valid_start().ToDoubleT()));
346 fields
->SetField(PP_X509CERTIFICATE_PRIVATE_VALIDITY_NOT_AFTER
,
347 new base::FundamentalValue(cert
.valid_expiry().ToDoubleT()));
349 net::X509Certificate::GetDEREncoded(cert
.os_cert_handle(), &der
);
351 PP_X509CERTIFICATE_PRIVATE_RAW
,
352 base::BinaryValue::CreateWithCopiedBuffer(der
.data(), der
.length()));
357 bool PepperTCPSocket::GetCertificateFields(
360 ppapi::PPB_X509Certificate_Fields
* fields
) {
361 scoped_refptr
<net::X509Certificate
> cert
=
362 net::X509Certificate::CreateFromBytes(der
, length
);
365 return GetCertificateFields(*cert
.get(), fields
);
368 void PepperTCPSocket::SendReadACKError(int32_t error
) {
369 manager_
->Send(new PpapiMsg_PPBTCPSocket_ReadACK(
370 routing_id_
, plugin_dispatcher_id_
, socket_id_
, error
, std::string()));
373 void PepperTCPSocket::SendWriteACKError(int32_t error
) {
375 manager_
->Send(new PpapiMsg_PPBTCPSocket_WriteACK(
376 routing_id_
, plugin_dispatcher_id_
, socket_id_
, error
));
379 void PepperTCPSocket::SendSSLHandshakeACK(bool succeeded
) {
380 ppapi::PPB_X509Certificate_Fields certificate_fields
;
382 // Our socket is guaranteed to be an SSL socket if we get here.
383 net::SSLClientSocket
* ssl_socket
=
384 static_cast<net::SSLClientSocket
*>(socket_
.get());
385 net::SSLInfo ssl_info
;
386 ssl_socket
->GetSSLInfo(&ssl_info
);
387 if (ssl_info
.cert
.get())
388 GetCertificateFields(*ssl_info
.cert
.get(), &certificate_fields
);
391 new PpapiMsg_PPBTCPSocket_SSLHandshakeACK(routing_id_
,
392 plugin_dispatcher_id_
,
395 certificate_fields
));
398 void PepperTCPSocket::SendSetOptionACK(int32_t result
) {
399 manager_
->Send(new PpapiMsg_PPBTCPSocket_SetOptionACK(
400 routing_id_
, plugin_dispatcher_id_
, socket_id_
, result
));
403 void PepperTCPSocket::OnResolveCompleted(int net_result
) {
404 DCHECK(connection_state_
== CONNECT_IN_PROGRESS
);
406 if (net_result
!= net::OK
) {
407 SendConnectACKError(NetErrorToPepperError(net_result
));
408 connection_state_
= BEFORE_CONNECT
;
412 StartConnect(address_list_
);
415 void PepperTCPSocket::OnConnectCompleted(int net_result
) {
416 DCHECK(connection_state_
== CONNECT_IN_PROGRESS
&& socket_
.get());
418 int32_t pp_result
= NetErrorToPepperError(net_result
);
420 if (pp_result
!= PP_OK
)
423 net::IPEndPoint ip_end_point_local
;
424 net::IPEndPoint ip_end_point_remote
;
426 NetErrorToPepperError(socket_
->GetLocalAddress(&ip_end_point_local
));
427 if (pp_result
!= PP_OK
)
430 NetErrorToPepperError(socket_
->GetPeerAddress(&ip_end_point_remote
));
431 if (pp_result
!= PP_OK
)
434 PP_NetAddress_Private local_addr
=
435 NetAddressPrivateImpl::kInvalidNetAddress
;
436 PP_NetAddress_Private remote_addr
=
437 NetAddressPrivateImpl::kInvalidNetAddress
;
438 if (!NetAddressPrivateImpl::IPEndPointToNetAddress(
439 ip_end_point_local
.address(),
440 ip_end_point_local
.port(),
442 !NetAddressPrivateImpl::IPEndPointToNetAddress(
443 ip_end_point_remote
.address(),
444 ip_end_point_remote
.port(),
446 pp_result
= PP_ERROR_ADDRESS_INVALID
;
450 manager_
->Send(new PpapiMsg_PPBTCPSocket_ConnectACK(routing_id_
,
451 plugin_dispatcher_id_
,
456 connection_state_
= CONNECTED
;
460 SendConnectACKError(pp_result
);
461 connection_state_
= BEFORE_CONNECT
;
464 void PepperTCPSocket::OnSSLHandshakeCompleted(int net_result
) {
465 DCHECK(connection_state_
== SSL_HANDSHAKE_IN_PROGRESS
);
467 bool succeeded
= net_result
== net::OK
;
468 SendSSLHandshakeACK(succeeded
);
469 connection_state_
= succeeded
? SSL_CONNECTED
: SSL_HANDSHAKE_FAILED
;
472 void PepperTCPSocket::OnReadCompleted(int net_result
) {
473 DCHECK(read_buffer_
.get());
475 if (net_result
> 0) {
476 manager_
->Send(new PpapiMsg_PPBTCPSocket_ReadACK(
478 plugin_dispatcher_id_
,
481 std::string(read_buffer_
->data(), net_result
)));
482 } else if (net_result
== 0) {
483 end_of_file_reached_
= true;
484 manager_
->Send(new PpapiMsg_PPBTCPSocket_ReadACK(
485 routing_id_
, plugin_dispatcher_id_
, socket_id_
, PP_OK
, std::string()));
487 SendReadACKError(NetErrorToPepperError(net_result
));
492 void PepperTCPSocket::OnWriteCompleted(int net_result
) {
493 DCHECK(write_buffer_base_
.get());
494 DCHECK(write_buffer_
.get());
496 // Note: For partial writes of 0 bytes, don't continue writing to avoid a
497 // likely infinite loop.
498 if (net_result
> 0) {
499 write_buffer_
->DidConsume(net_result
);
500 if (write_buffer_
->BytesRemaining() > 0) {
506 if (net_result
>= 0) {
508 new PpapiMsg_PPBTCPSocket_WriteACK(routing_id_
,
509 plugin_dispatcher_id_
,
511 write_buffer_
->BytesConsumed()));
513 SendWriteACKError(NetErrorToPepperError(net_result
));
516 write_buffer_
= NULL
;
517 write_buffer_base_
= NULL
;
520 bool PepperTCPSocket::IsConnected() const {
521 return connection_state_
== CONNECTED
|| connection_state_
== SSL_CONNECTED
;
524 bool PepperTCPSocket::IsSsl() const {
525 return connection_state_
== SSL_HANDSHAKE_IN_PROGRESS
||
526 connection_state_
== SSL_CONNECTED
||
527 connection_state_
== SSL_HANDSHAKE_FAILED
;
530 void PepperTCPSocket::DoWrite() {
531 DCHECK(write_buffer_base_
.get());
532 DCHECK(write_buffer_
.get());
533 DCHECK_GT(write_buffer_
->BytesRemaining(), 0);
535 int net_result
= socket_
->Write(
537 write_buffer_
->BytesRemaining(),
538 base::Bind(&PepperTCPSocket::OnWriteCompleted
, base::Unretained(this)));
539 if (net_result
!= net::ERR_IO_PENDING
)
540 OnWriteCompleted(net_result
);
543 } // namespace content