Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / content / browser / renderer_host / pepper / pepper_tcp_socket.cc
blob16b19b23bb8dc2baba85b37697ffc8c7dabfc66a
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(PepperMessageFilter* manager,
41 int32 routing_id,
42 uint32 plugin_dispatcher_id,
43 uint32 socket_id,
44 bool private_api)
45 : manager_(manager),
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) {
52 DCHECK(manager);
55 PepperTCPSocket::PepperTCPSocket(PepperMessageFilter* manager,
56 int32 routing_id,
57 uint32 plugin_dispatcher_id,
58 uint32 socket_id,
59 net::StreamSocket* socket,
60 bool private_api)
61 : manager_(manager),
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),
68 socket_(socket) {
69 DCHECK(manager);
72 PepperTCPSocket::~PepperTCPSocket() {
73 // Make sure no further callbacks from socket_.
74 if (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);
83 return;
86 connection_state_ = CONNECT_IN_PROGRESS;
87 net::HostResolver::RequestInfo request_info(net::HostPortPair(host, port));
88 resolver_.reset(
89 new net::SingleRequestHostResolver(manager_->GetHostResolver()));
90 int net_result = resolver_->Resolve(
91 request_info,
92 net::DEFAULT_PRIORITY,
93 &address_list_,
94 base::Bind(&PepperTCPSocket::OnResolveCompleted, base::Unretained(this)),
95 net::BoundNetLog());
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);
106 return;
109 net::IPAddressNumber address;
110 uint16 port;
111 if (!NetAddressPrivateImpl::NetAddressToIPEndPoint(
112 net_addr, &address, &port)) {
113 SendConnectACKError(PP_ERROR_ADDRESS_INVALID);
114 return;
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);
138 return;
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);
154 if (!socket_) {
155 LOG(WARNING) << "Failed to create an SSL client socket.";
156 OnSSLHandshakeCompleted(net::ERR_UNEXPECTED);
157 return;
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);
171 return;
174 if (read_buffer_.get()) {
175 SendReadACKError(PP_ERROR_INPROGRESS);
176 return;
179 if (bytes_to_read <= 0 ||
180 bytes_to_read > ppapi::TCPSocketShared::kMaxReadSize) {
181 SendReadACKError(PP_ERROR_BADARGUMENT);
182 return;
185 read_buffer_ = new net::IOBuffer(bytes_to_read);
186 int net_result = socket_->Read(
187 read_buffer_.get(),
188 bytes_to_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);
199 return;
202 if (write_buffer_base_.get() || write_buffer_.get()) {
203 SendWriteACKError(PP_ERROR_INPROGRESS);
204 return;
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);
211 return;
214 write_buffer_base_ = new net::IOBuffer(data_size);
215 memcpy(write_buffer_base_->data(), data.data(), data_size);
216 write_buffer_ =
217 new net::DrainableIOBuffer(write_buffer_base_.get(), data_size);
218 DoWrite();
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);
227 return;
230 net::TCPClientSocket* tcp_socket =
231 static_cast<net::TCPClientSocket*>(socket_.get());
232 DCHECK(tcp_socket);
234 switch (name) {
235 case PP_TCPSOCKET_OPTION_NO_DELAY: {
236 bool boolean_value = false;
237 if (!value.GetBool(&boolean_value)) {
238 SendSetOptionACK(PP_ERROR_BADARGUMENT);
239 return;
242 SendSetOptionACK(tcp_socket->SetNoDelay(boolean_value) ? PP_OK
243 : PP_ERROR_FAILED);
244 return;
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);
251 return;
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);
258 return;
260 net_result = tcp_socket->SetSendBufferSize(integer_value);
261 } else {
262 if (integer_value > ppapi::TCPSocketShared::kMaxReceiveBufferSize) {
263 SendSetOptionACK(PP_ERROR_BADARGUMENT);
264 return;
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);
270 return;
272 default: {
273 NOTREACHED();
274 SendSetOptionACK(PP_ERROR_BADARGUMENT);
275 return;
280 void PepperTCPSocket::StartConnect(const net::AddressList& addresses) {
281 DCHECK(connection_state_ == CONNECT_IN_PROGRESS);
283 socket_.reset(
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(
293 routing_id_,
294 plugin_dispatcher_id_,
295 socket_id_,
296 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(
315 PP_X509CERTIFICATE_PRIVATE_ISSUER_ORGANIZATION_NAME,
316 new base::StringValue(base::JoinString(issuer.organization_names, "\n")));
317 fields->SetField(
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));
331 fields->SetField(
332 PP_X509CERTIFICATE_PRIVATE_SUBJECT_ORGANIZATION_NAME,
333 new base::StringValue(
334 base::JoinString(subject.organization_names, "\n")));
335 fields->SetField(
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()));
348 std::string der;
349 net::X509Certificate::GetDEREncoded(cert.os_cert_handle(), &der);
350 fields->SetField(
351 PP_X509CERTIFICATE_PRIVATE_RAW,
352 base::BinaryValue::CreateWithCopiedBuffer(der.data(), der.length()));
353 return true;
356 // static
357 bool PepperTCPSocket::GetCertificateFields(
358 const char* der,
359 uint32_t length,
360 ppapi::PPB_X509Certificate_Fields* fields) {
361 scoped_refptr<net::X509Certificate> cert =
362 net::X509Certificate::CreateFromBytes(der, length);
363 if (!cert.get())
364 return false;
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) {
374 DCHECK_GT(0, 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;
381 if (succeeded) {
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);
390 manager_->Send(
391 new PpapiMsg_PPBTCPSocket_SSLHandshakeACK(routing_id_,
392 plugin_dispatcher_id_,
393 socket_id_,
394 succeeded,
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;
409 return;
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);
419 do {
420 if (pp_result != PP_OK)
421 break;
423 net::IPEndPoint ip_end_point_local;
424 net::IPEndPoint ip_end_point_remote;
425 pp_result =
426 NetErrorToPepperError(socket_->GetLocalAddress(&ip_end_point_local));
427 if (pp_result != PP_OK)
428 break;
429 pp_result =
430 NetErrorToPepperError(socket_->GetPeerAddress(&ip_end_point_remote));
431 if (pp_result != PP_OK)
432 break;
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(),
441 &local_addr) ||
442 !NetAddressPrivateImpl::IPEndPointToNetAddress(
443 ip_end_point_remote.address(),
444 ip_end_point_remote.port(),
445 &remote_addr)) {
446 pp_result = PP_ERROR_ADDRESS_INVALID;
447 break;
450 manager_->Send(new PpapiMsg_PPBTCPSocket_ConnectACK(routing_id_,
451 plugin_dispatcher_id_,
452 socket_id_,
453 PP_OK,
454 local_addr,
455 remote_addr));
456 connection_state_ = CONNECTED;
457 return;
458 } while (false);
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(
477 routing_id_,
478 plugin_dispatcher_id_,
479 socket_id_,
480 PP_OK,
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()));
486 } else {
487 SendReadACKError(NetErrorToPepperError(net_result));
489 read_buffer_ = NULL;
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) {
501 DoWrite();
502 return;
506 if (net_result >= 0) {
507 manager_->Send(
508 new PpapiMsg_PPBTCPSocket_WriteACK(routing_id_,
509 plugin_dispatcher_id_,
510 socket_id_,
511 write_buffer_->BytesConsumed()));
512 } else {
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(
536 write_buffer_.get(),
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