1 /*
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 
11 /*
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  *
32  *         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
58  *  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 
67 #include "webrtc/p2p/base/tcpport.h"
68 
69 #include "webrtc/p2p/base/common.h"
70 #include "webrtc/base/checks.h"
71 #include "webrtc/base/common.h"
72 #include "webrtc/base/logging.h"
73 
74 namespace cricket {
75 
TCPPort(rtc::Thread * thread,rtc::PacketSocketFactory * factory,rtc::Network * network,const rtc::IPAddress & ip,uint16_t min_port,uint16_t max_port,const std::string & username,const std::string & password,bool allow_listen)76 TCPPort::TCPPort(rtc::Thread* thread,
77                  rtc::PacketSocketFactory* factory,
78                  rtc::Network* network,
79                  const rtc::IPAddress& ip,
80                  uint16_t min_port,
81                  uint16_t max_port,
82                  const std::string& username,
83                  const std::string& password,
84                  bool allow_listen)
85     : Port(thread,
86            LOCAL_PORT_TYPE,
87            factory,
88            network,
89            ip,
90            min_port,
91            max_port,
92            username,
93            password),
94       incoming_only_(false),
95       allow_listen_(allow_listen),
96       socket_(NULL),
97       error_(0) {
98   // TODO(mallinath) - Set preference value as per RFC 6544.
99   // http://b/issue?id=7141794
100 }
101 
Init()102 bool TCPPort::Init() {
103   if (allow_listen_) {
104     // Treat failure to create or bind a TCP socket as fatal.  This
105     // should never happen.
106     socket_ = socket_factory()->CreateServerTcpSocket(
107         rtc::SocketAddress(ip(), 0), min_port(), max_port(),
108         false /* ssl */);
109     if (!socket_) {
110       LOG_J(LS_ERROR, this) << "TCP socket creation failed.";
111       return false;
112     }
113     socket_->SignalNewConnection.connect(this, &TCPPort::OnNewConnection);
114     socket_->SignalAddressReady.connect(this, &TCPPort::OnAddressReady);
115   }
116   return true;
117 }
118 
~TCPPort()119 TCPPort::~TCPPort() {
120   delete socket_;
121   std::list<Incoming>::iterator it;
122   for (it = incoming_.begin(); it != incoming_.end(); ++it)
123     delete it->socket;
124   incoming_.clear();
125 }
126 
CreateConnection(const Candidate & address,CandidateOrigin origin)127 Connection* TCPPort::CreateConnection(const Candidate& address,
128                                       CandidateOrigin origin) {
129   if (!SupportsProtocol(address.protocol())) {
130     return NULL;
131   }
132 
133   if (address.tcptype() == TCPTYPE_ACTIVE_STR ||
134       (address.tcptype().empty() && address.address().port() == 0)) {
135     // It's active only candidate, we should not try to create connections
136     // for these candidates.
137     return NULL;
138   }
139 
140   // We can't accept TCP connections incoming on other ports
141   if (origin == ORIGIN_OTHER_PORT)
142     return NULL;
143 
144   // Check if we are allowed to make outgoing TCP connections
145   if (incoming_only_ && (origin == ORIGIN_MESSAGE))
146     return NULL;
147 
148   // We don't know how to act as an ssl server yet
149   if ((address.protocol() == SSLTCP_PROTOCOL_NAME) &&
150       (origin == ORIGIN_THIS_PORT)) {
151     return NULL;
152   }
153 
154   if (!IsCompatibleAddress(address.address())) {
155     return NULL;
156   }
157 
158   TCPConnection* conn = NULL;
159   if (rtc::AsyncPacketSocket* socket =
160       GetIncoming(address.address(), true)) {
161     socket->SignalReadPacket.disconnect(this);
162     conn = new TCPConnection(this, address, socket);
163   } else {
164     conn = new TCPConnection(this, address);
165   }
166   AddOrReplaceConnection(conn);
167   return conn;
168 }
169 
PrepareAddress()170 void TCPPort::PrepareAddress() {
171   if (socket_) {
172     // If socket isn't bound yet the address will be added in
173     // OnAddressReady(). Socket may be in the CLOSED state if Listen()
174     // failed, we still want to add the socket address.
175     LOG(LS_VERBOSE) << "Preparing TCP address, current state: "
176                     << socket_->GetState();
177     if (socket_->GetState() == rtc::AsyncPacketSocket::STATE_BOUND ||
178         socket_->GetState() == rtc::AsyncPacketSocket::STATE_CLOSED)
179       AddAddress(socket_->GetLocalAddress(), socket_->GetLocalAddress(),
180                  rtc::SocketAddress(), TCP_PROTOCOL_NAME, "",
181                  TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE,
182                  ICE_TYPE_PREFERENCE_HOST_TCP, 0, true);
183   } else {
184     LOG_J(LS_INFO, this) << "Not listening due to firewall restrictions.";
185     // Note: We still add the address, since otherwise the remote side won't
186     // recognize our incoming TCP connections. According to
187     // https://tools.ietf.org/html/rfc6544#section-4.5, for active candidate,
188     // the port must be set to the discard port, i.e. 9.
189     AddAddress(rtc::SocketAddress(ip(), DISCARD_PORT),
190                rtc::SocketAddress(ip(), 0), rtc::SocketAddress(),
191                TCP_PROTOCOL_NAME, "", TCPTYPE_ACTIVE_STR, LOCAL_PORT_TYPE,
192                ICE_TYPE_PREFERENCE_HOST_TCP, 0, true);
193   }
194 }
195 
SendTo(const void * data,size_t size,const rtc::SocketAddress & addr,const rtc::PacketOptions & options,bool payload)196 int TCPPort::SendTo(const void* data, size_t size,
197                     const rtc::SocketAddress& addr,
198                     const rtc::PacketOptions& options,
199                     bool payload) {
200   rtc::AsyncPacketSocket * socket = NULL;
201   TCPConnection* conn = static_cast<TCPConnection*>(GetConnection(addr));
202 
203   // For Connection, this is the code path used by Ping() to establish
204   // WRITABLE. It has to send through the socket directly as TCPConnection::Send
205   // checks writability.
206   if (conn) {
207     if (!conn->connected()) {
208       conn->MaybeReconnect();
209       return SOCKET_ERROR;
210     }
211     socket = conn->socket();
212   } else {
213     socket = GetIncoming(addr);
214   }
215   if (!socket) {
216     LOG_J(LS_ERROR, this) << "Attempted to send to an unknown destination, "
217                           << addr.ToSensitiveString();
218     return SOCKET_ERROR;  // TODO(tbd): Set error_
219   }
220 
221   int sent = socket->Send(data, size, options);
222   if (sent < 0) {
223     error_ = socket->GetError();
224     // Error from this code path for a Connection (instead of from a bare
225     // socket) will not trigger reconnecting. In theory, this shouldn't matter
226     // as OnClose should always be called and set connected to false.
227     LOG_J(LS_ERROR, this) << "TCP send of " << size
228                           << " bytes failed with error " << error_;
229   }
230   return sent;
231 }
232 
GetOption(rtc::Socket::Option opt,int * value)233 int TCPPort::GetOption(rtc::Socket::Option opt, int* value) {
234   if (socket_) {
235     return socket_->GetOption(opt, value);
236   } else {
237     return SOCKET_ERROR;
238   }
239 }
240 
SetOption(rtc::Socket::Option opt,int value)241 int TCPPort::SetOption(rtc::Socket::Option opt, int value) {
242   if (socket_) {
243     return socket_->SetOption(opt, value);
244   } else {
245     return SOCKET_ERROR;
246   }
247 }
248 
GetError()249 int TCPPort::GetError() {
250   return error_;
251 }
252 
OnNewConnection(rtc::AsyncPacketSocket * socket,rtc::AsyncPacketSocket * new_socket)253 void TCPPort::OnNewConnection(rtc::AsyncPacketSocket* socket,
254                               rtc::AsyncPacketSocket* new_socket) {
255   RTC_DCHECK(socket == socket_);
256 
257   Incoming incoming;
258   incoming.addr = new_socket->GetRemoteAddress();
259   incoming.socket = new_socket;
260   incoming.socket->SignalReadPacket.connect(this, &TCPPort::OnReadPacket);
261   incoming.socket->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
262   incoming.socket->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
263 
264   LOG_J(LS_VERBOSE, this) << "Accepted connection from "
265                           << incoming.addr.ToSensitiveString();
266   incoming_.push_back(incoming);
267 }
268 
GetIncoming(const rtc::SocketAddress & addr,bool remove)269 rtc::AsyncPacketSocket* TCPPort::GetIncoming(
270     const rtc::SocketAddress& addr, bool remove) {
271   rtc::AsyncPacketSocket* socket = NULL;
272   for (std::list<Incoming>::iterator it = incoming_.begin();
273        it != incoming_.end(); ++it) {
274     if (it->addr == addr) {
275       socket = it->socket;
276       if (remove)
277         incoming_.erase(it);
278       break;
279     }
280   }
281   return socket;
282 }
283 
OnReadPacket(rtc::AsyncPacketSocket * socket,const char * data,size_t size,const rtc::SocketAddress & remote_addr,const rtc::PacketTime & packet_time)284 void TCPPort::OnReadPacket(rtc::AsyncPacketSocket* socket,
285                            const char* data, size_t size,
286                            const rtc::SocketAddress& remote_addr,
287                            const rtc::PacketTime& packet_time) {
288   Port::OnReadPacket(data, size, remote_addr, PROTO_TCP);
289 }
290 
OnSentPacket(rtc::AsyncPacketSocket * socket,const rtc::SentPacket & sent_packet)291 void TCPPort::OnSentPacket(rtc::AsyncPacketSocket* socket,
292                            const rtc::SentPacket& sent_packet) {
293   PortInterface::SignalSentPacket(sent_packet);
294 }
295 
OnReadyToSend(rtc::AsyncPacketSocket * socket)296 void TCPPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
297   Port::OnReadyToSend();
298 }
299 
OnAddressReady(rtc::AsyncPacketSocket * socket,const rtc::SocketAddress & address)300 void TCPPort::OnAddressReady(rtc::AsyncPacketSocket* socket,
301                              const rtc::SocketAddress& address) {
302   AddAddress(address, address, rtc::SocketAddress(), TCP_PROTOCOL_NAME, "",
303              TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP,
304              0, true);
305 }
306 
TCPConnection(TCPPort * port,const Candidate & candidate,rtc::AsyncPacketSocket * socket)307 TCPConnection::TCPConnection(TCPPort* port,
308                              const Candidate& candidate,
309                              rtc::AsyncPacketSocket* socket)
310     : Connection(port, 0, candidate),
311       socket_(socket),
312       error_(0),
313       outgoing_(socket == NULL),
314       connection_pending_(false),
315       pretending_to_be_writable_(false),
316       reconnection_timeout_(cricket::CONNECTION_WRITE_CONNECT_TIMEOUT) {
317   if (outgoing_) {
318     CreateOutgoingTcpSocket();
319   } else {
320     // Incoming connections should match the network address.
321     LOG_J(LS_VERBOSE, this)
322         << "socket ipaddr: " << socket_->GetLocalAddress().ToString()
323         << ",port() ip:" << port->ip().ToString();
324     RTC_DCHECK(socket_->GetLocalAddress().ipaddr() == port->ip());
325     ConnectSocketSignals(socket);
326   }
327 }
328 
~TCPConnection()329 TCPConnection::~TCPConnection() {
330 }
331 
Send(const void * data,size_t size,const rtc::PacketOptions & options)332 int TCPConnection::Send(const void* data, size_t size,
333                         const rtc::PacketOptions& options) {
334   if (!socket_) {
335     error_ = ENOTCONN;
336     return SOCKET_ERROR;
337   }
338 
339   // Sending after OnClose on active side will trigger a reconnect for a
340   // outgoing connection. Note that the write state is still WRITABLE as we want
341   // to spend a few seconds attempting a reconnect before saying we're
342   // unwritable.
343   if (!connected()) {
344     MaybeReconnect();
345     return SOCKET_ERROR;
346   }
347 
348   // Note that this is important to put this after the previous check to give
349   // the connection a chance to reconnect.
350   if (pretending_to_be_writable_ || write_state() != STATE_WRITABLE) {
351     // TODO: Should STATE_WRITE_TIMEOUT return a non-blocking error?
352     error_ = ENOTCONN;
353     return SOCKET_ERROR;
354   }
355   stats_.sent_total_packets++;
356   int sent = socket_->Send(data, size, options);
357   if (sent < 0) {
358     stats_.sent_discarded_packets++;
359     error_ = socket_->GetError();
360   } else {
361     send_rate_tracker_.AddSamples(sent);
362   }
363   return sent;
364 }
365 
GetError()366 int TCPConnection::GetError() {
367   return error_;
368 }
369 
OnConnectionRequestResponse(ConnectionRequest * req,StunMessage * response)370 void TCPConnection::OnConnectionRequestResponse(ConnectionRequest* req,
371                                                 StunMessage* response) {
372   // Process the STUN response before we inform upper layer ready to send.
373   Connection::OnConnectionRequestResponse(req, response);
374 
375   // If we're in the state of pretending to be writeable, we should inform the
376   // upper layer it's ready to send again as previous EWOULDLBLOCK from socket
377   // would have stopped the outgoing stream.
378   if (pretending_to_be_writable_) {
379     Connection::OnReadyToSend();
380   }
381   pretending_to_be_writable_ = false;
382   RTC_DCHECK(write_state() == STATE_WRITABLE);
383 }
384 
OnConnect(rtc::AsyncPacketSocket * socket)385 void TCPConnection::OnConnect(rtc::AsyncPacketSocket* socket) {
386   RTC_DCHECK(socket == socket_.get());
387   // Do not use this connection if the socket bound to a different address than
388   // the one we asked for. This is seen in Chrome, where TCP sockets cannot be
389   // given a binding address, and the platform is expected to pick the
390   // correct local address.
391   const rtc::SocketAddress& socket_addr = socket->GetLocalAddress();
392   if (socket_addr.ipaddr() == port()->ip()) {
393     LOG_J(LS_VERBOSE, this) << "Connection established to "
394                             << socket->GetRemoteAddress().ToSensitiveString();
395   } else if (IPIsAny(port()->ip())) {
396     LOG(LS_WARNING) << "Socket is bound to a different address:"
397                     << socket_addr.ipaddr().ToString()
398                     << ", rather then the local port:"
399                     << port()->ip().ToString()
400                     << ". Still allowing it since it's any address"
401                     << ", possibly caused by multi-routes being disabled.";
402   } else if (socket_addr.IsLoopbackIP()) {
403     LOG(LS_WARNING) << "Socket is bound to a different address:"
404                     << socket_addr.ipaddr().ToString()
405                     << ", rather then the local port:"
406                     << port()->ip().ToString()
407                     << ". Still allowing it since it's localhost.";
408   } else {
409     LOG_J(LS_WARNING, this) << "Dropping connection as TCP socket bound to IP "
410                             << socket_addr.ipaddr().ToSensitiveString()
411                             << ", different from the local candidate IP "
412                             << port()->ip().ToSensitiveString();
413     OnClose(socket, 0);
414     return;
415   }
416 
417   // Connection is established successfully.
418   set_connected(true);
419   connection_pending_ = false;
420 }
421 
OnClose(rtc::AsyncPacketSocket * socket,int error)422 void TCPConnection::OnClose(rtc::AsyncPacketSocket* socket, int error) {
423   RTC_DCHECK(socket == socket_.get());
424   LOG_J(LS_INFO, this) << "Connection closed with error " << error;
425 
426   // Guard against the condition where IPC socket will call OnClose for every
427   // packet it can't send.
428   if (connected()) {
429     set_connected(false);
430 
431     // Prevent the connection from being destroyed by redundant SignalClose
432     // events.
433     pretending_to_be_writable_ = true;
434 
435     // We don't attempt reconnect right here. This is to avoid a case where the
436     // shutdown is intentional and reconnect is not necessary. We only reconnect
437     // when the connection is used to Send() or Ping().
438     port()->thread()->PostDelayed(RTC_FROM_HERE, reconnection_timeout(), this,
439                                   MSG_TCPCONNECTION_DELAYED_ONCLOSE);
440   } else if (!pretending_to_be_writable_) {
441     // OnClose could be called when the underneath socket times out during the
442     // initial connect() (i.e. |pretending_to_be_writable_| is false) . We have
443     // to manually destroy here as this connection, as never connected, will not
444     // be scheduled for ping to trigger destroy.
445     Destroy();
446   }
447 }
448 
OnMessage(rtc::Message * pmsg)449 void TCPConnection::OnMessage(rtc::Message* pmsg) {
450   switch (pmsg->message_id) {
451     case MSG_TCPCONNECTION_DELAYED_ONCLOSE:
452       // If this connection can't become connected and writable again in 5
453       // seconds, it's time to tear this down. This is the case for the original
454       // TCP connection on passive side during a reconnect.
455       if (pretending_to_be_writable_) {
456         Destroy();
457       }
458       break;
459     default:
460       Connection::OnMessage(pmsg);
461   }
462 }
463 
MaybeReconnect()464 void TCPConnection::MaybeReconnect() {
465   // Only reconnect for an outgoing TCPConnection when OnClose was signaled and
466   // no outstanding reconnect is pending.
467   if (connected() || connection_pending_ || !outgoing_) {
468     return;
469   }
470 
471   LOG_J(LS_INFO, this) << "TCP Connection with remote is closed, "
472                        << "trying to reconnect";
473 
474   CreateOutgoingTcpSocket();
475   error_ = EPIPE;
476 }
477 
OnReadPacket(rtc::AsyncPacketSocket * socket,const char * data,size_t size,const rtc::SocketAddress & remote_addr,const rtc::PacketTime & packet_time)478 void TCPConnection::OnReadPacket(
479   rtc::AsyncPacketSocket* socket, const char* data, size_t size,
480   const rtc::SocketAddress& remote_addr,
481   const rtc::PacketTime& packet_time) {
482   RTC_DCHECK(socket == socket_.get());
483   Connection::OnReadPacket(data, size, packet_time);
484 }
485 
OnReadyToSend(rtc::AsyncPacketSocket * socket)486 void TCPConnection::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
487   RTC_DCHECK(socket == socket_.get());
488   Connection::OnReadyToSend();
489 }
490 
CreateOutgoingTcpSocket()491 void TCPConnection::CreateOutgoingTcpSocket() {
492   RTC_DCHECK(outgoing_);
493   // TODO(guoweis): Handle failures here (unlikely since TCP).
494   int opts = (remote_candidate().protocol() == SSLTCP_PROTOCOL_NAME)
495                  ? rtc::PacketSocketFactory::OPT_TLS_FAKE
496                  : 0;
497   socket_.reset(port()->socket_factory()->CreateClientTcpSocket(
498       rtc::SocketAddress(port()->ip(), 0), remote_candidate().address(),
499       port()->proxy(), port()->user_agent(), opts));
500   if (socket_) {
501     LOG_J(LS_VERBOSE, this)
502         << "Connecting from " << socket_->GetLocalAddress().ToSensitiveString()
503         << " to " << remote_candidate().address().ToSensitiveString();
504     set_connected(false);
505     connection_pending_ = true;
506     ConnectSocketSignals(socket_.get());
507   } else {
508     LOG_J(LS_WARNING, this) << "Failed to create connection to "
509                             << remote_candidate().address().ToSensitiveString();
510   }
511 }
512 
ConnectSocketSignals(rtc::AsyncPacketSocket * socket)513 void TCPConnection::ConnectSocketSignals(rtc::AsyncPacketSocket* socket) {
514   if (outgoing_) {
515     socket->SignalConnect.connect(this, &TCPConnection::OnConnect);
516   }
517   socket->SignalReadPacket.connect(this, &TCPConnection::OnReadPacket);
518   socket->SignalReadyToSend.connect(this, &TCPConnection::OnReadyToSend);
519   socket->SignalClose.connect(this, &TCPConnection::OnClose);
520 }
521 
522 }  // namespace cricket
523