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/location.h"
8 #include "base/single_thread_task_runner.h"
9 #include "base/sys_byteorder.h"
10 #include "content/common/p2p_messages.h"
11 #include "ipc/ipc_sender.h"
12 #include "jingle/glue/fake_ssl_client_socket.h"
13 #include "jingle/glue/proxy_resolving_client_socket.h"
14 #include "net/base/io_buffer.h"
15 #include "net/base/net_errors.h"
16 #include "net/base/net_util.h"
17 #include "net/socket/client_socket_factory.h"
18 #include "net/socket/client_socket_handle.h"
19 #include "net/socket/ssl_client_socket.h"
20 #include "net/socket/tcp_client_socket.h"
21 #include "net/url_request/url_request_context.h"
22 #include "net/url_request/url_request_context_getter.h"
23 #include "third_party/webrtc/base/asyncpacketsocket.h"
27 typedef uint16 PacketLength
;
28 const int kPacketHeaderSize
= sizeof(PacketLength
);
29 const int kReadBufferSize
= 4096;
30 const int kPacketLengthOffset
= 2;
31 const int kTurnChannelDataHeaderSize
= 4;
32 const int kRecvSocketBufferSize
= 128 * 1024;
33 const int kSendSocketBufferSize
= 128 * 1024;
35 bool IsTlsClientSocket(content::P2PSocketType type
) {
36 return (type
== content::P2P_SOCKET_STUN_TLS_CLIENT
||
37 type
== content::P2P_SOCKET_TLS_CLIENT
);
40 bool IsPseudoTlsClientSocket(content::P2PSocketType type
) {
41 return (type
== content::P2P_SOCKET_SSLTCP_CLIENT
||
42 type
== content::P2P_SOCKET_STUN_SSLTCP_CLIENT
);
49 P2PSocketHostTcpBase::P2PSocketHostTcpBase(
50 IPC::Sender
* message_sender
,
53 net::URLRequestContextGetter
* url_context
)
54 : P2PSocketHost(message_sender
, socket_id
, P2PSocketHost::TCP
),
55 write_pending_(false),
58 url_context_(url_context
) {
61 P2PSocketHostTcpBase::~P2PSocketHostTcpBase() {
62 if (state_
== STATE_OPEN
) {
63 DCHECK(socket_
.get());
68 bool P2PSocketHostTcpBase::InitAccepted(const net::IPEndPoint
& remote_address
,
69 net::StreamSocket
* socket
) {
71 DCHECK_EQ(state_
, STATE_UNINITIALIZED
);
73 remote_address_
.ip_address
= remote_address
;
74 // TODO(ronghuawu): Add FakeSSLServerSocket.
75 socket_
.reset(socket
);
78 return state_
!= STATE_ERROR
;
81 bool P2PSocketHostTcpBase::Init(const net::IPEndPoint
& local_address
,
82 const P2PHostAndIPEndPoint
& remote_address
) {
83 DCHECK_EQ(state_
, STATE_UNINITIALIZED
);
85 remote_address_
= remote_address
;
86 state_
= STATE_CONNECTING
;
88 net::HostPortPair dest_host_port_pair
;
89 // If there is no resolved address, let's try with domain name, assuming
90 // socket layer will do the DNS resolve.
91 if (remote_address
.ip_address
.address().empty()) {
92 DCHECK(!remote_address
.hostname
.empty());
93 dest_host_port_pair
= net::HostPortPair(remote_address
.hostname
,
94 remote_address
.ip_address
.port());
96 dest_host_port_pair
= net::HostPortPair::FromIPEndPoint(
97 remote_address
.ip_address
);
100 // TODO(mallinath) - We are ignoring local_address altogether. We should
101 // find a way to inject this into ProxyResolvingClientSocket. This could be
102 // a problem on multi-homed host.
104 // The default SSLConfig is good enough for us for now.
105 const net::SSLConfig ssl_config
;
106 socket_
.reset(new jingle_glue::ProxyResolvingClientSocket(
107 NULL
, // Default socket pool provided by the net::Proxy.
110 dest_host_port_pair
));
112 int status
= socket_
->Connect(
113 base::Bind(&P2PSocketHostTcpBase::OnConnected
,
114 base::Unretained(this)));
115 if (status
!= net::ERR_IO_PENDING
) {
116 // We defer execution of ProcessConnectDone instead of calling it
117 // directly here as the caller may not expect an error/close to
118 // happen here. This is okay, as from the caller's point of view,
119 // the connect always happens asynchronously.
120 base::MessageLoop
* message_loop
= base::MessageLoop::current();
122 message_loop
->task_runner()->PostTask(
123 FROM_HERE
, base::Bind(&P2PSocketHostTcpBase::OnConnected
,
124 base::Unretained(this), status
));
127 return state_
!= STATE_ERROR
;
130 void P2PSocketHostTcpBase::OnError() {
133 if (state_
== STATE_UNINITIALIZED
|| state_
== STATE_CONNECTING
||
134 state_
== STATE_TLS_CONNECTING
|| state_
== STATE_OPEN
) {
135 message_sender_
->Send(new P2PMsg_OnError(id_
));
138 state_
= STATE_ERROR
;
141 void P2PSocketHostTcpBase::OnConnected(int result
) {
142 DCHECK_EQ(state_
, STATE_CONNECTING
);
143 DCHECK_NE(result
, net::ERR_IO_PENDING
);
145 if (result
!= net::OK
) {
146 LOG(WARNING
) << "Error from connecting socket, result=" << result
;
151 if (IsTlsClientSocket(type_
)) {
152 state_
= STATE_TLS_CONNECTING
;
154 } else if (IsPseudoTlsClientSocket(type_
)) {
155 scoped_ptr
<net::StreamSocket
> transport_socket
= socket_
.Pass();
157 new jingle_glue::FakeSSLClientSocket(transport_socket
.Pass()));
158 state_
= STATE_TLS_CONNECTING
;
159 int status
= socket_
->Connect(
160 base::Bind(&P2PSocketHostTcpBase::ProcessTlsSslConnectDone
,
161 base::Unretained(this)));
162 if (status
!= net::ERR_IO_PENDING
) {
163 ProcessTlsSslConnectDone(status
);
166 // If we are not doing TLS, we are ready to send data now.
167 // In case of TLS, SignalConnect will be sent only after TLS handshake is
168 // successfull. So no buffering will be done at socket handlers if any
169 // packets sent before that by the application.
174 void P2PSocketHostTcpBase::StartTls() {
175 DCHECK_EQ(state_
, STATE_TLS_CONNECTING
);
176 DCHECK(socket_
.get());
178 scoped_ptr
<net::ClientSocketHandle
> socket_handle(
179 new net::ClientSocketHandle());
180 socket_handle
->SetSocket(socket_
.Pass());
182 net::SSLClientSocketContext context
;
183 context
.cert_verifier
= url_context_
->GetURLRequestContext()->cert_verifier();
184 context
.transport_security_state
=
185 url_context_
->GetURLRequestContext()->transport_security_state();
186 DCHECK(context
.transport_security_state
);
188 // Default ssl config.
189 const net::SSLConfig ssl_config
;
190 net::HostPortPair dest_host_port_pair
;
192 // Calling net::HostPortPair::FromIPEndPoint will crash if the IP address is
194 if (!remote_address_
.ip_address
.address().empty()) {
195 net::HostPortPair::FromIPEndPoint(remote_address_
.ip_address
);
197 dest_host_port_pair
.set_port(remote_address_
.ip_address
.port());
199 if (!remote_address_
.hostname
.empty())
200 dest_host_port_pair
.set_host(remote_address_
.hostname
);
202 net::ClientSocketFactory
* socket_factory
=
203 net::ClientSocketFactory::GetDefaultFactory();
204 DCHECK(socket_factory
);
206 socket_
= socket_factory
->CreateSSLClientSocket(
207 socket_handle
.Pass(), dest_host_port_pair
, ssl_config
, context
);
208 int status
= socket_
->Connect(
209 base::Bind(&P2PSocketHostTcpBase::ProcessTlsSslConnectDone
,
210 base::Unretained(this)));
212 if (status
!= net::ERR_IO_PENDING
) {
213 ProcessTlsSslConnectDone(status
);
217 void P2PSocketHostTcpBase::ProcessTlsSslConnectDone(int status
) {
218 DCHECK_NE(status
, net::ERR_IO_PENDING
);
219 DCHECK_EQ(state_
, STATE_TLS_CONNECTING
);
220 if (status
!= net::OK
) {
221 LOG(WARNING
) << "Error from connecting TLS socket, status=" << status
;
228 void P2PSocketHostTcpBase::OnOpen() {
230 // Setting socket send and receive buffer size.
231 if (net::OK
!= socket_
->SetReceiveBufferSize(kRecvSocketBufferSize
)) {
232 LOG(WARNING
) << "Failed to set socket receive buffer size to "
233 << kRecvSocketBufferSize
;
236 if (net::OK
!= socket_
->SetSendBufferSize(kSendSocketBufferSize
)) {
237 LOG(WARNING
) << "Failed to set socket send buffer size to "
238 << kSendSocketBufferSize
;
241 if (!DoSendSocketCreateMsg())
244 DCHECK_EQ(state_
, STATE_OPEN
);
248 bool P2PSocketHostTcpBase::DoSendSocketCreateMsg() {
249 DCHECK(socket_
.get());
251 net::IPEndPoint local_address
;
252 int result
= socket_
->GetLocalAddress(&local_address
);
254 LOG(ERROR
) << "P2PSocketHostTcpBase::OnConnected: unable to get local"
255 << " address: " << result
;
260 VLOG(1) << "Local address: " << local_address
.ToString();
262 net::IPEndPoint remote_address
;
264 // GetPeerAddress returns ERR_NAME_NOT_RESOLVED if the socket is connected
266 result
= socket_
->GetPeerAddress(&remote_address
);
267 if (result
< 0 && result
!= net::ERR_NAME_NOT_RESOLVED
) {
268 LOG(ERROR
) << "P2PSocketHostTcpBase::OnConnected: unable to get peer"
269 << " address: " << result
;
274 if (!remote_address
.address().empty()) {
275 VLOG(1) << "Remote address: " << remote_address
.ToString();
276 if (remote_address_
.ip_address
.address().empty()) {
277 // Save |remote_address| if address is empty.
278 remote_address_
.ip_address
= remote_address
;
281 VLOG(1) << "Remote address is unknown since connection is proxied";
284 // If we are not doing TLS, we are ready to send data now.
285 // In case of TLS SignalConnect will be sent only after TLS handshake is
286 // successful. So no buffering will be done at socket handlers if any
287 // packets sent before that by the application.
288 message_sender_
->Send(new P2PMsg_OnSocketCreated(
289 id_
, local_address
, remote_address
));
293 void P2PSocketHostTcpBase::DoRead() {
296 if (!read_buffer_
.get()) {
297 read_buffer_
= new net::GrowableIOBuffer();
298 read_buffer_
->SetCapacity(kReadBufferSize
);
299 } else if (read_buffer_
->RemainingCapacity() < kReadBufferSize
) {
300 // Make sure that we always have at least kReadBufferSize of
301 // remaining capacity in the read buffer. Normally all packets
302 // are smaller than kReadBufferSize, so this is not really
304 read_buffer_
->SetCapacity(read_buffer_
->capacity() + kReadBufferSize
-
305 read_buffer_
->RemainingCapacity());
307 result
= socket_
->Read(
309 read_buffer_
->RemainingCapacity(),
310 base::Bind(&P2PSocketHostTcp::OnRead
, base::Unretained(this)));
311 DidCompleteRead(result
);
312 } while (result
> 0);
315 void P2PSocketHostTcpBase::OnRead(int result
) {
316 DidCompleteRead(result
);
317 if (state_
== STATE_OPEN
) {
322 void P2PSocketHostTcpBase::OnPacket(const std::vector
<char>& data
) {
324 P2PSocketHost::StunMessageType type
;
325 bool stun
= GetStunPacketType(&*data
.begin(), data
.size(), &type
);
326 if (stun
&& IsRequestOrResponse(type
)) {
328 } else if (!stun
|| type
== STUN_DATA_INDICATION
) {
329 LOG(ERROR
) << "Received unexpected data packet from "
330 << remote_address_
.ip_address
.ToString()
331 << " before STUN binding is finished. "
332 << "Terminating connection.";
338 message_sender_
->Send(new P2PMsg_OnDataReceived(
339 id_
, remote_address_
.ip_address
, data
, base::TimeTicks::Now()));
341 if (dump_incoming_rtp_packet_
)
342 DumpRtpPacket(&data
[0], data
.size(), true);
345 // Note: dscp is not actually used on TCP sockets as this point,
346 // but may be honored in the future.
347 void P2PSocketHostTcpBase::Send(const net::IPEndPoint
& to
,
348 const std::vector
<char>& data
,
349 const rtc::PacketOptions
& options
,
352 // The Send message may be sent after the an OnError message was
353 // sent by hasn't been processed the renderer.
357 if (!(to
== remote_address_
.ip_address
)) {
358 // Renderer should use this socket only to send data to |remote_address_|.
365 P2PSocketHost::StunMessageType type
= P2PSocketHost::StunMessageType();
366 bool stun
= GetStunPacketType(&*data
.begin(), data
.size(), &type
);
367 if (!stun
|| type
== STUN_DATA_INDICATION
) {
368 LOG(ERROR
) << "Page tried to send a data packet to " << to
.ToString()
369 << " before STUN binding is finished.";
375 DoSend(to
, data
, options
);
378 void P2PSocketHostTcpBase::WriteOrQueue(
379 scoped_refptr
<net::DrainableIOBuffer
>& buffer
) {
380 IncrementTotalSentPackets();
381 if (write_buffer_
.get()) {
382 write_queue_
.push(buffer
);
383 IncrementDelayedPackets();
384 IncrementDelayedBytes(buffer
->size());
388 write_buffer_
= buffer
;
392 void P2PSocketHostTcpBase::DoWrite() {
393 while (write_buffer_
.get() && state_
== STATE_OPEN
&& !write_pending_
) {
394 int result
= socket_
->Write(
396 write_buffer_
->BytesRemaining(),
397 base::Bind(&P2PSocketHostTcp::OnWritten
, base::Unretained(this)));
398 HandleWriteResult(result
);
402 void P2PSocketHostTcpBase::OnWritten(int result
) {
403 DCHECK(write_pending_
);
404 DCHECK_NE(result
, net::ERR_IO_PENDING
);
406 write_pending_
= false;
407 HandleWriteResult(result
);
411 void P2PSocketHostTcpBase::HandleWriteResult(int result
) {
412 DCHECK(write_buffer_
.get());
414 write_buffer_
->DidConsume(result
);
415 if (write_buffer_
->BytesRemaining() == 0) {
416 message_sender_
->Send(
417 new P2PMsg_OnSendComplete(id_
, P2PSendPacketMetrics()));
418 if (write_queue_
.empty()) {
419 write_buffer_
= NULL
;
421 write_buffer_
= write_queue_
.front();
423 // Update how many bytes are still waiting to be sent.
424 DecrementDelayedBytes(write_buffer_
->size());
427 } else if (result
== net::ERR_IO_PENDING
) {
428 write_pending_
= true;
430 LOG(ERROR
) << "Error when sending data in TCP socket: " << result
;
435 P2PSocketHost
* P2PSocketHostTcpBase::AcceptIncomingTcpConnection(
436 const net::IPEndPoint
& remote_address
, int id
) {
442 void P2PSocketHostTcpBase::DidCompleteRead(int result
) {
443 DCHECK_EQ(state_
, STATE_OPEN
);
445 if (result
== net::ERR_IO_PENDING
) {
447 } else if (result
< 0) {
448 LOG(ERROR
) << "Error when reading from TCP socket: " << result
;
451 } else if (result
== 0) {
452 LOG(WARNING
) << "Remote peer has shutdown TCP socket.";
457 read_buffer_
->set_offset(read_buffer_
->offset() + result
);
458 char* head
= read_buffer_
->StartOfBuffer(); // Purely a convenience.
460 while (pos
<= read_buffer_
->offset() && state_
== STATE_OPEN
) {
461 int consumed
= ProcessInput(head
+ pos
, read_buffer_
->offset() - pos
);
466 // We've consumed all complete packets from the buffer; now move any remaining
467 // bytes to the head of the buffer and set offset to reflect this.
468 if (pos
&& pos
<= read_buffer_
->offset()) {
469 memmove(head
, head
+ pos
, read_buffer_
->offset() - pos
);
470 read_buffer_
->set_offset(read_buffer_
->offset() - pos
);
474 bool P2PSocketHostTcpBase::SetOption(P2PSocketOption option
, int value
) {
475 DCHECK_EQ(STATE_OPEN
, state_
);
477 case P2P_SOCKET_OPT_RCVBUF
:
478 return socket_
->SetReceiveBufferSize(value
) == net::OK
;
479 case P2P_SOCKET_OPT_SNDBUF
:
480 return socket_
->SetSendBufferSize(value
) == net::OK
;
481 case P2P_SOCKET_OPT_DSCP
:
482 return false; // For TCP sockets DSCP setting is not available.
489 P2PSocketHostTcp::P2PSocketHostTcp(IPC::Sender
* message_sender
,
492 net::URLRequestContextGetter
* url_context
)
493 : P2PSocketHostTcpBase(message_sender
, socket_id
, type
, url_context
) {
494 DCHECK(type
== P2P_SOCKET_TCP_CLIENT
||
495 type
== P2P_SOCKET_SSLTCP_CLIENT
||
496 type
== P2P_SOCKET_TLS_CLIENT
);
499 P2PSocketHostTcp::~P2PSocketHostTcp() {
502 int P2PSocketHostTcp::ProcessInput(char* input
, int input_len
) {
503 if (input_len
< kPacketHeaderSize
)
505 int packet_size
= base::NetToHost16(*reinterpret_cast<uint16
*>(input
));
506 if (input_len
< packet_size
+ kPacketHeaderSize
)
509 int consumed
= kPacketHeaderSize
;
510 char* cur
= input
+ consumed
;
511 std::vector
<char> data(cur
, cur
+ packet_size
);
513 consumed
+= packet_size
;
517 void P2PSocketHostTcp::DoSend(const net::IPEndPoint
& to
,
518 const std::vector
<char>& data
,
519 const rtc::PacketOptions
& options
) {
520 int size
= kPacketHeaderSize
+ data
.size();
521 scoped_refptr
<net::DrainableIOBuffer
> buffer
=
522 new net::DrainableIOBuffer(new net::IOBuffer(size
), size
);
523 *reinterpret_cast<uint16
*>(buffer
->data()) = base::HostToNet16(data
.size());
524 memcpy(buffer
->data() + kPacketHeaderSize
, &data
[0], data
.size());
526 packet_processing_helpers::ApplyPacketOptions(
527 buffer
->data() + kPacketHeaderSize
,
528 buffer
->BytesRemaining() - kPacketHeaderSize
,
531 WriteOrQueue(buffer
);
534 // P2PSocketHostStunTcp
535 P2PSocketHostStunTcp::P2PSocketHostStunTcp(
536 IPC::Sender
* message_sender
,
539 net::URLRequestContextGetter
* url_context
)
540 : P2PSocketHostTcpBase(message_sender
, socket_id
, type
, url_context
) {
541 DCHECK(type
== P2P_SOCKET_STUN_TCP_CLIENT
||
542 type
== P2P_SOCKET_STUN_SSLTCP_CLIENT
||
543 type
== P2P_SOCKET_STUN_TLS_CLIENT
);
546 P2PSocketHostStunTcp::~P2PSocketHostStunTcp() {
549 int P2PSocketHostStunTcp::ProcessInput(char* input
, int input_len
) {
550 if (input_len
< kPacketHeaderSize
+ kPacketLengthOffset
)
554 int packet_size
= GetExpectedPacketSize(
555 input
, input_len
, &pad_bytes
);
557 if (input_len
< packet_size
+ pad_bytes
)
560 // We have a complete packet. Read through it.
563 std::vector
<char> data(cur
, cur
+ packet_size
);
565 consumed
+= packet_size
;
566 consumed
+= pad_bytes
;
570 void P2PSocketHostStunTcp::DoSend(const net::IPEndPoint
& to
,
571 const std::vector
<char>& data
,
572 const rtc::PacketOptions
& options
) {
573 // Each packet is expected to have header (STUN/TURN ChannelData), where
574 // header contains message type and and length of message.
575 if (data
.size() < kPacketHeaderSize
+ kPacketLengthOffset
) {
582 size_t expected_len
= GetExpectedPacketSize(
583 &data
[0], data
.size(), &pad_bytes
);
585 // Accepts only complete STUN/TURN packets.
586 if (data
.size() != expected_len
) {
592 // Add any pad bytes to the total size.
593 int size
= data
.size() + pad_bytes
;
595 scoped_refptr
<net::DrainableIOBuffer
> buffer
=
596 new net::DrainableIOBuffer(new net::IOBuffer(size
), size
);
597 memcpy(buffer
->data(), &data
[0], data
.size());
599 packet_processing_helpers::ApplyPacketOptions(
600 buffer
->data(), data
.size(), options
, 0);
603 char padding
[4] = {0};
604 DCHECK_LE(pad_bytes
, 4);
605 memcpy(buffer
->data() + data
.size(), padding
, pad_bytes
);
607 WriteOrQueue(buffer
);
609 if (dump_outgoing_rtp_packet_
)
610 DumpRtpPacket(buffer
->data(), data
.size(), false);
613 int P2PSocketHostStunTcp::GetExpectedPacketSize(
614 const char* data
, int len
, int* pad_bytes
) {
615 DCHECK_LE(kTurnChannelDataHeaderSize
, len
);
616 // Both stun and turn had length at offset 2.
617 int packet_size
= base::NetToHost16(*reinterpret_cast<const uint16
*>(
618 data
+ kPacketLengthOffset
));
620 // Get packet type (STUN or TURN).
621 uint16 msg_type
= base::NetToHost16(*reinterpret_cast<const uint16
*>(data
));
624 // Add heder length to packet length.
625 if ((msg_type
& 0xC000) == 0) {
626 packet_size
+= kStunHeaderSize
;
628 packet_size
+= kTurnChannelDataHeaderSize
;
629 // Calculate any padding if present.
631 *pad_bytes
= 4 - packet_size
% 4;
636 } // namespace content