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/p2p/socket_host_tcp.h"
7 #include "base/sys_byteorder.h"
8 #include "content/common/p2p_messages.h"
9 #include "ipc/ipc_sender.h"
10 #include "jingle/glue/fake_ssl_client_socket.h"
11 #include "jingle/glue/proxy_resolving_client_socket.h"
12 #include "net/base/io_buffer.h"
13 #include "net/base/net_errors.h"
14 #include "net/base/net_util.h"
15 #include "net/socket/client_socket_factory.h"
16 #include "net/socket/client_socket_handle.h"
17 #include "net/socket/ssl_client_socket.h"
18 #include "net/socket/tcp_client_socket.h"
19 #include "net/url_request/url_request_context.h"
20 #include "net/url_request/url_request_context_getter.h"
21 #include "third_party/webrtc/base/asyncpacketsocket.h"
25 typedef uint16 PacketLength
;
26 const int kPacketHeaderSize
= sizeof(PacketLength
);
27 const int kReadBufferSize
= 4096;
28 const int kPacketLengthOffset
= 2;
29 const int kTurnChannelDataHeaderSize
= 4;
30 const int kRecvSocketBufferSize
= 128 * 1024;
31 const int kSendSocketBufferSize
= 128 * 1024;
33 bool IsTlsClientSocket(content::P2PSocketType type
) {
34 return (type
== content::P2P_SOCKET_STUN_TLS_CLIENT
||
35 type
== content::P2P_SOCKET_TLS_CLIENT
);
38 bool IsPseudoTlsClientSocket(content::P2PSocketType type
) {
39 return (type
== content::P2P_SOCKET_SSLTCP_CLIENT
||
40 type
== content::P2P_SOCKET_STUN_SSLTCP_CLIENT
);
47 P2PSocketHostTcpBase::P2PSocketHostTcpBase(
48 IPC::Sender
* message_sender
,
51 net::URLRequestContextGetter
* url_context
)
52 : P2PSocketHost(message_sender
, socket_id
, P2PSocketHost::TCP
),
53 write_pending_(false),
56 url_context_(url_context
) {
59 P2PSocketHostTcpBase::~P2PSocketHostTcpBase() {
60 if (state_
== STATE_OPEN
) {
61 DCHECK(socket_
.get());
66 bool P2PSocketHostTcpBase::InitAccepted(const net::IPEndPoint
& remote_address
,
67 net::StreamSocket
* socket
) {
69 DCHECK_EQ(state_
, STATE_UNINITIALIZED
);
71 remote_address_
.ip_address
= remote_address
;
72 // TODO(ronghuawu): Add FakeSSLServerSocket.
73 socket_
.reset(socket
);
76 return state_
!= STATE_ERROR
;
79 bool P2PSocketHostTcpBase::Init(const net::IPEndPoint
& local_address
,
80 const P2PHostAndIPEndPoint
& remote_address
) {
81 DCHECK_EQ(state_
, STATE_UNINITIALIZED
);
83 remote_address_
= remote_address
;
84 state_
= STATE_CONNECTING
;
86 net::HostPortPair dest_host_port_pair
;
87 // If there is no resolved address, let's try with domain name, assuming
88 // socket layer will do the DNS resolve.
89 if (remote_address
.ip_address
.address().empty()) {
90 DCHECK(!remote_address
.hostname
.empty());
91 dest_host_port_pair
= net::HostPortPair(remote_address
.hostname
,
92 remote_address
.ip_address
.port());
94 dest_host_port_pair
= net::HostPortPair::FromIPEndPoint(
95 remote_address
.ip_address
);
98 // TODO(mallinath) - We are ignoring local_address altogether. We should
99 // find a way to inject this into ProxyResolvingClientSocket. This could be
100 // a problem on multi-homed host.
102 // The default SSLConfig is good enough for us for now.
103 const net::SSLConfig ssl_config
;
104 socket_
.reset(new jingle_glue::ProxyResolvingClientSocket(
105 NULL
, // Default socket pool provided by the net::Proxy.
108 dest_host_port_pair
));
110 int status
= socket_
->Connect(
111 base::Bind(&P2PSocketHostTcpBase::OnConnected
,
112 base::Unretained(this)));
113 if (status
!= net::ERR_IO_PENDING
) {
114 // We defer execution of ProcessConnectDone instead of calling it
115 // directly here as the caller may not expect an error/close to
116 // happen here. This is okay, as from the caller's point of view,
117 // the connect always happens asynchronously.
118 base::MessageLoop
* message_loop
= base::MessageLoop::current();
120 message_loop
->PostTask(
122 base::Bind(&P2PSocketHostTcpBase::OnConnected
,
123 base::Unretained(this), status
));
126 return state_
!= STATE_ERROR
;
129 void P2PSocketHostTcpBase::OnError() {
132 if (state_
== STATE_UNINITIALIZED
|| state_
== STATE_CONNECTING
||
133 state_
== STATE_TLS_CONNECTING
|| state_
== STATE_OPEN
) {
134 message_sender_
->Send(new P2PMsg_OnError(id_
));
137 state_
= STATE_ERROR
;
140 void P2PSocketHostTcpBase::OnConnected(int result
) {
141 DCHECK_EQ(state_
, STATE_CONNECTING
);
142 DCHECK_NE(result
, net::ERR_IO_PENDING
);
144 if (result
!= net::OK
) {
145 LOG(WARNING
) << "Error from connecting socket, result=" << result
;
150 if (IsTlsClientSocket(type_
)) {
151 state_
= STATE_TLS_CONNECTING
;
153 } else if (IsPseudoTlsClientSocket(type_
)) {
154 scoped_ptr
<net::StreamSocket
> transport_socket
= socket_
.Pass();
156 new jingle_glue::FakeSSLClientSocket(transport_socket
.Pass()));
157 state_
= STATE_TLS_CONNECTING
;
158 int status
= socket_
->Connect(
159 base::Bind(&P2PSocketHostTcpBase::ProcessTlsSslConnectDone
,
160 base::Unretained(this)));
161 if (status
!= net::ERR_IO_PENDING
) {
162 ProcessTlsSslConnectDone(status
);
165 // If we are not doing TLS, we are ready to send data now.
166 // In case of TLS, SignalConnect will be sent only after TLS handshake is
167 // successfull. So no buffering will be done at socket handlers if any
168 // packets sent before that by the application.
173 void P2PSocketHostTcpBase::StartTls() {
174 DCHECK_EQ(state_
, STATE_TLS_CONNECTING
);
175 DCHECK(socket_
.get());
177 scoped_ptr
<net::ClientSocketHandle
> socket_handle(
178 new net::ClientSocketHandle());
179 socket_handle
->SetSocket(socket_
.Pass());
181 net::SSLClientSocketContext context
;
182 context
.cert_verifier
= url_context_
->GetURLRequestContext()->cert_verifier();
183 context
.transport_security_state
=
184 url_context_
->GetURLRequestContext()->transport_security_state();
185 DCHECK(context
.transport_security_state
);
187 // Default ssl config.
188 const net::SSLConfig ssl_config
;
189 net::HostPortPair dest_host_port_pair
;
191 // Calling net::HostPortPair::FromIPEndPoint will crash if the IP address is
193 if (!remote_address_
.ip_address
.address().empty()) {
194 net::HostPortPair::FromIPEndPoint(remote_address_
.ip_address
);
196 dest_host_port_pair
.set_port(remote_address_
.ip_address
.port());
198 if (!remote_address_
.hostname
.empty())
199 dest_host_port_pair
.set_host(remote_address_
.hostname
);
201 net::ClientSocketFactory
* socket_factory
=
202 net::ClientSocketFactory::GetDefaultFactory();
203 DCHECK(socket_factory
);
205 socket_
= socket_factory
->CreateSSLClientSocket(
206 socket_handle
.Pass(), dest_host_port_pair
, ssl_config
, context
);
207 int status
= socket_
->Connect(
208 base::Bind(&P2PSocketHostTcpBase::ProcessTlsSslConnectDone
,
209 base::Unretained(this)));
211 if (status
!= net::ERR_IO_PENDING
) {
212 ProcessTlsSslConnectDone(status
);
216 void P2PSocketHostTcpBase::ProcessTlsSslConnectDone(int status
) {
217 DCHECK_NE(status
, net::ERR_IO_PENDING
);
218 DCHECK_EQ(state_
, STATE_TLS_CONNECTING
);
219 if (status
!= net::OK
) {
220 LOG(WARNING
) << "Error from connecting TLS socket, status=" << status
;
227 void P2PSocketHostTcpBase::OnOpen() {
229 // Setting socket send and receive buffer size.
230 if (net::OK
!= socket_
->SetReceiveBufferSize(kRecvSocketBufferSize
)) {
231 LOG(WARNING
) << "Failed to set socket receive buffer size to "
232 << kRecvSocketBufferSize
;
235 if (net::OK
!= socket_
->SetSendBufferSize(kSendSocketBufferSize
)) {
236 LOG(WARNING
) << "Failed to set socket send buffer size to "
237 << kSendSocketBufferSize
;
240 if (!DoSendSocketCreateMsg())
243 DCHECK_EQ(state_
, STATE_OPEN
);
247 bool P2PSocketHostTcpBase::DoSendSocketCreateMsg() {
248 DCHECK(socket_
.get());
250 net::IPEndPoint local_address
;
251 int result
= socket_
->GetLocalAddress(&local_address
);
253 LOG(ERROR
) << "P2PSocketHostTcpBase::OnConnected: unable to get local"
254 << " address: " << result
;
259 VLOG(1) << "Local address: " << local_address
.ToString();
261 net::IPEndPoint remote_address
;
263 // GetPeerAddress returns ERR_NAME_NOT_RESOLVED if the socket is connected
265 result
= socket_
->GetPeerAddress(&remote_address
);
266 if (result
< 0 && result
!= net::ERR_NAME_NOT_RESOLVED
) {
267 LOG(ERROR
) << "P2PSocketHostTcpBase::OnConnected: unable to get peer"
268 << " address: " << result
;
273 if (!remote_address
.address().empty()) {
274 VLOG(1) << "Remote address: " << remote_address
.ToString();
275 if (remote_address_
.ip_address
.address().empty()) {
276 // Save |remote_address| if address is empty.
277 remote_address_
.ip_address
= remote_address
;
280 VLOG(1) << "Remote address is unknown since connection is proxied";
283 // If we are not doing TLS, we are ready to send data now.
284 // In case of TLS SignalConnect will be sent only after TLS handshake is
285 // successful. So no buffering will be done at socket handlers if any
286 // packets sent before that by the application.
287 message_sender_
->Send(new P2PMsg_OnSocketCreated(
288 id_
, local_address
, remote_address
));
292 void P2PSocketHostTcpBase::DoRead() {
295 if (!read_buffer_
.get()) {
296 read_buffer_
= new net::GrowableIOBuffer();
297 read_buffer_
->SetCapacity(kReadBufferSize
);
298 } else if (read_buffer_
->RemainingCapacity() < kReadBufferSize
) {
299 // Make sure that we always have at least kReadBufferSize of
300 // remaining capacity in the read buffer. Normally all packets
301 // are smaller than kReadBufferSize, so this is not really
303 read_buffer_
->SetCapacity(read_buffer_
->capacity() + kReadBufferSize
-
304 read_buffer_
->RemainingCapacity());
306 result
= socket_
->Read(
308 read_buffer_
->RemainingCapacity(),
309 base::Bind(&P2PSocketHostTcp::OnRead
, base::Unretained(this)));
310 DidCompleteRead(result
);
311 } while (result
> 0);
314 void P2PSocketHostTcpBase::OnRead(int result
) {
315 DidCompleteRead(result
);
316 if (state_
== STATE_OPEN
) {
321 void P2PSocketHostTcpBase::OnPacket(const std::vector
<char>& data
) {
323 P2PSocketHost::StunMessageType type
;
324 bool stun
= GetStunPacketType(&*data
.begin(), data
.size(), &type
);
325 if (stun
&& IsRequestOrResponse(type
)) {
327 } else if (!stun
|| type
== STUN_DATA_INDICATION
) {
328 LOG(ERROR
) << "Received unexpected data packet from "
329 << remote_address_
.ip_address
.ToString()
330 << " before STUN binding is finished. "
331 << "Terminating connection.";
337 message_sender_
->Send(new P2PMsg_OnDataReceived(
338 id_
, remote_address_
.ip_address
, data
, base::TimeTicks::Now()));
340 if (dump_incoming_rtp_packet_
)
341 DumpRtpPacket(&data
[0], data
.size(), true);
344 // Note: dscp is not actually used on TCP sockets as this point,
345 // but may be honored in the future.
346 void P2PSocketHostTcpBase::Send(const net::IPEndPoint
& to
,
347 const std::vector
<char>& data
,
348 const rtc::PacketOptions
& options
,
351 // The Send message may be sent after the an OnError message was
352 // sent by hasn't been processed the renderer.
356 if (!(to
== remote_address_
.ip_address
)) {
357 // Renderer should use this socket only to send data to |remote_address_|.
364 P2PSocketHost::StunMessageType type
= P2PSocketHost::StunMessageType();
365 bool stun
= GetStunPacketType(&*data
.begin(), data
.size(), &type
);
366 if (!stun
|| type
== STUN_DATA_INDICATION
) {
367 LOG(ERROR
) << "Page tried to send a data packet to " << to
.ToString()
368 << " before STUN binding is finished.";
374 DoSend(to
, data
, options
);
377 void P2PSocketHostTcpBase::WriteOrQueue(
378 scoped_refptr
<net::DrainableIOBuffer
>& buffer
) {
379 IncrementTotalSentPackets();
380 if (write_buffer_
.get()) {
381 write_queue_
.push(buffer
);
382 IncrementDelayedPackets();
383 IncrementDelayedBytes(buffer
->size());
387 write_buffer_
= buffer
;
391 void P2PSocketHostTcpBase::DoWrite() {
392 while (write_buffer_
.get() && state_
== STATE_OPEN
&& !write_pending_
) {
393 int result
= socket_
->Write(
395 write_buffer_
->BytesRemaining(),
396 base::Bind(&P2PSocketHostTcp::OnWritten
, base::Unretained(this)));
397 HandleWriteResult(result
);
401 void P2PSocketHostTcpBase::OnWritten(int result
) {
402 DCHECK(write_pending_
);
403 DCHECK_NE(result
, net::ERR_IO_PENDING
);
405 write_pending_
= false;
406 HandleWriteResult(result
);
410 void P2PSocketHostTcpBase::HandleWriteResult(int result
) {
411 DCHECK(write_buffer_
.get());
413 write_buffer_
->DidConsume(result
);
414 if (write_buffer_
->BytesRemaining() == 0) {
415 message_sender_
->Send(
416 new P2PMsg_OnSendComplete(id_
, P2PSendPacketMetrics()));
417 if (write_queue_
.empty()) {
418 write_buffer_
= NULL
;
420 write_buffer_
= write_queue_
.front();
422 // Update how many bytes are still waiting to be sent.
423 DecrementDelayedBytes(write_buffer_
->size());
426 } else if (result
== net::ERR_IO_PENDING
) {
427 write_pending_
= true;
429 LOG(ERROR
) << "Error when sending data in TCP socket: " << result
;
434 P2PSocketHost
* P2PSocketHostTcpBase::AcceptIncomingTcpConnection(
435 const net::IPEndPoint
& remote_address
, int id
) {
441 void P2PSocketHostTcpBase::DidCompleteRead(int result
) {
442 DCHECK_EQ(state_
, STATE_OPEN
);
444 if (result
== net::ERR_IO_PENDING
) {
446 } else if (result
< 0) {
447 LOG(ERROR
) << "Error when reading from TCP socket: " << result
;
450 } else if (result
== 0) {
451 LOG(WARNING
) << "Remote peer has shutdown TCP socket.";
456 read_buffer_
->set_offset(read_buffer_
->offset() + result
);
457 char* head
= read_buffer_
->StartOfBuffer(); // Purely a convenience.
459 while (pos
<= read_buffer_
->offset() && state_
== STATE_OPEN
) {
460 int consumed
= ProcessInput(head
+ pos
, read_buffer_
->offset() - pos
);
465 // We've consumed all complete packets from the buffer; now move any remaining
466 // bytes to the head of the buffer and set offset to reflect this.
467 if (pos
&& pos
<= read_buffer_
->offset()) {
468 memmove(head
, head
+ pos
, read_buffer_
->offset() - pos
);
469 read_buffer_
->set_offset(read_buffer_
->offset() - pos
);
473 bool P2PSocketHostTcpBase::SetOption(P2PSocketOption option
, int value
) {
474 DCHECK_EQ(STATE_OPEN
, state_
);
476 case P2P_SOCKET_OPT_RCVBUF
:
477 return socket_
->SetReceiveBufferSize(value
) == net::OK
;
478 case P2P_SOCKET_OPT_SNDBUF
:
479 return socket_
->SetSendBufferSize(value
) == net::OK
;
480 case P2P_SOCKET_OPT_DSCP
:
481 return false; // For TCP sockets DSCP setting is not available.
488 P2PSocketHostTcp::P2PSocketHostTcp(IPC::Sender
* message_sender
,
491 net::URLRequestContextGetter
* url_context
)
492 : P2PSocketHostTcpBase(message_sender
, socket_id
, type
, url_context
) {
493 DCHECK(type
== P2P_SOCKET_TCP_CLIENT
||
494 type
== P2P_SOCKET_SSLTCP_CLIENT
||
495 type
== P2P_SOCKET_TLS_CLIENT
);
498 P2PSocketHostTcp::~P2PSocketHostTcp() {
501 int P2PSocketHostTcp::ProcessInput(char* input
, int input_len
) {
502 if (input_len
< kPacketHeaderSize
)
504 int packet_size
= base::NetToHost16(*reinterpret_cast<uint16
*>(input
));
505 if (input_len
< packet_size
+ kPacketHeaderSize
)
508 int consumed
= kPacketHeaderSize
;
509 char* cur
= input
+ consumed
;
510 std::vector
<char> data(cur
, cur
+ packet_size
);
512 consumed
+= packet_size
;
516 void P2PSocketHostTcp::DoSend(const net::IPEndPoint
& to
,
517 const std::vector
<char>& data
,
518 const rtc::PacketOptions
& options
) {
519 int size
= kPacketHeaderSize
+ data
.size();
520 scoped_refptr
<net::DrainableIOBuffer
> buffer
=
521 new net::DrainableIOBuffer(new net::IOBuffer(size
), size
);
522 *reinterpret_cast<uint16
*>(buffer
->data()) = base::HostToNet16(data
.size());
523 memcpy(buffer
->data() + kPacketHeaderSize
, &data
[0], data
.size());
525 packet_processing_helpers::ApplyPacketOptions(
526 buffer
->data() + kPacketHeaderSize
,
527 buffer
->BytesRemaining() - kPacketHeaderSize
,
530 WriteOrQueue(buffer
);
533 // P2PSocketHostStunTcp
534 P2PSocketHostStunTcp::P2PSocketHostStunTcp(
535 IPC::Sender
* message_sender
,
538 net::URLRequestContextGetter
* url_context
)
539 : P2PSocketHostTcpBase(message_sender
, socket_id
, type
, url_context
) {
540 DCHECK(type
== P2P_SOCKET_STUN_TCP_CLIENT
||
541 type
== P2P_SOCKET_STUN_SSLTCP_CLIENT
||
542 type
== P2P_SOCKET_STUN_TLS_CLIENT
);
545 P2PSocketHostStunTcp::~P2PSocketHostStunTcp() {
548 int P2PSocketHostStunTcp::ProcessInput(char* input
, int input_len
) {
549 if (input_len
< kPacketHeaderSize
+ kPacketLengthOffset
)
553 int packet_size
= GetExpectedPacketSize(
554 input
, input_len
, &pad_bytes
);
556 if (input_len
< packet_size
+ pad_bytes
)
559 // We have a complete packet. Read through it.
562 std::vector
<char> data(cur
, cur
+ packet_size
);
564 consumed
+= packet_size
;
565 consumed
+= pad_bytes
;
569 void P2PSocketHostStunTcp::DoSend(const net::IPEndPoint
& to
,
570 const std::vector
<char>& data
,
571 const rtc::PacketOptions
& options
) {
572 // Each packet is expected to have header (STUN/TURN ChannelData), where
573 // header contains message type and and length of message.
574 if (data
.size() < kPacketHeaderSize
+ kPacketLengthOffset
) {
581 size_t expected_len
= GetExpectedPacketSize(
582 &data
[0], data
.size(), &pad_bytes
);
584 // Accepts only complete STUN/TURN packets.
585 if (data
.size() != expected_len
) {
591 // Add any pad bytes to the total size.
592 int size
= data
.size() + pad_bytes
;
594 scoped_refptr
<net::DrainableIOBuffer
> buffer
=
595 new net::DrainableIOBuffer(new net::IOBuffer(size
), size
);
596 memcpy(buffer
->data(), &data
[0], data
.size());
598 packet_processing_helpers::ApplyPacketOptions(
599 buffer
->data(), data
.size(), options
, 0);
602 char padding
[4] = {0};
603 DCHECK_LE(pad_bytes
, 4);
604 memcpy(buffer
->data() + data
.size(), padding
, pad_bytes
);
606 WriteOrQueue(buffer
);
608 if (dump_outgoing_rtp_packet_
)
609 DumpRtpPacket(buffer
->data(), data
.size(), false);
612 int P2PSocketHostStunTcp::GetExpectedPacketSize(
613 const char* data
, int len
, int* pad_bytes
) {
614 DCHECK_LE(kTurnChannelDataHeaderSize
, len
);
615 // Both stun and turn had length at offset 2.
616 int packet_size
= base::NetToHost16(*reinterpret_cast<const uint16
*>(
617 data
+ kPacketLengthOffset
));
619 // Get packet type (STUN or TURN).
620 uint16 msg_type
= base::NetToHost16(*reinterpret_cast<const uint16
*>(data
));
623 // Add heder length to packet length.
624 if ((msg_type
& 0xC000) == 0) {
625 packet_size
+= kStunHeaderSize
;
627 packet_size
+= kTurnChannelDataHeaderSize
;
628 // Calculate any padding if present.
630 *pad_bytes
= 4 - packet_size
% 4;
635 } // namespace content