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) {
149 if (IsTlsClientSocket(type_)) {
150 state_ = STATE_TLS_CONNECTING;
152 } else if (IsPseudoTlsClientSocket(type_)) {
153 scoped_ptr<net::StreamSocket> transport_socket = socket_.Pass();
155 new jingle_glue::FakeSSLClientSocket(transport_socket.Pass()));
156 state_ = STATE_TLS_CONNECTING;
157 int status = socket_->Connect(
158 base::Bind(&P2PSocketHostTcpBase::ProcessTlsSslConnectDone,
159 base::Unretained(this)));
160 if (status != net::ERR_IO_PENDING) {
161 ProcessTlsSslConnectDone(status);
164 // If we are not doing TLS, we are ready to send data now.
165 // In case of TLS, SignalConnect will be sent only after TLS handshake is
166 // successfull. So no buffering will be done at socket handlers if any
167 // packets sent before that by the application.
172 void P2PSocketHostTcpBase::StartTls() {
173 DCHECK_EQ(state_, STATE_TLS_CONNECTING);
174 DCHECK(socket_.get());
176 scoped_ptr<net::ClientSocketHandle> socket_handle(
177 new net::ClientSocketHandle());
178 socket_handle->SetSocket(socket_.Pass());
180 net::SSLClientSocketContext context;
181 context.cert_verifier = url_context_->GetURLRequestContext()->cert_verifier();
182 context.transport_security_state =
183 url_context_->GetURLRequestContext()->transport_security_state();
184 DCHECK(context.transport_security_state);
186 // Default ssl config.
187 const net::SSLConfig ssl_config;
188 net::HostPortPair dest_host_port_pair;
190 // Calling net::HostPortPair::FromIPEndPoint will crash if the IP address is
192 if (!remote_address_.ip_address.address().empty()) {
193 net::HostPortPair::FromIPEndPoint(remote_address_.ip_address);
195 dest_host_port_pair.set_port(remote_address_.ip_address.port());
197 if (!remote_address_.hostname.empty())
198 dest_host_port_pair.set_host(remote_address_.hostname);
200 net::ClientSocketFactory* socket_factory =
201 net::ClientSocketFactory::GetDefaultFactory();
202 DCHECK(socket_factory);
204 socket_ = socket_factory->CreateSSLClientSocket(
205 socket_handle.Pass(), dest_host_port_pair, ssl_config, context);
206 int status = socket_->Connect(
207 base::Bind(&P2PSocketHostTcpBase::ProcessTlsSslConnectDone,
208 base::Unretained(this)));
209 if (status != net::ERR_IO_PENDING) {
210 ProcessTlsSslConnectDone(status);
214 void P2PSocketHostTcpBase::ProcessTlsSslConnectDone(int status) {
215 DCHECK_NE(status, net::ERR_IO_PENDING);
216 DCHECK_EQ(state_, STATE_TLS_CONNECTING);
217 if (status != net::OK) {
224 void P2PSocketHostTcpBase::OnOpen() {
226 // Setting socket send and receive buffer size.
227 if (net::OK != socket_->SetReceiveBufferSize(kRecvSocketBufferSize)) {
228 LOG(WARNING) << "Failed to set socket receive buffer size to "
229 << kRecvSocketBufferSize;
232 if (net::OK != socket_->SetSendBufferSize(kSendSocketBufferSize)) {
233 LOG(WARNING) << "Failed to set socket send buffer size to "
234 << kSendSocketBufferSize;
237 if (!DoSendSocketCreateMsg())
240 DCHECK_EQ(state_, STATE_OPEN);
244 bool P2PSocketHostTcpBase::DoSendSocketCreateMsg() {
245 DCHECK(socket_.get());
247 net::IPEndPoint local_address;
248 int result = socket_->GetLocalAddress(&local_address);
250 LOG(ERROR) << "P2PSocketHostTcpBase::OnConnected: unable to get local"
251 << " address: " << result;
256 VLOG(1) << "Local address: " << local_address.ToString();
258 net::IPEndPoint remote_address;
259 result = socket_->GetPeerAddress(&remote_address);
261 LOG(ERROR) << "P2PSocketHostTcpBase::OnConnected: unable to get peer"
262 << " address: " << result;
266 VLOG(1) << "Remote address: " << remote_address.ToString();
267 if (remote_address_.ip_address.address().empty()) {
268 // Save |remote_address| if address is empty.
269 remote_address_.ip_address = remote_address;
272 // If we are not doing TLS, we are ready to send data now.
273 // In case of TLS SignalConnect will be sent only after TLS handshake is
274 // successfull. So no buffering will be done at socket handlers if any
275 // packets sent before that by the application.
276 message_sender_->Send(new P2PMsg_OnSocketCreated(
277 id_, local_address, remote_address));
281 void P2PSocketHostTcpBase::DoRead() {
284 if (!read_buffer_.get()) {
285 read_buffer_ = new net::GrowableIOBuffer();
286 read_buffer_->SetCapacity(kReadBufferSize);
287 } else if (read_buffer_->RemainingCapacity() < kReadBufferSize) {
288 // Make sure that we always have at least kReadBufferSize of
289 // remaining capacity in the read buffer. Normally all packets
290 // are smaller than kReadBufferSize, so this is not really
292 read_buffer_->SetCapacity(read_buffer_->capacity() + kReadBufferSize -
293 read_buffer_->RemainingCapacity());
295 result = socket_->Read(
297 read_buffer_->RemainingCapacity(),
298 base::Bind(&P2PSocketHostTcp::OnRead, base::Unretained(this)));
299 DidCompleteRead(result);
300 } while (result > 0);
303 void P2PSocketHostTcpBase::OnRead(int result) {
304 DidCompleteRead(result);
305 if (state_ == STATE_OPEN) {
310 void P2PSocketHostTcpBase::OnPacket(const std::vector<char>& data) {
312 P2PSocketHost::StunMessageType type;
313 bool stun = GetStunPacketType(&*data.begin(), data.size(), &type);
314 if (stun && IsRequestOrResponse(type)) {
316 } else if (!stun || type == STUN_DATA_INDICATION) {
317 LOG(ERROR) << "Received unexpected data packet from "
318 << remote_address_.ip_address.ToString()
319 << " before STUN binding is finished. "
320 << "Terminating connection.";
326 message_sender_->Send(new P2PMsg_OnDataReceived(
327 id_, remote_address_.ip_address, data, base::TimeTicks::Now()));
329 if (dump_incoming_rtp_packet_)
330 DumpRtpPacket(&data[0], data.size(), true);
333 // Note: dscp is not actually used on TCP sockets as this point,
334 // but may be honored in the future.
335 void P2PSocketHostTcpBase::Send(const net::IPEndPoint& to,
336 const std::vector<char>& data,
337 const rtc::PacketOptions& options,
340 // The Send message may be sent after the an OnError message was
341 // sent by hasn't been processed the renderer.
345 if (!(to == remote_address_.ip_address)) {
346 // Renderer should use this socket only to send data to |remote_address_|.
353 P2PSocketHost::StunMessageType type = P2PSocketHost::StunMessageType();
354 bool stun = GetStunPacketType(&*data.begin(), data.size(), &type);
355 if (!stun || type == STUN_DATA_INDICATION) {
356 LOG(ERROR) << "Page tried to send a data packet to " << to.ToString()
357 << " before STUN binding is finished.";
363 DoSend(to, data, options);
366 void P2PSocketHostTcpBase::WriteOrQueue(
367 scoped_refptr<net::DrainableIOBuffer>& buffer) {
368 IncrementTotalSentPackets();
369 if (write_buffer_.get()) {
370 write_queue_.push(buffer);
371 IncrementDelayedPackets();
372 IncrementDelayedBytes(buffer->size());
376 write_buffer_ = buffer;
380 void P2PSocketHostTcpBase::DoWrite() {
381 while (write_buffer_.get() && state_ == STATE_OPEN && !write_pending_) {
382 int result = socket_->Write(
384 write_buffer_->BytesRemaining(),
385 base::Bind(&P2PSocketHostTcp::OnWritten, base::Unretained(this)));
386 HandleWriteResult(result);
390 void P2PSocketHostTcpBase::OnWritten(int result) {
391 DCHECK(write_pending_);
392 DCHECK_NE(result, net::ERR_IO_PENDING);
394 write_pending_ = false;
395 HandleWriteResult(result);
399 void P2PSocketHostTcpBase::HandleWriteResult(int result) {
400 DCHECK(write_buffer_.get());
402 write_buffer_->DidConsume(result);
403 if (write_buffer_->BytesRemaining() == 0) {
404 message_sender_->Send(new P2PMsg_OnSendComplete(id_));
405 if (write_queue_.empty()) {
406 write_buffer_ = NULL;
408 write_buffer_ = write_queue_.front();
410 // Update how many bytes are still waiting to be sent.
411 DecrementDelayedBytes(write_buffer_->size());
414 } else if (result == net::ERR_IO_PENDING) {
415 write_pending_ = true;
417 LOG(ERROR) << "Error when sending data in TCP socket: " << result;
422 P2PSocketHost* P2PSocketHostTcpBase::AcceptIncomingTcpConnection(
423 const net::IPEndPoint& remote_address, int id) {
429 void P2PSocketHostTcpBase::DidCompleteRead(int result) {
430 DCHECK_EQ(state_, STATE_OPEN);
432 if (result == net::ERR_IO_PENDING) {
434 } else if (result < 0) {
435 LOG(ERROR) << "Error when reading from TCP socket: " << result;
440 read_buffer_->set_offset(read_buffer_->offset() + result);
441 char* head = read_buffer_->StartOfBuffer(); // Purely a convenience.
443 while (pos <= read_buffer_->offset() && state_ == STATE_OPEN) {
444 int consumed = ProcessInput(head + pos, read_buffer_->offset() - pos);
449 // We've consumed all complete packets from the buffer; now move any remaining
450 // bytes to the head of the buffer and set offset to reflect this.
451 if (pos && pos <= read_buffer_->offset()) {
452 memmove(head, head + pos, read_buffer_->offset() - pos);
453 read_buffer_->set_offset(read_buffer_->offset() - pos);
457 bool P2PSocketHostTcpBase::SetOption(P2PSocketOption option, int value) {
458 DCHECK_EQ(STATE_OPEN, state_);
460 case P2P_SOCKET_OPT_RCVBUF:
461 return socket_->SetReceiveBufferSize(value) == net::OK;
462 case P2P_SOCKET_OPT_SNDBUF:
463 return socket_->SetSendBufferSize(value) == net::OK;
464 case P2P_SOCKET_OPT_DSCP:
465 return false; // For TCP sockets DSCP setting is not available.
472 P2PSocketHostTcp::P2PSocketHostTcp(IPC::Sender* message_sender,
475 net::URLRequestContextGetter* url_context)
476 : P2PSocketHostTcpBase(message_sender, socket_id, type, url_context) {
477 DCHECK(type == P2P_SOCKET_TCP_CLIENT ||
478 type == P2P_SOCKET_SSLTCP_CLIENT ||
479 type == P2P_SOCKET_TLS_CLIENT);
482 P2PSocketHostTcp::~P2PSocketHostTcp() {
485 int P2PSocketHostTcp::ProcessInput(char* input, int input_len) {
486 if (input_len < kPacketHeaderSize)
488 int packet_size = base::NetToHost16(*reinterpret_cast<uint16*>(input));
489 if (input_len < packet_size + kPacketHeaderSize)
492 int consumed = kPacketHeaderSize;
493 char* cur = input + consumed;
494 std::vector<char> data(cur, cur + packet_size);
496 consumed += packet_size;
500 void P2PSocketHostTcp::DoSend(const net::IPEndPoint& to,
501 const std::vector<char>& data,
502 const rtc::PacketOptions& options) {
503 int size = kPacketHeaderSize + data.size();
504 scoped_refptr<net::DrainableIOBuffer> buffer =
505 new net::DrainableIOBuffer(new net::IOBuffer(size), size);
506 *reinterpret_cast<uint16*>(buffer->data()) = base::HostToNet16(data.size());
507 memcpy(buffer->data() + kPacketHeaderSize, &data[0], data.size());
509 packet_processing_helpers::ApplyPacketOptions(
510 buffer->data() + kPacketHeaderSize,
511 buffer->BytesRemaining() - kPacketHeaderSize,
514 WriteOrQueue(buffer);
517 // P2PSocketHostStunTcp
518 P2PSocketHostStunTcp::P2PSocketHostStunTcp(
519 IPC::Sender* message_sender,
522 net::URLRequestContextGetter* url_context)
523 : P2PSocketHostTcpBase(message_sender, socket_id, type, url_context) {
524 DCHECK(type == P2P_SOCKET_STUN_TCP_CLIENT ||
525 type == P2P_SOCKET_STUN_SSLTCP_CLIENT ||
526 type == P2P_SOCKET_STUN_TLS_CLIENT);
529 P2PSocketHostStunTcp::~P2PSocketHostStunTcp() {
532 int P2PSocketHostStunTcp::ProcessInput(char* input, int input_len) {
533 if (input_len < kPacketHeaderSize + kPacketLengthOffset)
537 int packet_size = GetExpectedPacketSize(
538 input, input_len, &pad_bytes);
540 if (input_len < packet_size + pad_bytes)
543 // We have a complete packet. Read through it.
546 std::vector<char> data(cur, cur + packet_size);
548 consumed += packet_size;
549 consumed += pad_bytes;
553 void P2PSocketHostStunTcp::DoSend(const net::IPEndPoint& to,
554 const std::vector<char>& data,
555 const rtc::PacketOptions& options) {
556 // Each packet is expected to have header (STUN/TURN ChannelData), where
557 // header contains message type and and length of message.
558 if (data.size() < kPacketHeaderSize + kPacketLengthOffset) {
565 size_t expected_len = GetExpectedPacketSize(
566 &data[0], data.size(), &pad_bytes);
568 // Accepts only complete STUN/TURN packets.
569 if (data.size() != expected_len) {
575 // Add any pad bytes to the total size.
576 int size = data.size() + pad_bytes;
578 scoped_refptr<net::DrainableIOBuffer> buffer =
579 new net::DrainableIOBuffer(new net::IOBuffer(size), size);
580 memcpy(buffer->data(), &data[0], data.size());
582 packet_processing_helpers::ApplyPacketOptions(
583 buffer->data(), data.size(), options, 0);
586 char padding[4] = {0};
587 DCHECK_LE(pad_bytes, 4);
588 memcpy(buffer->data() + data.size(), padding, pad_bytes);
590 WriteOrQueue(buffer);
592 if (dump_outgoing_rtp_packet_)
593 DumpRtpPacket(buffer->data(), data.size(), false);
596 int P2PSocketHostStunTcp::GetExpectedPacketSize(
597 const char* data, int len, int* pad_bytes) {
598 DCHECK_LE(kTurnChannelDataHeaderSize, len);
599 // Both stun and turn had length at offset 2.
600 int packet_size = base::NetToHost16(*reinterpret_cast<const uint16*>(
601 data + kPacketLengthOffset));
603 // Get packet type (STUN or TURN).
604 uint16 msg_type = base::NetToHost16(*reinterpret_cast<const uint16*>(data));
607 // Add heder length to packet length.
608 if ((msg_type & 0xC000) == 0) {
609 packet_size += kStunHeaderSize;
611 packet_size += kTurnChannelDataHeaderSize;
612 // Calculate any padding if present.
614 *pad_bytes = 4 - packet_size % 4;
619 } // namespace content