ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / content / browser / renderer_host / p2p / socket_host_tcp.cc
blob99d29ef1edd184ff829e50c53ae74deda1909d6b
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"
23 namespace {
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);
43 } // namespace
45 namespace content {
47 P2PSocketHostTcpBase::P2PSocketHostTcpBase(
48 IPC::Sender* message_sender,
49 int socket_id,
50 P2PSocketType type,
51 net::URLRequestContextGetter* url_context)
52 : P2PSocketHost(message_sender, socket_id, P2PSocketHost::TCP),
53 write_pending_(false),
54 connected_(false),
55 type_(type),
56 url_context_(url_context) {
59 P2PSocketHostTcpBase::~P2PSocketHostTcpBase() {
60 if (state_ == STATE_OPEN) {
61 DCHECK(socket_.get());
62 socket_.reset();
66 bool P2PSocketHostTcpBase::InitAccepted(const net::IPEndPoint& remote_address,
67 net::StreamSocket* socket) {
68 DCHECK(socket);
69 DCHECK_EQ(state_, STATE_UNINITIALIZED);
71 remote_address_.ip_address = remote_address;
72 // TODO(ronghuawu): Add FakeSSLServerSocket.
73 socket_.reset(socket);
74 state_ = STATE_OPEN;
75 DoRead();
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());
93 } else {
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.
106 url_context_,
107 ssl_config,
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();
119 CHECK(message_loop);
120 message_loop->PostTask(
121 FROM_HERE,
122 base::Bind(&P2PSocketHostTcpBase::OnConnected,
123 base::Unretained(this), status));
126 return state_ != STATE_ERROR;
129 void P2PSocketHostTcpBase::OnError() {
130 socket_.reset();
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 OnError();
146 return;
149 if (IsTlsClientSocket(type_)) {
150 state_ = STATE_TLS_CONNECTING;
151 StartTls();
152 } else if (IsPseudoTlsClientSocket(type_)) {
153 scoped_ptr<net::StreamSocket> transport_socket = socket_.Pass();
154 socket_.reset(
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);
163 } else {
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.
168 OnOpen();
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
191 // empty.
192 if (!remote_address_.ip_address.address().empty()) {
193 net::HostPortPair::FromIPEndPoint(remote_address_.ip_address);
194 } else {
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) {
218 OnError();
219 return;
221 OnOpen();
224 void P2PSocketHostTcpBase::OnOpen() {
225 state_ = STATE_OPEN;
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())
238 return;
240 DCHECK_EQ(state_, STATE_OPEN);
241 DoRead();
244 bool P2PSocketHostTcpBase::DoSendSocketCreateMsg() {
245 DCHECK(socket_.get());
247 net::IPEndPoint local_address;
248 int result = socket_->GetLocalAddress(&local_address);
249 if (result < 0) {
250 LOG(ERROR) << "P2PSocketHostTcpBase::OnConnected: unable to get local"
251 << " address: " << result;
252 OnError();
253 return false;
256 VLOG(1) << "Local address: " << local_address.ToString();
258 net::IPEndPoint remote_address;
260 // |remote_address| could be empty if it is connected through a proxy.
261 result = socket_->GetPeerAddress(&remote_address);
262 if (result < 0) {
263 LOG(ERROR) << "P2PSocketHostTcpBase::OnConnected: unable to get peer"
264 << " address: " << result;
265 OnError();
266 return false;
268 VLOG(1) << "Remote address: " << remote_address.ToString();
269 if (remote_address_.ip_address.address().empty() &&
270 !remote_address.address().empty()) {
271 // Save |remote_address| if address is empty.
272 remote_address_.ip_address = remote_address;
275 // If we are not doing TLS, we are ready to send data now.
276 // In case of TLS SignalConnect will be sent only after TLS handshake is
277 // successful. So no buffering will be done at socket handlers if any
278 // packets sent before that by the application.
279 message_sender_->Send(new P2PMsg_OnSocketCreated(
280 id_, local_address, remote_address));
281 return true;
284 void P2PSocketHostTcpBase::DoRead() {
285 int result;
286 do {
287 if (!read_buffer_.get()) {
288 read_buffer_ = new net::GrowableIOBuffer();
289 read_buffer_->SetCapacity(kReadBufferSize);
290 } else if (read_buffer_->RemainingCapacity() < kReadBufferSize) {
291 // Make sure that we always have at least kReadBufferSize of
292 // remaining capacity in the read buffer. Normally all packets
293 // are smaller than kReadBufferSize, so this is not really
294 // required.
295 read_buffer_->SetCapacity(read_buffer_->capacity() + kReadBufferSize -
296 read_buffer_->RemainingCapacity());
298 result = socket_->Read(
299 read_buffer_.get(),
300 read_buffer_->RemainingCapacity(),
301 base::Bind(&P2PSocketHostTcp::OnRead, base::Unretained(this)));
302 DidCompleteRead(result);
303 } while (result > 0);
306 void P2PSocketHostTcpBase::OnRead(int result) {
307 DidCompleteRead(result);
308 if (state_ == STATE_OPEN) {
309 DoRead();
313 void P2PSocketHostTcpBase::OnPacket(const std::vector<char>& data) {
314 if (!connected_) {
315 P2PSocketHost::StunMessageType type;
316 bool stun = GetStunPacketType(&*data.begin(), data.size(), &type);
317 if (stun && IsRequestOrResponse(type)) {
318 connected_ = true;
319 } else if (!stun || type == STUN_DATA_INDICATION) {
320 LOG(ERROR) << "Received unexpected data packet from "
321 << remote_address_.ip_address.ToString()
322 << " before STUN binding is finished. "
323 << "Terminating connection.";
324 OnError();
325 return;
329 message_sender_->Send(new P2PMsg_OnDataReceived(
330 id_, remote_address_.ip_address, data, base::TimeTicks::Now()));
332 if (dump_incoming_rtp_packet_)
333 DumpRtpPacket(&data[0], data.size(), true);
336 // Note: dscp is not actually used on TCP sockets as this point,
337 // but may be honored in the future.
338 void P2PSocketHostTcpBase::Send(const net::IPEndPoint& to,
339 const std::vector<char>& data,
340 const rtc::PacketOptions& options,
341 uint64 packet_id) {
342 if (!socket_) {
343 // The Send message may be sent after the an OnError message was
344 // sent by hasn't been processed the renderer.
345 return;
348 if (!(to == remote_address_.ip_address)) {
349 // Renderer should use this socket only to send data to |remote_address_|.
350 NOTREACHED();
351 OnError();
352 return;
355 if (!connected_) {
356 P2PSocketHost::StunMessageType type = P2PSocketHost::StunMessageType();
357 bool stun = GetStunPacketType(&*data.begin(), data.size(), &type);
358 if (!stun || type == STUN_DATA_INDICATION) {
359 LOG(ERROR) << "Page tried to send a data packet to " << to.ToString()
360 << " before STUN binding is finished.";
361 OnError();
362 return;
366 DoSend(to, data, options);
369 void P2PSocketHostTcpBase::WriteOrQueue(
370 scoped_refptr<net::DrainableIOBuffer>& buffer) {
371 IncrementTotalSentPackets();
372 if (write_buffer_.get()) {
373 write_queue_.push(buffer);
374 IncrementDelayedPackets();
375 IncrementDelayedBytes(buffer->size());
376 return;
379 write_buffer_ = buffer;
380 DoWrite();
383 void P2PSocketHostTcpBase::DoWrite() {
384 while (write_buffer_.get() && state_ == STATE_OPEN && !write_pending_) {
385 int result = socket_->Write(
386 write_buffer_.get(),
387 write_buffer_->BytesRemaining(),
388 base::Bind(&P2PSocketHostTcp::OnWritten, base::Unretained(this)));
389 HandleWriteResult(result);
393 void P2PSocketHostTcpBase::OnWritten(int result) {
394 DCHECK(write_pending_);
395 DCHECK_NE(result, net::ERR_IO_PENDING);
397 write_pending_ = false;
398 HandleWriteResult(result);
399 DoWrite();
402 void P2PSocketHostTcpBase::HandleWriteResult(int result) {
403 DCHECK(write_buffer_.get());
404 if (result >= 0) {
405 write_buffer_->DidConsume(result);
406 if (write_buffer_->BytesRemaining() == 0) {
407 message_sender_->Send(
408 new P2PMsg_OnSendComplete(id_, P2PSendPacketMetrics()));
409 if (write_queue_.empty()) {
410 write_buffer_ = NULL;
411 } else {
412 write_buffer_ = write_queue_.front();
413 write_queue_.pop();
414 // Update how many bytes are still waiting to be sent.
415 DecrementDelayedBytes(write_buffer_->size());
418 } else if (result == net::ERR_IO_PENDING) {
419 write_pending_ = true;
420 } else {
421 LOG(ERROR) << "Error when sending data in TCP socket: " << result;
422 OnError();
426 P2PSocketHost* P2PSocketHostTcpBase::AcceptIncomingTcpConnection(
427 const net::IPEndPoint& remote_address, int id) {
428 NOTREACHED();
429 OnError();
430 return NULL;
433 void P2PSocketHostTcpBase::DidCompleteRead(int result) {
434 DCHECK_EQ(state_, STATE_OPEN);
436 if (result == net::ERR_IO_PENDING) {
437 return;
438 } else if (result < 0) {
439 LOG(ERROR) << "Error when reading from TCP socket: " << result;
440 OnError();
441 return;
442 } else if (result == 0) {
443 LOG(WARNING) << "Remote peer has shutdown TCP socket.";
444 OnError();
445 return;
448 read_buffer_->set_offset(read_buffer_->offset() + result);
449 char* head = read_buffer_->StartOfBuffer(); // Purely a convenience.
450 int pos = 0;
451 while (pos <= read_buffer_->offset() && state_ == STATE_OPEN) {
452 int consumed = ProcessInput(head + pos, read_buffer_->offset() - pos);
453 if (!consumed)
454 break;
455 pos += consumed;
457 // We've consumed all complete packets from the buffer; now move any remaining
458 // bytes to the head of the buffer and set offset to reflect this.
459 if (pos && pos <= read_buffer_->offset()) {
460 memmove(head, head + pos, read_buffer_->offset() - pos);
461 read_buffer_->set_offset(read_buffer_->offset() - pos);
465 bool P2PSocketHostTcpBase::SetOption(P2PSocketOption option, int value) {
466 DCHECK_EQ(STATE_OPEN, state_);
467 switch (option) {
468 case P2P_SOCKET_OPT_RCVBUF:
469 return socket_->SetReceiveBufferSize(value) == net::OK;
470 case P2P_SOCKET_OPT_SNDBUF:
471 return socket_->SetSendBufferSize(value) == net::OK;
472 case P2P_SOCKET_OPT_DSCP:
473 return false; // For TCP sockets DSCP setting is not available.
474 default:
475 NOTREACHED();
476 return false;
480 P2PSocketHostTcp::P2PSocketHostTcp(IPC::Sender* message_sender,
481 int socket_id,
482 P2PSocketType type,
483 net::URLRequestContextGetter* url_context)
484 : P2PSocketHostTcpBase(message_sender, socket_id, type, url_context) {
485 DCHECK(type == P2P_SOCKET_TCP_CLIENT ||
486 type == P2P_SOCKET_SSLTCP_CLIENT ||
487 type == P2P_SOCKET_TLS_CLIENT);
490 P2PSocketHostTcp::~P2PSocketHostTcp() {
493 int P2PSocketHostTcp::ProcessInput(char* input, int input_len) {
494 if (input_len < kPacketHeaderSize)
495 return 0;
496 int packet_size = base::NetToHost16(*reinterpret_cast<uint16*>(input));
497 if (input_len < packet_size + kPacketHeaderSize)
498 return 0;
500 int consumed = kPacketHeaderSize;
501 char* cur = input + consumed;
502 std::vector<char> data(cur, cur + packet_size);
503 OnPacket(data);
504 consumed += packet_size;
505 return consumed;
508 void P2PSocketHostTcp::DoSend(const net::IPEndPoint& to,
509 const std::vector<char>& data,
510 const rtc::PacketOptions& options) {
511 int size = kPacketHeaderSize + data.size();
512 scoped_refptr<net::DrainableIOBuffer> buffer =
513 new net::DrainableIOBuffer(new net::IOBuffer(size), size);
514 *reinterpret_cast<uint16*>(buffer->data()) = base::HostToNet16(data.size());
515 memcpy(buffer->data() + kPacketHeaderSize, &data[0], data.size());
517 packet_processing_helpers::ApplyPacketOptions(
518 buffer->data() + kPacketHeaderSize,
519 buffer->BytesRemaining() - kPacketHeaderSize,
520 options, 0);
522 WriteOrQueue(buffer);
525 // P2PSocketHostStunTcp
526 P2PSocketHostStunTcp::P2PSocketHostStunTcp(
527 IPC::Sender* message_sender,
528 int socket_id,
529 P2PSocketType type,
530 net::URLRequestContextGetter* url_context)
531 : P2PSocketHostTcpBase(message_sender, socket_id, type, url_context) {
532 DCHECK(type == P2P_SOCKET_STUN_TCP_CLIENT ||
533 type == P2P_SOCKET_STUN_SSLTCP_CLIENT ||
534 type == P2P_SOCKET_STUN_TLS_CLIENT);
537 P2PSocketHostStunTcp::~P2PSocketHostStunTcp() {
540 int P2PSocketHostStunTcp::ProcessInput(char* input, int input_len) {
541 if (input_len < kPacketHeaderSize + kPacketLengthOffset)
542 return 0;
544 int pad_bytes;
545 int packet_size = GetExpectedPacketSize(
546 input, input_len, &pad_bytes);
548 if (input_len < packet_size + pad_bytes)
549 return 0;
551 // We have a complete packet. Read through it.
552 int consumed = 0;
553 char* cur = input;
554 std::vector<char> data(cur, cur + packet_size);
555 OnPacket(data);
556 consumed += packet_size;
557 consumed += pad_bytes;
558 return consumed;
561 void P2PSocketHostStunTcp::DoSend(const net::IPEndPoint& to,
562 const std::vector<char>& data,
563 const rtc::PacketOptions& options) {
564 // Each packet is expected to have header (STUN/TURN ChannelData), where
565 // header contains message type and and length of message.
566 if (data.size() < kPacketHeaderSize + kPacketLengthOffset) {
567 NOTREACHED();
568 OnError();
569 return;
572 int pad_bytes;
573 size_t expected_len = GetExpectedPacketSize(
574 &data[0], data.size(), &pad_bytes);
576 // Accepts only complete STUN/TURN packets.
577 if (data.size() != expected_len) {
578 NOTREACHED();
579 OnError();
580 return;
583 // Add any pad bytes to the total size.
584 int size = data.size() + pad_bytes;
586 scoped_refptr<net::DrainableIOBuffer> buffer =
587 new net::DrainableIOBuffer(new net::IOBuffer(size), size);
588 memcpy(buffer->data(), &data[0], data.size());
590 packet_processing_helpers::ApplyPacketOptions(
591 buffer->data(), data.size(), options, 0);
593 if (pad_bytes) {
594 char padding[4] = {0};
595 DCHECK_LE(pad_bytes, 4);
596 memcpy(buffer->data() + data.size(), padding, pad_bytes);
598 WriteOrQueue(buffer);
600 if (dump_outgoing_rtp_packet_)
601 DumpRtpPacket(buffer->data(), data.size(), false);
604 int P2PSocketHostStunTcp::GetExpectedPacketSize(
605 const char* data, int len, int* pad_bytes) {
606 DCHECK_LE(kTurnChannelDataHeaderSize, len);
607 // Both stun and turn had length at offset 2.
608 int packet_size = base::NetToHost16(*reinterpret_cast<const uint16*>(
609 data + kPacketLengthOffset));
611 // Get packet type (STUN or TURN).
612 uint16 msg_type = base::NetToHost16(*reinterpret_cast<const uint16*>(data));
614 *pad_bytes = 0;
615 // Add heder length to packet length.
616 if ((msg_type & 0xC000) == 0) {
617 packet_size += kStunHeaderSize;
618 } else {
619 packet_size += kTurnChannelDataHeaderSize;
620 // Calculate any padding if present.
621 if (packet_size % 4)
622 *pad_bytes = 4 - packet_size % 4;
624 return packet_size;
627 } // namespace content