blob: 2590d0aca893610551ab9af824701361afb27371 [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Guo-wei Shiehbe508a12015-04-06 12:48:47 -070011/*
12 * This is a diagram of how TCP reconnect works for the active side. The
13 * passive side just waits for an incoming connection.
14 *
15 * - Connected: Indicate whether the TCP socket is connected.
16 *
17 * - Writable: Whether the stun binding is completed. Sending a data packet
18 * before stun binding completed will trigger IPC socket layer to shutdown
19 * the connection.
20 *
21 * - PendingTCP: |connection_pending_| indicates whether there is an
22 * outstanding TCP connection in progress.
23 *
24 * - PretendWri: Tracked by |pretending_to_be_writable_|. Marking connection as
25 * WRITE_TIMEOUT will cause the connection be deleted. Instead, we're
26 * "pretending" we're still writable for a period of time such that reconnect
27 * could work.
28 *
29 * Data could only be sent in state 3. Sening data during state 2 & 6 will get
30 * EWOULDBLOCK, 4 & 5 EPIPE.
31 *
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -070032 * OS Timeout 7 -------------+
33 * +----------------------->|Connected: N |
34 * | |Writable: N | Timeout
35 * | Timeout |Connection is |<----------------+
36 * | +------------------->|Dead | |
37 * | | +--------------+ |
38 * | | ^ |
39 * | | OnClose | |
40 * | | +-----------------------+ | |
41 * | | | | |Timeout |
42 * | | v | | |
43 * | 4 +----------+ 5 -----+--+--+ 6 -----+-----+
44 * | |Connected: N|Send() or |Connected: N| |Connected: Y|
45 * | |Writable: Y|Ping() |Writable: Y|OnConnect |Writable: Y|
46 * | |PendingTCP:N+--------> |PendingTCP:Y+---------> |PendingTCP:N|
47 * | |PretendWri:Y| |PretendWri:Y| |PretendWri:Y|
48 * | +-----+------+ +------------+ +---+--+-----+
49 * | ^ ^ | |
50 * | | | OnClose | |
51 * | | +----------------------------------------------+ |
52 * | | |
53 * | | Stun Binding Completed |
54 * | | |
55 * | | OnClose |
56 * | +------------------------------------------------+ |
57 * | | v
Guo-wei Shiehbe508a12015-04-06 12:48:47 -070058 * 1 -----------+ 2 -----------+Stun 3 -----------+
59 * |Connected: N| |Connected: Y|Binding |Connected: Y|
60 * |Writable: N|OnConnect |Writable: N|Completed |Writable: Y|
61 * |PendingTCP:Y+---------> |PendingTCP:N+--------> |PendingTCP:N|
62 * |PretendWri:N| |PretendWri:N| |PretendWri:N|
63 * +------------+ +------------+ +------------+
64 *
65 */
66
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000067#include "webrtc/p2p/base/tcpport.h"
68
69#include "webrtc/p2p/base/common.h"
70#include "webrtc/base/common.h"
71#include "webrtc/base/logging.h"
72
73namespace cricket {
74
75TCPPort::TCPPort(rtc::Thread* thread,
76 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +000077 rtc::Network* network,
78 const rtc::IPAddress& ip,
Peter Boström0c4e06b2015-10-07 12:23:21 +020079 uint16_t min_port,
80 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +000081 const std::string& username,
82 const std::string& password,
83 bool allow_listen)
Peter Boström0c4e06b2015-10-07 12:23:21 +020084 : Port(thread,
85 LOCAL_PORT_TYPE,
86 factory,
87 network,
88 ip,
89 min_port,
90 max_port,
91 username,
92 password),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000093 incoming_only_(false),
94 allow_listen_(allow_listen),
95 socket_(NULL),
96 error_(0) {
97 // TODO(mallinath) - Set preference value as per RFC 6544.
98 // http://b/issue?id=7141794
99}
100
101bool TCPPort::Init() {
102 if (allow_listen_) {
103 // Treat failure to create or bind a TCP socket as fatal. This
104 // should never happen.
105 socket_ = socket_factory()->CreateServerTcpSocket(
106 rtc::SocketAddress(ip(), 0), min_port(), max_port(),
107 false /* ssl */);
108 if (!socket_) {
109 LOG_J(LS_ERROR, this) << "TCP socket creation failed.";
110 return false;
111 }
112 socket_->SignalNewConnection.connect(this, &TCPPort::OnNewConnection);
113 socket_->SignalAddressReady.connect(this, &TCPPort::OnAddressReady);
114 }
115 return true;
116}
117
118TCPPort::~TCPPort() {
119 delete socket_;
120 std::list<Incoming>::iterator it;
121 for (it = incoming_.begin(); it != incoming_.end(); ++it)
122 delete it->socket;
123 incoming_.clear();
124}
125
126Connection* TCPPort::CreateConnection(const Candidate& address,
127 CandidateOrigin origin) {
128 // We only support TCP protocols
129 if ((address.protocol() != TCP_PROTOCOL_NAME) &&
130 (address.protocol() != SSLTCP_PROTOCOL_NAME)) {
131 return NULL;
132 }
133
134 if (address.tcptype() == TCPTYPE_ACTIVE_STR ||
135 (address.tcptype().empty() && address.address().port() == 0)) {
136 // It's active only candidate, we should not try to create connections
137 // for these candidates.
138 return NULL;
139 }
140
141 // We can't accept TCP connections incoming on other ports
142 if (origin == ORIGIN_OTHER_PORT)
143 return NULL;
144
145 // Check if we are allowed to make outgoing TCP connections
146 if (incoming_only_ && (origin == ORIGIN_MESSAGE))
147 return NULL;
148
149 // We don't know how to act as an ssl server yet
150 if ((address.protocol() == SSLTCP_PROTOCOL_NAME) &&
151 (origin == ORIGIN_THIS_PORT)) {
152 return NULL;
153 }
154
155 if (!IsCompatibleAddress(address.address())) {
156 return NULL;
157 }
158
159 TCPConnection* conn = NULL;
160 if (rtc::AsyncPacketSocket* socket =
161 GetIncoming(address.address(), true)) {
162 socket->SignalReadPacket.disconnect(this);
163 conn = new TCPConnection(this, address, socket);
164 } else {
165 conn = new TCPConnection(this, address);
166 }
167 AddConnection(conn);
168 return conn;
169}
170
171void TCPPort::PrepareAddress() {
172 if (socket_) {
173 // If socket isn't bound yet the address will be added in
174 // OnAddressReady(). Socket may be in the CLOSED state if Listen()
175 // failed, we still want to add the socket address.
176 LOG(LS_VERBOSE) << "Preparing TCP address, current state: "
177 << socket_->GetState();
178 if (socket_->GetState() == rtc::AsyncPacketSocket::STATE_BOUND ||
179 socket_->GetState() == rtc::AsyncPacketSocket::STATE_CLOSED)
180 AddAddress(socket_->GetLocalAddress(), socket_->GetLocalAddress(),
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700181 rtc::SocketAddress(), TCP_PROTOCOL_NAME, "",
182 TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000183 ICE_TYPE_PREFERENCE_HOST_TCP, 0, true);
184 } else {
185 LOG_J(LS_INFO, this) << "Not listening due to firewall restrictions.";
186 // Note: We still add the address, since otherwise the remote side won't
187 // recognize our incoming TCP connections.
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700188 AddAddress(rtc::SocketAddress(ip(), 0), rtc::SocketAddress(ip(), 0),
189 rtc::SocketAddress(), TCP_PROTOCOL_NAME, "", TCPTYPE_ACTIVE_STR,
190 LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP, 0, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000191 }
192}
193
194int TCPPort::SendTo(const void* data, size_t size,
195 const rtc::SocketAddress& addr,
196 const rtc::PacketOptions& options,
197 bool payload) {
198 rtc::AsyncPacketSocket * socket = NULL;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700199 TCPConnection* conn = static_cast<TCPConnection*>(GetConnection(addr));
200
201 // For Connection, this is the code path used by Ping() to establish
202 // WRITABLE. It has to send through the socket directly as TCPConnection::Send
203 // checks writability.
204 if (conn) {
205 if (!conn->connected()) {
206 conn->MaybeReconnect();
207 return SOCKET_ERROR;
208 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000209 socket = conn->socket();
210 } else {
211 socket = GetIncoming(addr);
212 }
213 if (!socket) {
214 LOG_J(LS_ERROR, this) << "Attempted to send to an unknown destination, "
215 << addr.ToSensitiveString();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700216 return SOCKET_ERROR; // TODO(tbd): Set error_
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000217 }
218
219 int sent = socket->Send(data, size, options);
220 if (sent < 0) {
221 error_ = socket->GetError();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700222 // Error from this code path for a Connection (instead of from a bare
223 // socket) will not trigger reconnecting. In theory, this shouldn't matter
224 // as OnClose should always be called and set connected to false.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000225 LOG_J(LS_ERROR, this) << "TCP send of " << size
226 << " bytes failed with error " << error_;
227 }
228 return sent;
229}
230
231int TCPPort::GetOption(rtc::Socket::Option opt, int* value) {
232 if (socket_) {
233 return socket_->GetOption(opt, value);
234 } else {
235 return SOCKET_ERROR;
236 }
237}
238
239int TCPPort::SetOption(rtc::Socket::Option opt, int value) {
240 if (socket_) {
241 return socket_->SetOption(opt, value);
242 } else {
243 return SOCKET_ERROR;
244 }
245}
246
247int TCPPort::GetError() {
248 return error_;
249}
250
251void TCPPort::OnNewConnection(rtc::AsyncPacketSocket* socket,
252 rtc::AsyncPacketSocket* new_socket) {
253 ASSERT(socket == socket_);
254
255 Incoming incoming;
256 incoming.addr = new_socket->GetRemoteAddress();
257 incoming.socket = new_socket;
258 incoming.socket->SignalReadPacket.connect(this, &TCPPort::OnReadPacket);
259 incoming.socket->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
260
261 LOG_J(LS_VERBOSE, this) << "Accepted connection from "
262 << incoming.addr.ToSensitiveString();
263 incoming_.push_back(incoming);
264}
265
266rtc::AsyncPacketSocket* TCPPort::GetIncoming(
267 const rtc::SocketAddress& addr, bool remove) {
268 rtc::AsyncPacketSocket* socket = NULL;
269 for (std::list<Incoming>::iterator it = incoming_.begin();
270 it != incoming_.end(); ++it) {
271 if (it->addr == addr) {
272 socket = it->socket;
273 if (remove)
274 incoming_.erase(it);
275 break;
276 }
277 }
278 return socket;
279}
280
281void TCPPort::OnReadPacket(rtc::AsyncPacketSocket* socket,
282 const char* data, size_t size,
283 const rtc::SocketAddress& remote_addr,
284 const rtc::PacketTime& packet_time) {
285 Port::OnReadPacket(data, size, remote_addr, PROTO_TCP);
286}
287
288void TCPPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
289 Port::OnReadyToSend();
290}
291
292void TCPPort::OnAddressReady(rtc::AsyncPacketSocket* socket,
293 const rtc::SocketAddress& address) {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700294 AddAddress(address, address, rtc::SocketAddress(), TCP_PROTOCOL_NAME, "",
295 TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP,
296 0, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000297}
298
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700299TCPConnection::TCPConnection(TCPPort* port,
300 const Candidate& candidate,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000301 rtc::AsyncPacketSocket* socket)
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700302 : Connection(port, 0, candidate),
303 socket_(socket),
304 error_(0),
305 outgoing_(socket == NULL),
306 connection_pending_(false),
307 pretending_to_be_writable_(false),
308 reconnection_timeout_(cricket::CONNECTION_WRITE_CONNECT_TIMEOUT) {
309 if (outgoing_) {
310 CreateOutgoingTcpSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000311 } else {
312 // Incoming connections should match the network address.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700313 LOG_J(LS_VERBOSE, this)
314 << "socket ipaddr: " << socket_->GetLocalAddress().ToString()
315 << ",port() ip:" << port->ip().ToString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000316 ASSERT(socket_->GetLocalAddress().ipaddr() == port->ip());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700317 ConnectSocketSignals(socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000318 }
319}
320
321TCPConnection::~TCPConnection() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000322}
323
324int TCPConnection::Send(const void* data, size_t size,
325 const rtc::PacketOptions& options) {
326 if (!socket_) {
327 error_ = ENOTCONN;
328 return SOCKET_ERROR;
329 }
330
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700331 // Sending after OnClose on active side will trigger a reconnect for a
332 // outgoing connection. Note that the write state is still WRITABLE as we want
333 // to spend a few seconds attempting a reconnect before saying we're
334 // unwritable.
335 if (!connected()) {
336 MaybeReconnect();
337 return SOCKET_ERROR;
338 }
339
340 // Note that this is important to put this after the previous check to give
341 // the connection a chance to reconnect.
342 if (pretending_to_be_writable_ || write_state() != STATE_WRITABLE) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000343 // TODO: Should STATE_WRITE_TIMEOUT return a non-blocking error?
344 error_ = EWOULDBLOCK;
345 return SOCKET_ERROR;
346 }
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000347 sent_packets_total_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000348 int sent = socket_->Send(data, size, options);
349 if (sent < 0) {
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000350 sent_packets_discarded_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000351 error_ = socket_->GetError();
352 } else {
Tim Psiaki63046262015-09-14 10:38:08 -0700353 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000354 }
355 return sent;
356}
357
358int TCPConnection::GetError() {
359 return error_;
360}
361
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700362void TCPConnection::OnConnectionRequestResponse(ConnectionRequest* req,
363 StunMessage* response) {
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700364 // Process the STUN response before we inform upper layer ready to send.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700365 Connection::OnConnectionRequestResponse(req, response);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700366
367 // If we're in the state of pretending to be writeable, we should inform the
368 // upper layer it's ready to send again as previous EWOULDLBLOCK from socket
369 // would have stopped the outgoing stream.
370 if (pretending_to_be_writable_) {
371 Connection::OnReadyToSend();
372 }
373 pretending_to_be_writable_ = false;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700374 ASSERT(write_state() == STATE_WRITABLE);
375}
376
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000377void TCPConnection::OnConnect(rtc::AsyncPacketSocket* socket) {
378 ASSERT(socket == socket_);
379 // Do not use this connection if the socket bound to a different address than
380 // the one we asked for. This is seen in Chrome, where TCP sockets cannot be
381 // given a binding address, and the platform is expected to pick the
382 // correct local address.
henrike@webrtc.org43e033e2014-11-10 19:40:29 +0000383 const rtc::IPAddress& socket_ip = socket->GetLocalAddress().ipaddr();
Guo-wei Shieh53eee432015-09-23 14:09:09 -0700384 if (socket_ip == port()->ip() || IPIsAny(port()->ip())) {
385 if (socket_ip == port()->ip()) {
386 LOG_J(LS_VERBOSE, this) << "Connection established to "
387 << socket->GetRemoteAddress().ToSensitiveString();
388 } else {
389 LOG(LS_WARNING) << "Socket is bound to a different address:"
390 << socket->GetLocalAddress().ipaddr().ToString()
391 << ", rather then the local port:"
392 << port()->ip().ToString()
393 << ". Still allowing it since it's any address"
394 << ", possibly caused by multi-routes being disabled.";
395 }
Guo-wei Shieh2e4b6202015-09-23 13:57:07 -0700396 set_connected(true);
397 connection_pending_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000398 } else {
henrike@webrtc.org43e033e2014-11-10 19:40:29 +0000399 LOG_J(LS_WARNING, this) << "Dropping connection as TCP socket bound to IP "
400 << socket_ip.ToSensitiveString()
401 << ", different from the local candidate IP "
402 << port()->ip().ToSensitiveString();
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700403 OnClose(socket, 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000404 }
405}
406
407void TCPConnection::OnClose(rtc::AsyncPacketSocket* socket, int error) {
408 ASSERT(socket == socket_);
henrike@webrtc.org43e033e2014-11-10 19:40:29 +0000409 LOG_J(LS_INFO, this) << "Connection closed with error " << error;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700410
411 // Guard against the condition where IPC socket will call OnClose for every
412 // packet it can't send.
413 if (connected()) {
414 set_connected(false);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700415
416 // Prevent the connection from being destroyed by redundant SignalClose
417 // events.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700418 pretending_to_be_writable_ = true;
419
420 // We don't attempt reconnect right here. This is to avoid a case where the
421 // shutdown is intentional and reconnect is not necessary. We only reconnect
422 // when the connection is used to Send() or Ping().
423 port()->thread()->PostDelayed(reconnection_timeout(), this,
424 MSG_TCPCONNECTION_DELAYED_ONCLOSE);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700425 } else if (!pretending_to_be_writable_) {
426 // OnClose could be called when the underneath socket times out during the
427 // initial connect() (i.e. |pretending_to_be_writable_| is false) . We have
428 // to manually destroy here as this connection, as never connected, will not
429 // be scheduled for ping to trigger destroy.
430 Destroy();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700431 }
432}
433
434void TCPConnection::OnMessage(rtc::Message* pmsg) {
435 switch (pmsg->message_id) {
436 case MSG_TCPCONNECTION_DELAYED_ONCLOSE:
437 // If this connection can't become connected and writable again in 5
438 // seconds, it's time to tear this down. This is the case for the original
439 // TCP connection on passive side during a reconnect.
440 if (pretending_to_be_writable_) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700441 Destroy();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700442 }
443 break;
444 default:
445 Connection::OnMessage(pmsg);
446 }
447}
448
449void TCPConnection::MaybeReconnect() {
450 // Only reconnect for an outgoing TCPConnection when OnClose was signaled and
451 // no outstanding reconnect is pending.
452 if (connected() || connection_pending_ || !outgoing_) {
453 return;
454 }
455
456 LOG_J(LS_INFO, this) << "TCP Connection with remote is closed, "
457 << "trying to reconnect";
458
459 CreateOutgoingTcpSocket();
460 error_ = EPIPE;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000461}
462
463void TCPConnection::OnReadPacket(
464 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
465 const rtc::SocketAddress& remote_addr,
466 const rtc::PacketTime& packet_time) {
467 ASSERT(socket == socket_);
468 Connection::OnReadPacket(data, size, packet_time);
469}
470
471void TCPConnection::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
472 ASSERT(socket == socket_);
473 Connection::OnReadyToSend();
474}
475
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700476void TCPConnection::CreateOutgoingTcpSocket() {
477 ASSERT(outgoing_);
478 // TODO(guoweis): Handle failures here (unlikely since TCP).
479 int opts = (remote_candidate().protocol() == SSLTCP_PROTOCOL_NAME)
480 ? rtc::PacketSocketFactory::OPT_SSLTCP
481 : 0;
482 socket_.reset(port()->socket_factory()->CreateClientTcpSocket(
483 rtc::SocketAddress(port()->ip(), 0), remote_candidate().address(),
484 port()->proxy(), port()->user_agent(), opts));
485 if (socket_) {
486 LOG_J(LS_VERBOSE, this)
487 << "Connecting from " << socket_->GetLocalAddress().ToSensitiveString()
488 << " to " << remote_candidate().address().ToSensitiveString();
489 set_connected(false);
490 connection_pending_ = true;
491 ConnectSocketSignals(socket_.get());
492 } else {
493 LOG_J(LS_WARNING, this) << "Failed to create connection to "
494 << remote_candidate().address().ToSensitiveString();
495 }
496}
497
498void TCPConnection::ConnectSocketSignals(rtc::AsyncPacketSocket* socket) {
499 if (outgoing_) {
500 socket->SignalConnect.connect(this, &TCPConnection::OnConnect);
501 }
502 socket->SignalReadPacket.connect(this, &TCPConnection::OnReadPacket);
503 socket->SignalReadyToSend.connect(this, &TCPConnection::OnReadyToSend);
504 socket->SignalClose.connect(this, &TCPConnection::OnClose);
505}
506
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000507} // namespace cricket