blob: b780a1e52759f267717d3158c035da93904f7b9f [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020067#include "p2p/base/tcpport.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000068
Steve Anton6c38cc72017-11-29 10:25:58 -080069#include <vector>
70
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020071#include "p2p/base/common.h"
72#include "rtc_base/checks.h"
73#include "rtc_base/logging.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000074
75namespace cricket {
76
77TCPPort::TCPPort(rtc::Thread* thread,
78 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +000079 rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +020080 uint16_t min_port,
81 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +000082 const std::string& username,
83 const std::string& password,
84 bool allow_listen)
Peter Boström0c4e06b2015-10-07 12:23:21 +020085 : Port(thread,
86 LOCAL_PORT_TYPE,
87 factory,
88 network,
Peter Boström0c4e06b2015-10-07 12:23:21 +020089 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
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000099 if (allow_listen_) {
deadbeef1ee21252017-06-13 15:49:45 -0700100 TryCreateServerSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000101 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000102}
103
104TCPPort::~TCPPort() {
105 delete socket_;
106 std::list<Incoming>::iterator it;
107 for (it = incoming_.begin(); it != incoming_.end(); ++it)
108 delete it->socket;
109 incoming_.clear();
110}
111
112Connection* TCPPort::CreateConnection(const Candidate& address,
113 CandidateOrigin origin) {
Honghai Zhangf9945b22015-12-15 12:20:13 -0800114 if (!SupportsProtocol(address.protocol())) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000115 return NULL;
116 }
117
118 if (address.tcptype() == TCPTYPE_ACTIVE_STR ||
119 (address.tcptype().empty() && address.address().port() == 0)) {
120 // It's active only candidate, we should not try to create connections
121 // for these candidates.
122 return NULL;
123 }
124
125 // We can't accept TCP connections incoming on other ports
126 if (origin == ORIGIN_OTHER_PORT)
127 return NULL;
128
129 // Check if we are allowed to make outgoing TCP connections
130 if (incoming_only_ && (origin == ORIGIN_MESSAGE))
131 return NULL;
132
133 // We don't know how to act as an ssl server yet
134 if ((address.protocol() == SSLTCP_PROTOCOL_NAME) &&
135 (origin == ORIGIN_THIS_PORT)) {
136 return NULL;
137 }
138
139 if (!IsCompatibleAddress(address.address())) {
140 return NULL;
141 }
142
143 TCPConnection* conn = NULL;
144 if (rtc::AsyncPacketSocket* socket =
145 GetIncoming(address.address(), true)) {
deadbeef06878292017-04-21 14:22:23 -0700146 // Incoming connection; we already created a socket and connected signals,
147 // so we need to hand off the "read packet" responsibility to
148 // TCPConnection.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000149 socket->SignalReadPacket.disconnect(this);
150 conn = new TCPConnection(this, address, socket);
151 } else {
deadbeef06878292017-04-21 14:22:23 -0700152 // Outgoing connection, which will create a new socket for which we still
153 // need to connect SignalReadyToSend and SignalSentPacket.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000154 conn = new TCPConnection(this, address);
deadbeef06878292017-04-21 14:22:23 -0700155 if (conn->socket()) {
156 conn->socket()->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
157 conn->socket()->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
158 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000159 }
honghaiz36f50e82016-06-01 15:57:03 -0700160 AddOrReplaceConnection(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000161 return conn;
162}
163
164void TCPPort::PrepareAddress() {
165 if (socket_) {
166 // If socket isn't bound yet the address will be added in
167 // OnAddressReady(). Socket may be in the CLOSED state if Listen()
168 // failed, we still want to add the socket address.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100169 RTC_LOG(LS_VERBOSE) << "Preparing TCP address, current state: "
170 << socket_->GetState();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000171 if (socket_->GetState() == rtc::AsyncPacketSocket::STATE_BOUND ||
172 socket_->GetState() == rtc::AsyncPacketSocket::STATE_CLOSED)
173 AddAddress(socket_->GetLocalAddress(), socket_->GetLocalAddress(),
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700174 rtc::SocketAddress(), TCP_PROTOCOL_NAME, "",
175 TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE,
zhihuang26d99c22017-02-13 12:47:27 -0800176 ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000177 } else {
178 LOG_J(LS_INFO, this) << "Not listening due to firewall restrictions.";
179 // Note: We still add the address, since otherwise the remote side won't
Guo-wei Shieh310b0932015-11-17 19:15:50 -0800180 // recognize our incoming TCP connections. According to
181 // https://tools.ietf.org/html/rfc6544#section-4.5, for active candidate,
deadbeef5c3c1042017-08-04 15:01:57 -0700182 // the port must be set to the discard port, i.e. 9. We can't be 100% sure
183 // which IP address will actually be used, so GetBestIP is as good as we
184 // can do.
185 // TODO(deadbeef): We could do something like create a dummy socket just to
186 // see what IP we get. But that may be overkill.
187 AddAddress(rtc::SocketAddress(Network()->GetBestIP(), DISCARD_PORT),
188 rtc::SocketAddress(Network()->GetBestIP(), 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
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700251bool TCPPort::SupportsProtocol(const std::string& protocol) const {
252 return protocol == TCP_PROTOCOL_NAME || protocol == SSLTCP_PROTOCOL_NAME;
253}
254
255ProtocolType TCPPort::GetProtocol() const {
256 return PROTO_TCP;
257}
258
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000259void TCPPort::OnNewConnection(rtc::AsyncPacketSocket* socket,
260 rtc::AsyncPacketSocket* new_socket) {
nisseede5da42017-01-12 05:15:36 -0800261 RTC_DCHECK(socket == socket_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000262
263 Incoming incoming;
264 incoming.addr = new_socket->GetRemoteAddress();
265 incoming.socket = new_socket;
266 incoming.socket->SignalReadPacket.connect(this, &TCPPort::OnReadPacket);
267 incoming.socket->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
Stefan Holmer55674ff2016-01-14 15:49:16 +0100268 incoming.socket->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000269
270 LOG_J(LS_VERBOSE, this) << "Accepted connection from "
271 << incoming.addr.ToSensitiveString();
272 incoming_.push_back(incoming);
273}
274
deadbeef1ee21252017-06-13 15:49:45 -0700275void TCPPort::TryCreateServerSocket() {
276 socket_ = socket_factory()->CreateServerTcpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -0700277 rtc::SocketAddress(Network()->GetBestIP(), 0), min_port(), max_port(),
278 false /* ssl */);
deadbeef1ee21252017-06-13 15:49:45 -0700279 if (!socket_) {
280 LOG_J(LS_WARNING, this)
281 << "TCP server socket creation failed; continuing anyway.";
282 return;
283 }
284 socket_->SignalNewConnection.connect(this, &TCPPort::OnNewConnection);
285 socket_->SignalAddressReady.connect(this, &TCPPort::OnAddressReady);
286}
287
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000288rtc::AsyncPacketSocket* TCPPort::GetIncoming(
289 const rtc::SocketAddress& addr, bool remove) {
290 rtc::AsyncPacketSocket* socket = NULL;
291 for (std::list<Incoming>::iterator it = incoming_.begin();
292 it != incoming_.end(); ++it) {
293 if (it->addr == addr) {
294 socket = it->socket;
295 if (remove)
296 incoming_.erase(it);
297 break;
298 }
299 }
300 return socket;
301}
302
303void TCPPort::OnReadPacket(rtc::AsyncPacketSocket* socket,
304 const char* data, size_t size,
305 const rtc::SocketAddress& remote_addr,
306 const rtc::PacketTime& packet_time) {
307 Port::OnReadPacket(data, size, remote_addr, PROTO_TCP);
308}
309
Stefan Holmer55674ff2016-01-14 15:49:16 +0100310void TCPPort::OnSentPacket(rtc::AsyncPacketSocket* socket,
311 const rtc::SentPacket& sent_packet) {
Stefan Holmer55674ff2016-01-14 15:49:16 +0100312 PortInterface::SignalSentPacket(sent_packet);
313}
314
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000315void TCPPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
316 Port::OnReadyToSend();
317}
318
319void TCPPort::OnAddressReady(rtc::AsyncPacketSocket* socket,
320 const rtc::SocketAddress& address) {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700321 AddAddress(address, address, rtc::SocketAddress(), TCP_PROTOCOL_NAME, "",
322 TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP,
zhihuang26d99c22017-02-13 12:47:27 -0800323 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000324}
325
Qingsi Wang22e623a2018-03-13 10:53:57 -0700326// TODO(qingsi): |CONNECTION_WRITE_CONNECT_TIMEOUT| is overriden by
327// |ice_unwritable_timeout| in IceConfig when determining the writability state.
328// Replace this constant with the config parameter assuming the default value if
329// we decide it is also applicable here.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700330TCPConnection::TCPConnection(TCPPort* port,
331 const Candidate& candidate,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000332 rtc::AsyncPacketSocket* socket)
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700333 : Connection(port, 0, candidate),
334 socket_(socket),
335 error_(0),
336 outgoing_(socket == NULL),
337 connection_pending_(false),
338 pretending_to_be_writable_(false),
339 reconnection_timeout_(cricket::CONNECTION_WRITE_CONNECT_TIMEOUT) {
340 if (outgoing_) {
341 CreateOutgoingTcpSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000342 } else {
deadbeef5c3c1042017-08-04 15:01:57 -0700343 // Incoming connections should match one of the network addresses. Same as
344 // what's being checked in OnConnect, but just DCHECKing here.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700345 LOG_J(LS_VERBOSE, this)
346 << "socket ipaddr: " << socket_->GetLocalAddress().ToString()
deadbeef5c3c1042017-08-04 15:01:57 -0700347 << ", port() Network:" << port->Network()->ToString();
348 const std::vector<rtc::InterfaceAddress>& desired_addresses =
349 port_->Network()->GetIPs();
350 RTC_DCHECK(std::find(desired_addresses.begin(), desired_addresses.end(),
351 socket_->GetLocalAddress().ipaddr()) !=
352 desired_addresses.end());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700353 ConnectSocketSignals(socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000354 }
355}
356
357TCPConnection::~TCPConnection() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000358}
359
360int TCPConnection::Send(const void* data, size_t size,
361 const rtc::PacketOptions& options) {
362 if (!socket_) {
363 error_ = ENOTCONN;
364 return SOCKET_ERROR;
365 }
366
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700367 // Sending after OnClose on active side will trigger a reconnect for a
368 // outgoing connection. Note that the write state is still WRITABLE as we want
369 // to spend a few seconds attempting a reconnect before saying we're
370 // unwritable.
371 if (!connected()) {
372 MaybeReconnect();
373 return SOCKET_ERROR;
374 }
375
376 // Note that this is important to put this after the previous check to give
377 // the connection a chance to reconnect.
378 if (pretending_to_be_writable_ || write_state() != STATE_WRITABLE) {
Steve Anton6c38cc72017-11-29 10:25:58 -0800379 // TODO(?): Should STATE_WRITE_TIMEOUT return a non-blocking error?
skvladc309e0e2016-07-28 17:15:20 -0700380 error_ = ENOTCONN;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000381 return SOCKET_ERROR;
382 }
zhihuang5ecf16c2016-06-01 17:09:15 -0700383 stats_.sent_total_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000384 int sent = socket_->Send(data, size, options);
385 if (sent < 0) {
zhihuang5ecf16c2016-06-01 17:09:15 -0700386 stats_.sent_discarded_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000387 error_ = socket_->GetError();
388 } else {
Tim Psiaki63046262015-09-14 10:38:08 -0700389 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000390 }
391 return sent;
392}
393
394int TCPConnection::GetError() {
395 return error_;
396}
397
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700398void TCPConnection::OnConnectionRequestResponse(ConnectionRequest* req,
399 StunMessage* response) {
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700400 // Process the STUN response before we inform upper layer ready to send.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700401 Connection::OnConnectionRequestResponse(req, response);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700402
403 // If we're in the state of pretending to be writeable, we should inform the
404 // upper layer it's ready to send again as previous EWOULDLBLOCK from socket
405 // would have stopped the outgoing stream.
406 if (pretending_to_be_writable_) {
407 Connection::OnReadyToSend();
408 }
409 pretending_to_be_writable_ = false;
nisseede5da42017-01-12 05:15:36 -0800410 RTC_DCHECK(write_state() == STATE_WRITABLE);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700411}
412
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000413void TCPConnection::OnConnect(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800414 RTC_DCHECK(socket == socket_.get());
deadbeef5c3c1042017-08-04 15:01:57 -0700415 // Do not use this port if the socket bound to an address not associated with
416 // the desired network interface. This is seen in Chrome, where TCP sockets
417 // cannot be given a binding address, and the platform is expected to pick
418 // the correct local address.
419 //
420 // However, there are two situations in which we allow the bound address to
421 // not be one of the addresses of the requested interface:
422 // 1. The bound address is the loopback address. This happens when a proxy
423 // forces TCP to bind to only the localhost address (see issue 3927).
424 // 2. The bound address is the "any address". This happens when
425 // multiple_routes is disabled (see issue 4780).
426 //
427 // Note that, aside from minor differences in log statements, this logic is
428 // identical to that in TurnPort.
429 const rtc::SocketAddress& socket_address = socket->GetLocalAddress();
430 const std::vector<rtc::InterfaceAddress>& desired_addresses =
431 port_->Network()->GetIPs();
432 if (std::find(desired_addresses.begin(), desired_addresses.end(),
433 socket_address.ipaddr()) != desired_addresses.end()) {
tommi5ce1a2a2016-05-14 03:19:31 -0700434 LOG_J(LS_VERBOSE, this) << "Connection established to "
435 << socket->GetRemoteAddress().ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000436 } else {
deadbeef5c3c1042017-08-04 15:01:57 -0700437 if (socket->GetLocalAddress().IsLoopbackIP()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100438 RTC_LOG(LS_WARNING) << "Socket is bound to the address:"
439 << socket_address.ipaddr().ToString()
Taylor Brandstetter3ba7a572018-03-02 10:58:25 -0800440 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100441 << port_->Network()->ToString()
442 << ". Still allowing it since it's localhost.";
deadbeef5c3c1042017-08-04 15:01:57 -0700443 } else if (IPIsAny(port_->Network()->GetBestIP())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100444 RTC_LOG(LS_WARNING)
445 << "Socket is bound to the address:"
446 << socket_address.ipaddr().ToString()
Taylor Brandstetter3ba7a572018-03-02 10:58:25 -0800447 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100448 << port_->Network()->ToString()
449 << ". Still allowing it since it's the 'any' address"
450 << ", possibly caused by multiple_routes being disabled.";
deadbeef5c3c1042017-08-04 15:01:57 -0700451 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100452 RTC_LOG(LS_WARNING) << "Dropping connection as TCP socket bound to IP "
453 << socket_address.ipaddr().ToString()
Taylor Brandstetter3ba7a572018-03-02 10:58:25 -0800454 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100455 << port_->Network()->ToString();
deadbeef5c3c1042017-08-04 15:01:57 -0700456 OnClose(socket, 0);
457 return;
458 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000459 }
tommi5ce1a2a2016-05-14 03:19:31 -0700460
461 // Connection is established successfully.
462 set_connected(true);
463 connection_pending_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000464}
465
466void TCPConnection::OnClose(rtc::AsyncPacketSocket* socket, int error) {
nisseede5da42017-01-12 05:15:36 -0800467 RTC_DCHECK(socket == socket_.get());
henrike@webrtc.org43e033e2014-11-10 19:40:29 +0000468 LOG_J(LS_INFO, this) << "Connection closed with error " << error;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700469
470 // Guard against the condition where IPC socket will call OnClose for every
471 // packet it can't send.
472 if (connected()) {
473 set_connected(false);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700474
475 // Prevent the connection from being destroyed by redundant SignalClose
476 // events.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700477 pretending_to_be_writable_ = true;
478
479 // We don't attempt reconnect right here. This is to avoid a case where the
480 // shutdown is intentional and reconnect is not necessary. We only reconnect
481 // when the connection is used to Send() or Ping().
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700482 port()->thread()->PostDelayed(RTC_FROM_HERE, reconnection_timeout(), this,
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700483 MSG_TCPCONNECTION_DELAYED_ONCLOSE);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700484 } else if (!pretending_to_be_writable_) {
485 // OnClose could be called when the underneath socket times out during the
486 // initial connect() (i.e. |pretending_to_be_writable_| is false) . We have
487 // to manually destroy here as this connection, as never connected, will not
488 // be scheduled for ping to trigger destroy.
489 Destroy();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700490 }
491}
492
493void TCPConnection::OnMessage(rtc::Message* pmsg) {
494 switch (pmsg->message_id) {
495 case MSG_TCPCONNECTION_DELAYED_ONCLOSE:
496 // If this connection can't become connected and writable again in 5
497 // seconds, it's time to tear this down. This is the case for the original
498 // TCP connection on passive side during a reconnect.
499 if (pretending_to_be_writable_) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700500 Destroy();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700501 }
502 break;
503 default:
504 Connection::OnMessage(pmsg);
505 }
506}
507
508void TCPConnection::MaybeReconnect() {
509 // Only reconnect for an outgoing TCPConnection when OnClose was signaled and
510 // no outstanding reconnect is pending.
511 if (connected() || connection_pending_ || !outgoing_) {
512 return;
513 }
514
515 LOG_J(LS_INFO, this) << "TCP Connection with remote is closed, "
516 << "trying to reconnect";
517
518 CreateOutgoingTcpSocket();
519 error_ = EPIPE;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000520}
521
522void TCPConnection::OnReadPacket(
523 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
524 const rtc::SocketAddress& remote_addr,
525 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -0800526 RTC_DCHECK(socket == socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000527 Connection::OnReadPacket(data, size, packet_time);
528}
529
530void TCPConnection::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800531 RTC_DCHECK(socket == socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000532 Connection::OnReadyToSend();
533}
534
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700535void TCPConnection::CreateOutgoingTcpSocket() {
nisseede5da42017-01-12 05:15:36 -0800536 RTC_DCHECK(outgoing_);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700537 // TODO(guoweis): Handle failures here (unlikely since TCP).
538 int opts = (remote_candidate().protocol() == SSLTCP_PROTOCOL_NAME)
hnsl04833622017-01-09 08:35:45 -0800539 ? rtc::PacketSocketFactory::OPT_TLS_FAKE
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700540 : 0;
541 socket_.reset(port()->socket_factory()->CreateClientTcpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -0700542 rtc::SocketAddress(port()->Network()->GetBestIP(), 0),
543 remote_candidate().address(), port()->proxy(), port()->user_agent(),
544 opts));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700545 if (socket_) {
546 LOG_J(LS_VERBOSE, this)
547 << "Connecting from " << socket_->GetLocalAddress().ToSensitiveString()
548 << " to " << remote_candidate().address().ToSensitiveString();
549 set_connected(false);
550 connection_pending_ = true;
551 ConnectSocketSignals(socket_.get());
552 } else {
553 LOG_J(LS_WARNING, this) << "Failed to create connection to "
554 << remote_candidate().address().ToSensitiveString();
555 }
556}
557
558void TCPConnection::ConnectSocketSignals(rtc::AsyncPacketSocket* socket) {
559 if (outgoing_) {
560 socket->SignalConnect.connect(this, &TCPConnection::OnConnect);
561 }
562 socket->SignalReadPacket.connect(this, &TCPConnection::OnReadPacket);
563 socket->SignalReadyToSend.connect(this, &TCPConnection::OnReadyToSend);
564 socket->SignalClose.connect(this, &TCPConnection::OnClose);
565}
566
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000567} // namespace cricket