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(
41 PepperMessageFilter
* manager
,
43 uint32 plugin_dispatcher_id
,
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) {
56 PepperTCPSocket::PepperTCPSocket(
57 PepperMessageFilter
* manager
,
59 uint32 plugin_dispatcher_id
,
61 net::StreamSocket
* socket
,
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),
74 PepperTCPSocket::~PepperTCPSocket() {
75 // Make sure no further callbacks from 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
);
88 connection_state_
= CONNECT_IN_PROGRESS
;
89 net::HostResolver::RequestInfo
request_info(net::HostPortPair(host
, port
));
91 new net::SingleRequestHostResolver(manager_
->GetHostResolver()));
92 int net_result
= resolver_
->Resolve(
94 net::DEFAULT_PRIORITY
,
96 base::Bind(&PepperTCPSocket::OnResolveCompleted
, base::Unretained(this)),
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
);
111 net::IPAddressNumber address
;
113 if (!NetAddressPrivateImpl::NetAddressToIPEndPoint(net_addr
, &address
,
115 SendConnectACKError(PP_ERROR_ADDRESS_INVALID
);
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);
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
);
157 LOG(WARNING
) << "Failed to create an SSL client socket.";
158 OnSSLHandshakeCompleted(net::ERR_UNEXPECTED
);
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
);
177 if (read_buffer_
.get()) {
178 SendReadACKError(PP_ERROR_INPROGRESS
);
182 if (bytes_to_read
<= 0 ||
183 bytes_to_read
> ppapi::TCPSocketShared::kMaxReadSize
) {
184 SendReadACKError(PP_ERROR_BADARGUMENT
);
188 read_buffer_
= new net::IOBuffer(bytes_to_read
);
189 int net_result
= socket_
->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
);
205 if (write_buffer_base_
.get() || write_buffer_
.get()) {
206 SendWriteACKError(PP_ERROR_INPROGRESS
);
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
);
217 write_buffer_base_
= new net::IOBuffer(data_size
);
218 memcpy(write_buffer_base_
->data(), data
.data(), data_size
);
220 new net::DrainableIOBuffer(write_buffer_base_
.get(), data_size
);
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
);
233 net::TCPClientSocket
* tcp_socket
=
234 static_cast<net::TCPClientSocket
*>(socket_
.get());
238 case PP_TCPSOCKET_OPTION_NO_DELAY
: {
239 bool boolean_value
= false;
240 if (!value
.GetBool(&boolean_value
)) {
241 SendSetOptionACK(PP_ERROR_BADARGUMENT
);
246 tcp_socket
->SetNoDelay(boolean_value
) ? PP_OK
: PP_ERROR_FAILED
);
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
);
258 if (name
== PP_TCPSOCKET_OPTION_SEND_BUFFER_SIZE
) {
259 if (integer_value
> ppapi::TCPSocketShared::kMaxSendBufferSize
) {
260 SendSetOptionACK(PP_ERROR_BADARGUMENT
);
263 result
= tcp_socket
->SetSendBufferSize(integer_value
);
265 if (integer_value
> ppapi::TCPSocketShared::kMaxReceiveBufferSize
) {
266 SendSetOptionACK(PP_ERROR_BADARGUMENT
);
269 result
= tcp_socket
->SetReceiveBufferSize(integer_value
);
271 SendSetOptionACK(result
? PP_OK
: PP_ERROR_FAILED
);
276 SendSetOptionACK(PP_ERROR_BADARGUMENT
);
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
));
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()));
342 net::X509Certificate::GetDEREncoded(cert
.os_cert_handle(), &der
);
343 fields
->SetField(PP_X509CERTIFICATE_PRIVATE_RAW
,
344 base::BinaryValue::CreateWithCopiedBuffer(der
.data(), der
.length()));
349 bool PepperTCPSocket::GetCertificateFields(
352 ppapi::PPB_X509Certificate_Fields
* fields
) {
353 scoped_refptr
<net::X509Certificate
> cert
=
354 net::X509Certificate::CreateFromBytes(der
, length
);
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
) {
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
;
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(
384 plugin_dispatcher_id_
,
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
;
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
);
412 if (pp_result
!= PP_OK
)
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
)
421 pp_result
= NetErrorToPepperError(
422 socket_
->GetPeerAddress(&ip_end_point_remote
));
423 if (pp_result
!= PP_OK
)
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(),
434 !NetAddressPrivateImpl::IPEndPointToNetAddress(
435 ip_end_point_remote
.address(),
436 ip_end_point_remote
.port(),
438 pp_result
= PP_ERROR_ADDRESS_INVALID
;
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
;
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()));
473 SendReadACKError(NetErrorToPepperError(net_result
));
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) {
492 if (net_result
>= 0) {
493 manager_
->Send(new PpapiMsg_PPBTCPSocket_WriteACK(
494 routing_id_
, plugin_dispatcher_id_
, socket_id_
,
495 write_buffer_
->BytesConsumed()));
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(
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