blob: f98322a9d934a6b92cb8852a1c3266ebae3ba3f3 [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:111/*
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 19:48:4711/*
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 18:02:5532 * 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 19:48:4758 * 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
Steve Anton10542f22019-01-11 17:11:0067#include "p2p/base/tcp_port.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:1168
Yves Gerey3e707812018-11-28 15:47:4969#include <errno.h>
Steve Anton6c38cc72017-11-29 18:25:5870#include <vector>
71
Steve Antonae226f62019-01-29 20:47:3872#include "absl/algorithm/container.h"
Steve Anton10542f22019-01-11 17:11:0073#include "p2p/base/p2p_constants.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3174#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 17:11:0075#include "rtc_base/ip_address.h"
Yves Gerey3e707812018-11-28 15:47:4976#include "rtc_base/location.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3177#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 17:11:0078#include "rtc_base/net_helper.h"
79#include "rtc_base/rate_tracker.h"
Yves Gerey3e707812018-11-28 15:47:4980#include "rtc_base/third_party/sigslot/sigslot.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:1181
82namespace cricket {
83
84TCPPort::TCPPort(rtc::Thread* thread,
85 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:2286 rtc::Network* network,
Peter Boström0c4e06b2015-10-07 10:23:2187 uint16_t min_port,
88 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:2289 const std::string& username,
90 const std::string& password,
91 bool allow_listen)
Peter Boström0c4e06b2015-10-07 10:23:2192 : Port(thread,
93 LOCAL_PORT_TYPE,
94 factory,
95 network,
Peter Boström0c4e06b2015-10-07 10:23:2196 min_port,
97 max_port,
98 username,
99 password),
henrike@webrtc.org269fb4b2014-10-28 22:20:11100 incoming_only_(false),
101 allow_listen_(allow_listen),
102 socket_(NULL),
103 error_(0) {
104 // TODO(mallinath) - Set preference value as per RFC 6544.
105 // http://b/issue?id=7141794
henrike@webrtc.org269fb4b2014-10-28 22:20:11106 if (allow_listen_) {
deadbeef1ee21252017-06-13 22:49:45107 TryCreateServerSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11108 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11109}
110
111TCPPort::~TCPPort() {
112 delete socket_;
113 std::list<Incoming>::iterator it;
114 for (it = incoming_.begin(); it != incoming_.end(); ++it)
115 delete it->socket;
116 incoming_.clear();
117}
118
119Connection* TCPPort::CreateConnection(const Candidate& address,
120 CandidateOrigin origin) {
Honghai Zhangf9945b22015-12-15 20:20:13121 if (!SupportsProtocol(address.protocol())) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11122 return NULL;
123 }
124
125 if (address.tcptype() == TCPTYPE_ACTIVE_STR ||
126 (address.tcptype().empty() && address.address().port() == 0)) {
127 // It's active only candidate, we should not try to create connections
128 // for these candidates.
129 return NULL;
130 }
131
132 // We can't accept TCP connections incoming on other ports
133 if (origin == ORIGIN_OTHER_PORT)
134 return NULL;
135
136 // Check if we are allowed to make outgoing TCP connections
137 if (incoming_only_ && (origin == ORIGIN_MESSAGE))
138 return NULL;
139
140 // We don't know how to act as an ssl server yet
141 if ((address.protocol() == SSLTCP_PROTOCOL_NAME) &&
142 (origin == ORIGIN_THIS_PORT)) {
143 return NULL;
144 }
145
146 if (!IsCompatibleAddress(address.address())) {
147 return NULL;
148 }
149
150 TCPConnection* conn = NULL;
Yves Gerey665174f2018-06-19 13:03:05151 if (rtc::AsyncPacketSocket* socket = GetIncoming(address.address(), true)) {
deadbeef06878292017-04-21 21:22:23152 // Incoming connection; we already created a socket and connected signals,
153 // so we need to hand off the "read packet" responsibility to
154 // TCPConnection.
henrike@webrtc.org269fb4b2014-10-28 22:20:11155 socket->SignalReadPacket.disconnect(this);
156 conn = new TCPConnection(this, address, socket);
157 } else {
deadbeef06878292017-04-21 21:22:23158 // Outgoing connection, which will create a new socket for which we still
159 // need to connect SignalReadyToSend and SignalSentPacket.
henrike@webrtc.org269fb4b2014-10-28 22:20:11160 conn = new TCPConnection(this, address);
deadbeef06878292017-04-21 21:22:23161 if (conn->socket()) {
162 conn->socket()->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
163 conn->socket()->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
164 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11165 }
honghaiz36f50e82016-06-01 22:57:03166 AddOrReplaceConnection(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11167 return conn;
168}
169
170void 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.
Mirko Bonadei675513b2017-11-09 10:09:25175 RTC_LOG(LS_VERBOSE) << "Preparing TCP address, current state: "
176 << socket_->GetState();
henrike@webrtc.org269fb4b2014-10-28 22:20:11177 if (socket_->GetState() == rtc::AsyncPacketSocket::STATE_BOUND ||
178 socket_->GetState() == rtc::AsyncPacketSocket::STATE_CLOSED)
179 AddAddress(socket_->GetLocalAddress(), socket_->GetLocalAddress(),
Guo-wei Shieh3d564c12015-08-19 23:51:15180 rtc::SocketAddress(), TCP_PROTOCOL_NAME, "",
181 TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE,
zhihuang26d99c22017-02-13 20:47:27182 ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11183 } else {
Jonas Olssond7d762d2018-03-28 07:47:51184 RTC_LOG(LS_INFO) << ToString()
185 << ": Not listening due to firewall restrictions.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11186 // Note: We still add the address, since otherwise the remote side won't
Guo-wei Shieh310b0932015-11-18 03:15:50187 // recognize our incoming TCP connections. According to
188 // https://tools.ietf.org/html/rfc6544#section-4.5, for active candidate,
deadbeef5c3c1042017-08-04 22:01:57189 // the port must be set to the discard port, i.e. 9. We can't be 100% sure
190 // which IP address will actually be used, so GetBestIP is as good as we
191 // can do.
192 // TODO(deadbeef): We could do something like create a dummy socket just to
193 // see what IP we get. But that may be overkill.
194 AddAddress(rtc::SocketAddress(Network()->GetBestIP(), DISCARD_PORT),
195 rtc::SocketAddress(Network()->GetBestIP(), 0),
196 rtc::SocketAddress(), TCP_PROTOCOL_NAME, "", TCPTYPE_ACTIVE_STR,
197 LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11198 }
199}
200
Yves Gerey665174f2018-06-19 13:03:05201int TCPPort::SendTo(const void* data,
202 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11203 const rtc::SocketAddress& addr,
204 const rtc::PacketOptions& options,
205 bool payload) {
Yves Gerey665174f2018-06-19 13:03:05206 rtc::AsyncPacketSocket* socket = NULL;
Guo-wei Shiehbe508a12015-04-06 19:48:47207 TCPConnection* conn = static_cast<TCPConnection*>(GetConnection(addr));
208
209 // For Connection, this is the code path used by Ping() to establish
210 // WRITABLE. It has to send through the socket directly as TCPConnection::Send
211 // checks writability.
212 if (conn) {
213 if (!conn->connected()) {
214 conn->MaybeReconnect();
215 return SOCKET_ERROR;
216 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11217 socket = conn->socket();
218 } else {
219 socket = GetIncoming(addr);
220 }
221 if (!socket) {
Jonas Olssond7d762d2018-03-28 07:47:51222 RTC_LOG(LS_ERROR) << ToString()
223 << ": Attempted to send to an unknown destination: "
224 << addr.ToSensitiveString();
Guo-wei Shiehbe508a12015-04-06 19:48:47225 return SOCKET_ERROR; // TODO(tbd): Set error_
henrike@webrtc.org269fb4b2014-10-28 22:20:11226 }
Qingsi Wang6e641e62018-04-12 03:14:17227 rtc::PacketOptions modified_options(options);
228 CopyPortInformationToPacketInfo(&modified_options.info_signaled_after_sent);
229 int sent = socket->Send(data, size, modified_options);
henrike@webrtc.org269fb4b2014-10-28 22:20:11230 if (sent < 0) {
231 error_ = socket->GetError();
Guo-wei Shiehbe508a12015-04-06 19:48:47232 // Error from this code path for a Connection (instead of from a bare
233 // socket) will not trigger reconnecting. In theory, this shouldn't matter
234 // as OnClose should always be called and set connected to false.
Yves Gerey665174f2018-06-19 13:03:05235 RTC_LOG(LS_ERROR) << ToString() << ": TCP send of " << size
236 << " bytes failed with error " << error_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11237 }
238 return sent;
239}
240
241int TCPPort::GetOption(rtc::Socket::Option opt, int* value) {
242 if (socket_) {
243 return socket_->GetOption(opt, value);
244 } else {
245 return SOCKET_ERROR;
246 }
247}
248
249int TCPPort::SetOption(rtc::Socket::Option opt, int value) {
250 if (socket_) {
251 return socket_->SetOption(opt, value);
252 } else {
253 return SOCKET_ERROR;
254 }
255}
256
257int TCPPort::GetError() {
258 return error_;
259}
260
Steve Anton1cf1b7d2017-10-30 17:00:15261bool TCPPort::SupportsProtocol(const std::string& protocol) const {
262 return protocol == TCP_PROTOCOL_NAME || protocol == SSLTCP_PROTOCOL_NAME;
263}
264
265ProtocolType TCPPort::GetProtocol() const {
266 return PROTO_TCP;
267}
268
henrike@webrtc.org269fb4b2014-10-28 22:20:11269void TCPPort::OnNewConnection(rtc::AsyncPacketSocket* socket,
270 rtc::AsyncPacketSocket* new_socket) {
nisseede5da42017-01-12 13:15:36271 RTC_DCHECK(socket == socket_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11272
273 Incoming incoming;
274 incoming.addr = new_socket->GetRemoteAddress();
275 incoming.socket = new_socket;
276 incoming.socket->SignalReadPacket.connect(this, &TCPPort::OnReadPacket);
277 incoming.socket->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
Stefan Holmer55674ff2016-01-14 14:49:16278 incoming.socket->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11279
Yves Gerey665174f2018-06-19 13:03:05280 RTC_LOG(LS_VERBOSE) << ToString() << ": Accepted connection from "
Jonas Olssond7d762d2018-03-28 07:47:51281 << incoming.addr.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11282 incoming_.push_back(incoming);
283}
284
deadbeef1ee21252017-06-13 22:49:45285void TCPPort::TryCreateServerSocket() {
286 socket_ = socket_factory()->CreateServerTcpSocket(
deadbeef5c3c1042017-08-04 22:01:57287 rtc::SocketAddress(Network()->GetBestIP(), 0), min_port(), max_port(),
288 false /* ssl */);
deadbeef1ee21252017-06-13 22:49:45289 if (!socket_) {
Jonas Olssond7d762d2018-03-28 07:47:51290 RTC_LOG(LS_WARNING)
291 << ToString()
292 << ": TCP server socket creation failed; continuing anyway.";
deadbeef1ee21252017-06-13 22:49:45293 return;
294 }
295 socket_->SignalNewConnection.connect(this, &TCPPort::OnNewConnection);
296 socket_->SignalAddressReady.connect(this, &TCPPort::OnAddressReady);
297}
298
Yves Gerey665174f2018-06-19 13:03:05299rtc::AsyncPacketSocket* TCPPort::GetIncoming(const rtc::SocketAddress& addr,
300 bool remove) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11301 rtc::AsyncPacketSocket* socket = NULL;
302 for (std::list<Incoming>::iterator it = incoming_.begin();
303 it != incoming_.end(); ++it) {
304 if (it->addr == addr) {
305 socket = it->socket;
306 if (remove)
307 incoming_.erase(it);
308 break;
309 }
310 }
311 return socket;
312}
313
314void TCPPort::OnReadPacket(rtc::AsyncPacketSocket* socket,
Yves Gerey665174f2018-06-19 13:03:05315 const char* data,
316 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11317 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 12:01:41318 const int64_t& packet_time_us) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11319 Port::OnReadPacket(data, size, remote_addr, PROTO_TCP);
320}
321
Stefan Holmer55674ff2016-01-14 14:49:16322void TCPPort::OnSentPacket(rtc::AsyncPacketSocket* socket,
323 const rtc::SentPacket& sent_packet) {
Stefan Holmer55674ff2016-01-14 14:49:16324 PortInterface::SignalSentPacket(sent_packet);
325}
326
henrike@webrtc.org269fb4b2014-10-28 22:20:11327void TCPPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
328 Port::OnReadyToSend();
329}
330
331void TCPPort::OnAddressReady(rtc::AsyncPacketSocket* socket,
332 const rtc::SocketAddress& address) {
Guo-wei Shieh3d564c12015-08-19 23:51:15333 AddAddress(address, address, rtc::SocketAddress(), TCP_PROTOCOL_NAME, "",
334 TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP,
zhihuang26d99c22017-02-13 20:47:27335 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11336}
337
Qingsi Wang22e623a2018-03-13 17:53:57338// TODO(qingsi): |CONNECTION_WRITE_CONNECT_TIMEOUT| is overriden by
339// |ice_unwritable_timeout| in IceConfig when determining the writability state.
340// Replace this constant with the config parameter assuming the default value if
341// we decide it is also applicable here.
Guo-wei Shiehbe508a12015-04-06 19:48:47342TCPConnection::TCPConnection(TCPPort* port,
343 const Candidate& candidate,
henrike@webrtc.org269fb4b2014-10-28 22:20:11344 rtc::AsyncPacketSocket* socket)
Guo-wei Shiehbe508a12015-04-06 19:48:47345 : Connection(port, 0, candidate),
346 socket_(socket),
347 error_(0),
348 outgoing_(socket == NULL),
349 connection_pending_(false),
350 pretending_to_be_writable_(false),
351 reconnection_timeout_(cricket::CONNECTION_WRITE_CONNECT_TIMEOUT) {
352 if (outgoing_) {
353 CreateOutgoingTcpSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11354 } else {
deadbeef5c3c1042017-08-04 22:01:57355 // Incoming connections should match one of the network addresses. Same as
356 // what's being checked in OnConnect, but just DCHECKing here.
Jonas Olssond7d762d2018-03-28 07:47:51357 RTC_LOG(LS_VERBOSE) << ToString() << ": socket ipaddr: "
358 << socket_->GetLocalAddress().ToString()
359 << ", port() Network:" << port->Network()->ToString();
Steve Antonae226f62019-01-29 20:47:38360 RTC_DCHECK(absl::c_any_of(
361 port_->Network()->GetIPs(), [this](const rtc::InterfaceAddress& addr) {
362 return socket_->GetLocalAddress().ipaddr() == addr;
363 }));
Guo-wei Shiehbe508a12015-04-06 19:48:47364 ConnectSocketSignals(socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11365 }
366}
367
Yves Gerey665174f2018-06-19 13:03:05368TCPConnection::~TCPConnection() {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11369
Yves Gerey665174f2018-06-19 13:03:05370int TCPConnection::Send(const void* data,
371 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11372 const rtc::PacketOptions& options) {
373 if (!socket_) {
374 error_ = ENOTCONN;
375 return SOCKET_ERROR;
376 }
377
Guo-wei Shiehbe508a12015-04-06 19:48:47378 // Sending after OnClose on active side will trigger a reconnect for a
379 // outgoing connection. Note that the write state is still WRITABLE as we want
380 // to spend a few seconds attempting a reconnect before saying we're
381 // unwritable.
382 if (!connected()) {
383 MaybeReconnect();
384 return SOCKET_ERROR;
385 }
386
387 // Note that this is important to put this after the previous check to give
388 // the connection a chance to reconnect.
389 if (pretending_to_be_writable_ || write_state() != STATE_WRITABLE) {
Steve Anton6c38cc72017-11-29 18:25:58390 // TODO(?): Should STATE_WRITE_TIMEOUT return a non-blocking error?
skvladc309e0e2016-07-29 00:15:20391 error_ = ENOTCONN;
henrike@webrtc.org269fb4b2014-10-28 22:20:11392 return SOCKET_ERROR;
393 }
zhihuang5ecf16c2016-06-02 00:09:15394 stats_.sent_total_packets++;
Qingsi Wang6e641e62018-04-12 03:14:17395 rtc::PacketOptions modified_options(options);
396 static_cast<TCPPort*>(port_)->CopyPortInformationToPacketInfo(
397 &modified_options.info_signaled_after_sent);
398 int sent = socket_->Send(data, size, modified_options);
henrike@webrtc.org269fb4b2014-10-28 22:20:11399 if (sent < 0) {
zhihuang5ecf16c2016-06-02 00:09:15400 stats_.sent_discarded_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11401 error_ = socket_->GetError();
402 } else {
Tim Psiaki63046262015-09-14 17:38:08403 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11404 }
405 return sent;
406}
407
408int TCPConnection::GetError() {
409 return error_;
410}
411
Guo-wei Shiehbe508a12015-04-06 19:48:47412void TCPConnection::OnConnectionRequestResponse(ConnectionRequest* req,
413 StunMessage* response) {
Guo-wei Shiehb5940412015-08-24 18:58:03414 // Process the STUN response before we inform upper layer ready to send.
Guo-wei Shiehbe508a12015-04-06 19:48:47415 Connection::OnConnectionRequestResponse(req, response);
Guo-wei Shiehb5940412015-08-24 18:58:03416
417 // If we're in the state of pretending to be writeable, we should inform the
418 // upper layer it's ready to send again as previous EWOULDLBLOCK from socket
419 // would have stopped the outgoing stream.
420 if (pretending_to_be_writable_) {
421 Connection::OnReadyToSend();
422 }
423 pretending_to_be_writable_ = false;
nisseede5da42017-01-12 13:15:36424 RTC_DCHECK(write_state() == STATE_WRITABLE);
Guo-wei Shiehbe508a12015-04-06 19:48:47425}
426
henrike@webrtc.org269fb4b2014-10-28 22:20:11427void TCPConnection::OnConnect(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 13:15:36428 RTC_DCHECK(socket == socket_.get());
deadbeef5c3c1042017-08-04 22:01:57429 // Do not use this port if the socket bound to an address not associated with
430 // the desired network interface. This is seen in Chrome, where TCP sockets
431 // cannot be given a binding address, and the platform is expected to pick
432 // the correct local address.
433 //
434 // However, there are two situations in which we allow the bound address to
435 // not be one of the addresses of the requested interface:
436 // 1. The bound address is the loopback address. This happens when a proxy
437 // forces TCP to bind to only the localhost address (see issue 3927).
438 // 2. The bound address is the "any address". This happens when
439 // multiple_routes is disabled (see issue 4780).
440 //
441 // Note that, aside from minor differences in log statements, this logic is
442 // identical to that in TurnPort.
443 const rtc::SocketAddress& socket_address = socket->GetLocalAddress();
Steve Antonae226f62019-01-29 20:47:38444 if (absl::c_any_of(port_->Network()->GetIPs(),
445 [socket_address](const rtc::InterfaceAddress& addr) {
446 return socket_address.ipaddr() == addr;
447 })) {
Yves Gerey665174f2018-06-19 13:03:05448 RTC_LOG(LS_VERBOSE) << ToString() << ": Connection established to "
Jonas Olssond7d762d2018-03-28 07:47:51449 << socket->GetRemoteAddress().ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11450 } else {
deadbeef5c3c1042017-08-04 22:01:57451 if (socket->GetLocalAddress().IsLoopbackIP()) {
Mirko Bonadei675513b2017-11-09 10:09:25452 RTC_LOG(LS_WARNING) << "Socket is bound to the address:"
453 << socket_address.ipaddr().ToString()
Taylor Brandstetter3ba7a572018-03-02 18:58:25454 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 10:09:25455 << port_->Network()->ToString()
456 << ". Still allowing it since it's localhost.";
deadbeef5c3c1042017-08-04 22:01:57457 } else if (IPIsAny(port_->Network()->GetBestIP())) {
Mirko Bonadei675513b2017-11-09 10:09:25458 RTC_LOG(LS_WARNING)
459 << "Socket is bound to the address:"
460 << socket_address.ipaddr().ToString()
Taylor Brandstetter3ba7a572018-03-02 18:58:25461 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 10:09:25462 << port_->Network()->ToString()
463 << ". Still allowing it since it's the 'any' address"
Jonas Olssond7d762d2018-03-28 07:47:51464 ", possibly caused by multiple_routes being disabled.";
deadbeef5c3c1042017-08-04 22:01:57465 } else {
Mirko Bonadei675513b2017-11-09 10:09:25466 RTC_LOG(LS_WARNING) << "Dropping connection as TCP socket bound to IP "
467 << socket_address.ipaddr().ToString()
Taylor Brandstetter3ba7a572018-03-02 18:58:25468 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 10:09:25469 << port_->Network()->ToString();
deadbeef5c3c1042017-08-04 22:01:57470 OnClose(socket, 0);
471 return;
472 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11473 }
tommi5ce1a2a2016-05-14 10:19:31474
475 // Connection is established successfully.
476 set_connected(true);
477 connection_pending_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11478}
479
480void TCPConnection::OnClose(rtc::AsyncPacketSocket* socket, int error) {
nisseede5da42017-01-12 13:15:36481 RTC_DCHECK(socket == socket_.get());
Yves Gerey665174f2018-06-19 13:03:05482 RTC_LOG(LS_INFO) << ToString() << ": Connection closed with error " << error;
Guo-wei Shiehbe508a12015-04-06 19:48:47483
484 // Guard against the condition where IPC socket will call OnClose for every
485 // packet it can't send.
486 if (connected()) {
487 set_connected(false);
Guo-wei Shieh1eb87c72015-08-25 18:02:55488
489 // Prevent the connection from being destroyed by redundant SignalClose
490 // events.
Guo-wei Shiehbe508a12015-04-06 19:48:47491 pretending_to_be_writable_ = true;
492
493 // We don't attempt reconnect right here. This is to avoid a case where the
494 // shutdown is intentional and reconnect is not necessary. We only reconnect
495 // when the connection is used to Send() or Ping().
Taylor Brandstetter5d97a9a2016-06-10 21:17:27496 port()->thread()->PostDelayed(RTC_FROM_HERE, reconnection_timeout(), this,
Guo-wei Shiehbe508a12015-04-06 19:48:47497 MSG_TCPCONNECTION_DELAYED_ONCLOSE);
Guo-wei Shieh1eb87c72015-08-25 18:02:55498 } else if (!pretending_to_be_writable_) {
499 // OnClose could be called when the underneath socket times out during the
500 // initial connect() (i.e. |pretending_to_be_writable_| is false) . We have
501 // to manually destroy here as this connection, as never connected, will not
502 // be scheduled for ping to trigger destroy.
503 Destroy();
Guo-wei Shiehbe508a12015-04-06 19:48:47504 }
505}
506
507void TCPConnection::OnMessage(rtc::Message* pmsg) {
508 switch (pmsg->message_id) {
509 case MSG_TCPCONNECTION_DELAYED_ONCLOSE:
510 // If this connection can't become connected and writable again in 5
511 // seconds, it's time to tear this down. This is the case for the original
512 // TCP connection on passive side during a reconnect.
513 if (pretending_to_be_writable_) {
Guo-wei Shieh1eb87c72015-08-25 18:02:55514 Destroy();
Guo-wei Shiehbe508a12015-04-06 19:48:47515 }
516 break;
517 default:
518 Connection::OnMessage(pmsg);
519 }
520}
521
522void TCPConnection::MaybeReconnect() {
523 // Only reconnect for an outgoing TCPConnection when OnClose was signaled and
524 // no outstanding reconnect is pending.
525 if (connected() || connection_pending_ || !outgoing_) {
526 return;
527 }
528
Jonas Olssond7d762d2018-03-28 07:47:51529 RTC_LOG(LS_INFO) << ToString()
530 << ": TCP Connection with remote is closed, "
531 "trying to reconnect";
Guo-wei Shiehbe508a12015-04-06 19:48:47532
533 CreateOutgoingTcpSocket();
534 error_ = EPIPE;
henrike@webrtc.org269fb4b2014-10-28 22:20:11535}
536
Yves Gerey665174f2018-06-19 13:03:05537void TCPConnection::OnReadPacket(rtc::AsyncPacketSocket* socket,
538 const char* data,
539 size_t size,
540 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 12:01:41541 const int64_t& packet_time_us) {
nisseede5da42017-01-12 13:15:36542 RTC_DCHECK(socket == socket_.get());
Niels Möllere6933812018-11-05 12:01:41543 Connection::OnReadPacket(data, size, packet_time_us);
henrike@webrtc.org269fb4b2014-10-28 22:20:11544}
545
546void TCPConnection::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 13:15:36547 RTC_DCHECK(socket == socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11548 Connection::OnReadyToSend();
549}
550
Guo-wei Shiehbe508a12015-04-06 19:48:47551void TCPConnection::CreateOutgoingTcpSocket() {
nisseede5da42017-01-12 13:15:36552 RTC_DCHECK(outgoing_);
Guo-wei Shiehbe508a12015-04-06 19:48:47553 // TODO(guoweis): Handle failures here (unlikely since TCP).
554 int opts = (remote_candidate().protocol() == SSLTCP_PROTOCOL_NAME)
hnsl04833622017-01-09 16:35:45555 ? rtc::PacketSocketFactory::OPT_TLS_FAKE
Guo-wei Shiehbe508a12015-04-06 19:48:47556 : 0;
557 socket_.reset(port()->socket_factory()->CreateClientTcpSocket(
deadbeef5c3c1042017-08-04 22:01:57558 rtc::SocketAddress(port()->Network()->GetBestIP(), 0),
559 remote_candidate().address(), port()->proxy(), port()->user_agent(),
560 opts));
Guo-wei Shiehbe508a12015-04-06 19:48:47561 if (socket_) {
Yves Gerey665174f2018-06-19 13:03:05562 RTC_LOG(LS_VERBOSE) << ToString() << ": Connecting from "
Jonas Olssond7d762d2018-03-28 07:47:51563 << socket_->GetLocalAddress().ToSensitiveString()
564 << " to "
565 << remote_candidate().address().ToSensitiveString();
Guo-wei Shiehbe508a12015-04-06 19:48:47566 set_connected(false);
567 connection_pending_ = true;
568 ConnectSocketSignals(socket_.get());
569 } else {
Yves Gerey665174f2018-06-19 13:03:05570 RTC_LOG(LS_WARNING) << ToString() << ": Failed to create connection to "
Jonas Olssond7d762d2018-03-28 07:47:51571 << remote_candidate().address().ToSensitiveString();
Guo-wei Shiehbe508a12015-04-06 19:48:47572 }
573}
574
575void TCPConnection::ConnectSocketSignals(rtc::AsyncPacketSocket* socket) {
576 if (outgoing_) {
577 socket->SignalConnect.connect(this, &TCPConnection::OnConnect);
578 }
579 socket->SignalReadPacket.connect(this, &TCPConnection::OnReadPacket);
580 socket->SignalReadyToSend.connect(this, &TCPConnection::OnReadyToSend);
581 socket->SignalClose.connect(this, &TCPConnection::OnClose);
582}
583
henrike@webrtc.org269fb4b2014-10-28 22:20:11584} // namespace cricket