blob: ee644eb7f436c7e915e3b0e0bc136342a28edb30 [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 *
Artem Titov2dbb4c92021-07-26 15:12:41 +020021 * - PendingTCP: `connection_pending_` indicates whether there is an
Guo-wei Shiehbe508a12015-04-06 12:48:47 -070022 * outstanding TCP connection in progress.
23 *
Artem Titov2dbb4c92021-07-26 15:12:41 +020024 * - PretendWri: Tracked by `pretending_to_be_writable_`. Marking connection as
Guo-wei Shiehbe508a12015-04-06 12:48:47 -070025 * 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
Steve Anton10542f22019-01-11 09:11:00 -080067#include "p2p/base/tcp_port.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000068
Yves Gerey3e707812018-11-28 16:47:49 +010069#include <errno.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020070
Tommid7e5cfb2022-03-30 20:13:06 +020071#include <utility>
Steve Anton6c38cc72017-11-29 10:25:58 -080072#include <vector>
73
Steve Antonae226f62019-01-29 12:47:38 -080074#include "absl/algorithm/container.h"
Niels Möller6d19d142021-10-06 11:19:03 +020075#include "absl/memory/memory.h"
Steve Anton10542f22019-01-11 09:11:00 -080076#include "p2p/base/p2p_constants.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020077#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080078#include "rtc_base/ip_address.h"
Yves Gerey3e707812018-11-28 16:47:49 +010079#include "rtc_base/location.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020080#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080081#include "rtc_base/net_helper.h"
82#include "rtc_base/rate_tracker.h"
Mirko Bonadei0cb1cfa2022-02-25 10:45:32 +000083#include "rtc_base/task_utils/to_queued_task.h"
Yves Gerey3e707812018-11-28 16:47:49 +010084#include "rtc_base/third_party/sigslot/sigslot.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000085
86namespace cricket {
87
88TCPPort::TCPPort(rtc::Thread* thread,
89 rtc::PacketSocketFactory* factory,
Niels Möllere0c6bdf2022-03-24 15:18:02 +010090 const rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +020091 uint16_t min_port,
92 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +000093 const std::string& username,
94 const std::string& password,
Jonas Orelandc06fe8b2022-03-28 14:58:26 +020095 bool allow_listen,
Jonas Orelande62c2f22022-03-29 11:04:48 +020096 const webrtc::FieldTrialsView* field_trials)
Peter Boström0c4e06b2015-10-07 12:23:21 +020097 : Port(thread,
98 LOCAL_PORT_TYPE,
99 factory,
100 network,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200101 min_port,
102 max_port,
103 username,
Jonas Orelandc06fe8b2022-03-28 14:58:26 +0200104 password,
105 field_trials),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000106 allow_listen_(allow_listen),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000107 error_(0) {
108 // TODO(mallinath) - Set preference value as per RFC 6544.
109 // http://b/issue?id=7141794
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000110 if (allow_listen_) {
deadbeef1ee21252017-06-13 15:49:45 -0700111 TryCreateServerSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000112 }
Niels Möller646fddc2021-11-02 15:56:05 +0100113 // Set TCP_NODELAY (via OPT_NODELAY) for improved performance; this causes
114 // small media packets to be sent immediately rather than being buffered up,
115 // reducing latency.
116 SetOption(rtc::Socket::OPT_NODELAY, 1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000117}
118
119TCPPort::~TCPPort() {
Niels Möller6d19d142021-10-06 11:19:03 +0200120 listen_socket_ = nullptr;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000121 std::list<Incoming>::iterator it;
122 for (it = incoming_.begin(); it != incoming_.end(); ++it)
123 delete it->socket;
124 incoming_.clear();
125}
126
127Connection* TCPPort::CreateConnection(const Candidate& address,
128 CandidateOrigin origin) {
Honghai Zhangf9945b22015-12-15 12:20:13 -0800129 if (!SupportsProtocol(address.protocol())) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000130 return NULL;
131 }
132
Philipp Hanckee283d1c2020-03-27 09:56:51 +0100133 if ((address.tcptype() == TCPTYPE_ACTIVE_STR &&
134 address.type() != PRFLX_PORT_TYPE) ||
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000135 (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
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000145 // We don't know how to act as an ssl server yet
146 if ((address.protocol() == SSLTCP_PROTOCOL_NAME) &&
147 (origin == ORIGIN_THIS_PORT)) {
148 return NULL;
149 }
150
151 if (!IsCompatibleAddress(address.address())) {
152 return NULL;
153 }
154
155 TCPConnection* conn = NULL;
Yves Gerey665174f2018-06-19 15:03:05 +0200156 if (rtc::AsyncPacketSocket* socket = GetIncoming(address.address(), true)) {
deadbeef06878292017-04-21 14:22:23 -0700157 // Incoming connection; we already created a socket and connected signals,
158 // so we need to hand off the "read packet" responsibility to
159 // TCPConnection.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000160 socket->SignalReadPacket.disconnect(this);
Tommid7e5cfb2022-03-30 20:13:06 +0200161 conn = new TCPConnection(NewWeakPtr(), address, socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000162 } else {
deadbeef06878292017-04-21 14:22:23 -0700163 // Outgoing connection, which will create a new socket for which we still
164 // need to connect SignalReadyToSend and SignalSentPacket.
Tommid7e5cfb2022-03-30 20:13:06 +0200165 conn = new TCPConnection(NewWeakPtr(), address);
deadbeef06878292017-04-21 14:22:23 -0700166 if (conn->socket()) {
167 conn->socket()->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
168 conn->socket()->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
169 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000170 }
honghaiz36f50e82016-06-01 15:57:03 -0700171 AddOrReplaceConnection(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000172 return conn;
173}
174
175void TCPPort::PrepareAddress() {
Niels Möller6d19d142021-10-06 11:19:03 +0200176 if (listen_socket_) {
Niels Möller4a1c2c42021-09-28 10:17:07 +0200177 // Socket may be in the CLOSED state if Listen()
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000178 // failed, we still want to add the socket address.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100179 RTC_LOG(LS_VERBOSE) << "Preparing TCP address, current state: "
Niels Möllerd30ece12021-10-19 10:11:02 +0200180 << static_cast<int>(listen_socket_->GetState());
181 AddAddress(listen_socket_->GetLocalAddress(),
182 listen_socket_->GetLocalAddress(), rtc::SocketAddress(),
183 TCP_PROTOCOL_NAME, "", TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE,
184 ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000185 } else {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200186 RTC_LOG(LS_INFO) << ToString()
187 << ": Not listening due to firewall restrictions.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000188 // Note: We still add the address, since otherwise the remote side won't
Guo-wei Shieh310b0932015-11-17 19:15:50 -0800189 // recognize our incoming TCP connections. According to
190 // https://tools.ietf.org/html/rfc6544#section-4.5, for active candidate,
deadbeef5c3c1042017-08-04 15:01:57 -0700191 // the port must be set to the discard port, i.e. 9. We can't be 100% sure
192 // which IP address will actually be used, so GetBestIP is as good as we
193 // can do.
194 // TODO(deadbeef): We could do something like create a dummy socket just to
195 // see what IP we get. But that may be overkill.
196 AddAddress(rtc::SocketAddress(Network()->GetBestIP(), DISCARD_PORT),
197 rtc::SocketAddress(Network()->GetBestIP(), 0),
198 rtc::SocketAddress(), TCP_PROTOCOL_NAME, "", TCPTYPE_ACTIVE_STR,
199 LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000200 }
201}
202
Yves Gerey665174f2018-06-19 15:03:05 +0200203int TCPPort::SendTo(const void* data,
204 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000205 const rtc::SocketAddress& addr,
206 const rtc::PacketOptions& options,
207 bool payload) {
Yves Gerey665174f2018-06-19 15:03:05 +0200208 rtc::AsyncPacketSocket* socket = NULL;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700209 TCPConnection* conn = static_cast<TCPConnection*>(GetConnection(addr));
210
211 // For Connection, this is the code path used by Ping() to establish
212 // WRITABLE. It has to send through the socket directly as TCPConnection::Send
213 // checks writability.
214 if (conn) {
215 if (!conn->connected()) {
216 conn->MaybeReconnect();
217 return SOCKET_ERROR;
218 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000219 socket = conn->socket();
Harald Alvestranddc800172020-01-06 20:01:36 +0100220 if (!socket) {
221 // The failure to initialize should have been logged elsewhere,
222 // so this log is not important.
223 RTC_LOG(LS_INFO) << ToString()
224 << ": Attempted to send to an uninitialized socket: "
225 << addr.ToSensitiveString();
226 error_ = EHOSTUNREACH;
227 return SOCKET_ERROR;
228 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000229 } else {
230 socket = GetIncoming(addr);
Harald Alvestranddc800172020-01-06 20:01:36 +0100231 if (!socket) {
232 RTC_LOG(LS_ERROR) << ToString()
233 << ": Attempted to send to an unknown destination: "
234 << addr.ToSensitiveString();
235 error_ = EHOSTUNREACH;
236 return SOCKET_ERROR;
237 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000238 }
Qingsi Wang6e641e62018-04-11 20:14:17 -0700239 rtc::PacketOptions modified_options(options);
240 CopyPortInformationToPacketInfo(&modified_options.info_signaled_after_sent);
241 int sent = socket->Send(data, size, modified_options);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000242 if (sent < 0) {
243 error_ = socket->GetError();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700244 // Error from this code path for a Connection (instead of from a bare
245 // socket) will not trigger reconnecting. In theory, this shouldn't matter
246 // as OnClose should always be called and set connected to false.
Yves Gerey665174f2018-06-19 15:03:05 +0200247 RTC_LOG(LS_ERROR) << ToString() << ": TCP send of " << size
248 << " bytes failed with error " << error_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000249 }
250 return sent;
251}
252
253int TCPPort::GetOption(rtc::Socket::Option opt, int* value) {
Niels Möller646fddc2021-11-02 15:56:05 +0100254 auto const& it = socket_options_.find(opt);
255 if (it == socket_options_.end()) {
256 return -1;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000257 }
Niels Möller646fddc2021-11-02 15:56:05 +0100258 *value = it->second;
259 return 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000260}
261
262int TCPPort::SetOption(rtc::Socket::Option opt, int value) {
Niels Möller646fddc2021-11-02 15:56:05 +0100263 socket_options_[opt] = value;
264 return 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000265}
266
267int TCPPort::GetError() {
268 return error_;
269}
270
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700271bool TCPPort::SupportsProtocol(const std::string& protocol) const {
272 return protocol == TCP_PROTOCOL_NAME || protocol == SSLTCP_PROTOCOL_NAME;
273}
274
275ProtocolType TCPPort::GetProtocol() const {
276 return PROTO_TCP;
277}
278
Niels Möller6d19d142021-10-06 11:19:03 +0200279void TCPPort::OnNewConnection(rtc::AsyncListenSocket* socket,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000280 rtc::AsyncPacketSocket* new_socket) {
Niels Möller6d19d142021-10-06 11:19:03 +0200281 RTC_DCHECK(socket == listen_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000282
Niels Möller646fddc2021-11-02 15:56:05 +0100283 for (const auto& option : socket_options_) {
284 new_socket->SetOption(option.first, option.second);
285 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000286 Incoming incoming;
287 incoming.addr = new_socket->GetRemoteAddress();
288 incoming.socket = new_socket;
289 incoming.socket->SignalReadPacket.connect(this, &TCPPort::OnReadPacket);
290 incoming.socket->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
Stefan Holmer55674ff2016-01-14 15:49:16 +0100291 incoming.socket->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000292
Yves Gerey665174f2018-06-19 15:03:05 +0200293 RTC_LOG(LS_VERBOSE) << ToString() << ": Accepted connection from "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200294 << incoming.addr.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000295 incoming_.push_back(incoming);
296}
297
deadbeef1ee21252017-06-13 15:49:45 -0700298void TCPPort::TryCreateServerSocket() {
Niels Möller6d19d142021-10-06 11:19:03 +0200299 listen_socket_ = absl::WrapUnique(socket_factory()->CreateServerTcpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -0700300 rtc::SocketAddress(Network()->GetBestIP(), 0), min_port(), max_port(),
Niels Möller6d19d142021-10-06 11:19:03 +0200301 false /* ssl */));
302 if (!listen_socket_) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200303 RTC_LOG(LS_WARNING)
304 << ToString()
305 << ": TCP server socket creation failed; continuing anyway.";
deadbeef1ee21252017-06-13 15:49:45 -0700306 return;
307 }
Niels Möller6d19d142021-10-06 11:19:03 +0200308 listen_socket_->SignalNewConnection.connect(this, &TCPPort::OnNewConnection);
deadbeef1ee21252017-06-13 15:49:45 -0700309}
310
Yves Gerey665174f2018-06-19 15:03:05 +0200311rtc::AsyncPacketSocket* TCPPort::GetIncoming(const rtc::SocketAddress& addr,
312 bool remove) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000313 rtc::AsyncPacketSocket* socket = NULL;
314 for (std::list<Incoming>::iterator it = incoming_.begin();
315 it != incoming_.end(); ++it) {
316 if (it->addr == addr) {
317 socket = it->socket;
318 if (remove)
319 incoming_.erase(it);
320 break;
321 }
322 }
323 return socket;
324}
325
326void TCPPort::OnReadPacket(rtc::AsyncPacketSocket* socket,
Yves Gerey665174f2018-06-19 15:03:05 +0200327 const char* data,
328 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000329 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +0100330 const int64_t& packet_time_us) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000331 Port::OnReadPacket(data, size, remote_addr, PROTO_TCP);
332}
333
Stefan Holmer55674ff2016-01-14 15:49:16 +0100334void TCPPort::OnSentPacket(rtc::AsyncPacketSocket* socket,
335 const rtc::SentPacket& sent_packet) {
Stefan Holmer55674ff2016-01-14 15:49:16 +0100336 PortInterface::SignalSentPacket(sent_packet);
337}
338
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000339void TCPPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
340 Port::OnReadyToSend();
341}
342
Artem Titov2dbb4c92021-07-26 15:12:41 +0200343// TODO(qingsi): `CONNECTION_WRITE_CONNECT_TIMEOUT` is overriden by
344// `ice_unwritable_timeout` in IceConfig when determining the writability state.
Qingsi Wang22e623a2018-03-13 10:53:57 -0700345// Replace this constant with the config parameter assuming the default value if
346// we decide it is also applicable here.
Tommid7e5cfb2022-03-30 20:13:06 +0200347TCPConnection::TCPConnection(rtc::WeakPtr<Port> tcp_port,
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700348 const Candidate& candidate,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000349 rtc::AsyncPacketSocket* socket)
Tommid7e5cfb2022-03-30 20:13:06 +0200350 : Connection(std::move(tcp_port), 0, candidate),
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700351 socket_(socket),
352 error_(0),
353 outgoing_(socket == NULL),
354 connection_pending_(false),
355 pretending_to_be_writable_(false),
356 reconnection_timeout_(cricket::CONNECTION_WRITE_CONNECT_TIMEOUT) {
Tommid7e5cfb2022-03-30 20:13:06 +0200357 RTC_DCHECK_EQ(port()->GetProtocol(), PROTO_TCP); // Needs to be TCPPort.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700358 if (outgoing_) {
359 CreateOutgoingTcpSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000360 } else {
deadbeef5c3c1042017-08-04 15:01:57 -0700361 // Incoming connections should match one of the network addresses. Same as
362 // what's being checked in OnConnect, but just DCHECKing here.
Jonas Olssond7d762d2018-03-28 09:47:51 +0200363 RTC_LOG(LS_VERBOSE) << ToString() << ": socket ipaddr: "
Qingsi Wang20232a92019-09-06 12:51:17 -0700364 << socket_->GetLocalAddress().ToSensitiveString()
Tommid7e5cfb2022-03-30 20:13:06 +0200365 << ", port() Network:" << port()->Network()->ToString();
Steve Antonae226f62019-01-29 12:47:38 -0800366 RTC_DCHECK(absl::c_any_of(
367 port_->Network()->GetIPs(), [this](const rtc::InterfaceAddress& addr) {
368 return socket_->GetLocalAddress().ipaddr() == addr;
369 }));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700370 ConnectSocketSignals(socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000371 }
372}
373
Mirko Bonadei0cb1cfa2022-02-25 10:45:32 +0000374TCPConnection::~TCPConnection() {
375 RTC_DCHECK_RUN_ON(network_thread_);
376}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000377
Yves Gerey665174f2018-06-19 15:03:05 +0200378int TCPConnection::Send(const void* data,
379 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000380 const rtc::PacketOptions& options) {
381 if (!socket_) {
382 error_ = ENOTCONN;
383 return SOCKET_ERROR;
384 }
385
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700386 // Sending after OnClose on active side will trigger a reconnect for a
387 // outgoing connection. Note that the write state is still WRITABLE as we want
388 // to spend a few seconds attempting a reconnect before saying we're
389 // unwritable.
390 if (!connected()) {
391 MaybeReconnect();
392 return SOCKET_ERROR;
393 }
394
395 // Note that this is important to put this after the previous check to give
396 // the connection a chance to reconnect.
397 if (pretending_to_be_writable_ || write_state() != STATE_WRITABLE) {
Steve Anton6c38cc72017-11-29 10:25:58 -0800398 // TODO(?): Should STATE_WRITE_TIMEOUT return a non-blocking error?
skvladc309e0e2016-07-28 17:15:20 -0700399 error_ = ENOTCONN;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000400 return SOCKET_ERROR;
401 }
zhihuang5ecf16c2016-06-01 17:09:15 -0700402 stats_.sent_total_packets++;
Qingsi Wang6e641e62018-04-11 20:14:17 -0700403 rtc::PacketOptions modified_options(options);
Tommid7e5cfb2022-03-30 20:13:06 +0200404 tcp_port()->CopyPortInformationToPacketInfo(
Qingsi Wang6e641e62018-04-11 20:14:17 -0700405 &modified_options.info_signaled_after_sent);
406 int sent = socket_->Send(data, size, modified_options);
Jonas Oreland3c5d5822020-12-14 12:45:05 +0100407 int64_t now = rtc::TimeMillis();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000408 if (sent < 0) {
zhihuang5ecf16c2016-06-01 17:09:15 -0700409 stats_.sent_discarded_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000410 error_ = socket_->GetError();
411 } else {
Jonas Oreland3c5d5822020-12-14 12:45:05 +0100412 send_rate_tracker_.AddSamplesAtTime(now, sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000413 }
Jonas Oreland3c5d5822020-12-14 12:45:05 +0100414 last_send_data_ = now;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000415 return sent;
416}
417
418int TCPConnection::GetError() {
419 return error_;
420}
421
Tommic85e4732022-05-27 16:37:42 +0200422void TCPConnection::OnConnectionRequestResponse(StunRequest* req,
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700423 StunMessage* response) {
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700424 // Process the STUN response before we inform upper layer ready to send.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700425 Connection::OnConnectionRequestResponse(req, response);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700426
427 // If we're in the state of pretending to be writeable, we should inform the
428 // upper layer it's ready to send again as previous EWOULDLBLOCK from socket
429 // would have stopped the outgoing stream.
430 if (pretending_to_be_writable_) {
431 Connection::OnReadyToSend();
432 }
433 pretending_to_be_writable_ = false;
nisseede5da42017-01-12 05:15:36 -0800434 RTC_DCHECK(write_state() == STATE_WRITABLE);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700435}
436
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000437void TCPConnection::OnConnect(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800438 RTC_DCHECK(socket == socket_.get());
deadbeef5c3c1042017-08-04 15:01:57 -0700439 // Do not use this port if the socket bound to an address not associated with
440 // the desired network interface. This is seen in Chrome, where TCP sockets
441 // cannot be given a binding address, and the platform is expected to pick
442 // the correct local address.
443 //
444 // However, there are two situations in which we allow the bound address to
445 // not be one of the addresses of the requested interface:
446 // 1. The bound address is the loopback address. This happens when a proxy
447 // forces TCP to bind to only the localhost address (see issue 3927).
448 // 2. The bound address is the "any address". This happens when
449 // multiple_routes is disabled (see issue 4780).
450 //
451 // Note that, aside from minor differences in log statements, this logic is
452 // identical to that in TurnPort.
453 const rtc::SocketAddress& socket_address = socket->GetLocalAddress();
Steve Antonae226f62019-01-29 12:47:38 -0800454 if (absl::c_any_of(port_->Network()->GetIPs(),
455 [socket_address](const rtc::InterfaceAddress& addr) {
456 return socket_address.ipaddr() == addr;
457 })) {
Yves Gerey665174f2018-06-19 15:03:05 +0200458 RTC_LOG(LS_VERBOSE) << ToString() << ": Connection established to "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200459 << socket->GetRemoteAddress().ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000460 } else {
deadbeef5c3c1042017-08-04 15:01:57 -0700461 if (socket->GetLocalAddress().IsLoopbackIP()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100462 RTC_LOG(LS_WARNING) << "Socket is bound to the address:"
Qingsi Wang20232a92019-09-06 12:51:17 -0700463 << socket_address.ipaddr().ToSensitiveString()
Taylor Brandstetter3ba7a572018-03-02 10:58:25 -0800464 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100465 << port_->Network()->ToString()
466 << ". Still allowing it since it's localhost.";
deadbeef5c3c1042017-08-04 15:01:57 -0700467 } else if (IPIsAny(port_->Network()->GetBestIP())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100468 RTC_LOG(LS_WARNING)
469 << "Socket is bound to the address:"
Qingsi Wang20232a92019-09-06 12:51:17 -0700470 << socket_address.ipaddr().ToSensitiveString()
Taylor Brandstetter3ba7a572018-03-02 10:58:25 -0800471 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100472 << port_->Network()->ToString()
473 << ". Still allowing it since it's the 'any' address"
Jonas Olssond7d762d2018-03-28 09:47:51 +0200474 ", possibly caused by multiple_routes being disabled.";
deadbeef5c3c1042017-08-04 15:01:57 -0700475 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100476 RTC_LOG(LS_WARNING) << "Dropping connection as TCP socket bound to IP "
Qingsi Wang20232a92019-09-06 12:51:17 -0700477 << socket_address.ipaddr().ToSensitiveString()
Taylor Brandstetter3ba7a572018-03-02 10:58:25 -0800478 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100479 << port_->Network()->ToString();
deadbeef5c3c1042017-08-04 15:01:57 -0700480 OnClose(socket, 0);
481 return;
482 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000483 }
tommi5ce1a2a2016-05-14 03:19:31 -0700484
485 // Connection is established successfully.
486 set_connected(true);
487 connection_pending_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000488}
489
490void TCPConnection::OnClose(rtc::AsyncPacketSocket* socket, int error) {
nisseede5da42017-01-12 05:15:36 -0800491 RTC_DCHECK(socket == socket_.get());
Yves Gerey665174f2018-06-19 15:03:05 +0200492 RTC_LOG(LS_INFO) << ToString() << ": Connection closed with error " << error;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700493
494 // Guard against the condition where IPC socket will call OnClose for every
495 // packet it can't send.
496 if (connected()) {
497 set_connected(false);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700498
499 // Prevent the connection from being destroyed by redundant SignalClose
500 // events.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700501 pretending_to_be_writable_ = true;
502
Mirko Bonadei0cb1cfa2022-02-25 10:45:32 +0000503 // If this connection can't become connected and writable again in 5
504 // seconds, it's time to tear this down. This is the case for the original
505 // TCP connection on passive side during a reconnect.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700506 // We don't attempt reconnect right here. This is to avoid a case where the
507 // shutdown is intentional and reconnect is not necessary. We only reconnect
508 // when the connection is used to Send() or Ping().
Tommi1043fcd2022-05-26 13:54:35 +0200509 network_thread()->PostDelayedTask(
Mirko Bonadei0cb1cfa2022-02-25 10:45:32 +0000510 webrtc::ToQueuedTask(network_safety_,
511 [this]() {
Tomas Gunnarsson869c87a2022-05-02 19:08:43 +0000512 if (pretending_to_be_writable_) {
513 Destroy();
514 }
Mirko Bonadei0cb1cfa2022-02-25 10:45:32 +0000515 }),
516 reconnection_timeout());
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700517 } else if (!pretending_to_be_writable_) {
518 // OnClose could be called when the underneath socket times out during the
Artem Titov2dbb4c92021-07-26 15:12:41 +0200519 // initial connect() (i.e. `pretending_to_be_writable_` is false) . We have
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700520 // to manually destroy here as this connection, as never connected, will not
521 // be scheduled for ping to trigger destroy.
Tomas Gunnarssonf15189d2022-04-13 09:03:52 +0000522 socket_->UnsubscribeClose(this);
Tomas Gunnarsson869c87a2022-05-02 19:08:43 +0000523 Destroy();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700524 }
525}
526
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700527void TCPConnection::MaybeReconnect() {
528 // Only reconnect for an outgoing TCPConnection when OnClose was signaled and
529 // no outstanding reconnect is pending.
530 if (connected() || connection_pending_ || !outgoing_) {
531 return;
532 }
533
Jonas Olssond7d762d2018-03-28 09:47:51 +0200534 RTC_LOG(LS_INFO) << ToString()
535 << ": TCP Connection with remote is closed, "
536 "trying to reconnect";
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700537
538 CreateOutgoingTcpSocket();
539 error_ = EPIPE;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000540}
541
Yves Gerey665174f2018-06-19 15:03:05 +0200542void TCPConnection::OnReadPacket(rtc::AsyncPacketSocket* socket,
543 const char* data,
544 size_t size,
545 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +0100546 const int64_t& packet_time_us) {
nisseede5da42017-01-12 05:15:36 -0800547 RTC_DCHECK(socket == socket_.get());
Niels Möllere6933812018-11-05 13:01:41 +0100548 Connection::OnReadPacket(data, size, packet_time_us);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000549}
550
551void TCPConnection::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800552 RTC_DCHECK(socket == socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000553 Connection::OnReadyToSend();
554}
555
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700556void TCPConnection::CreateOutgoingTcpSocket() {
nisseede5da42017-01-12 05:15:36 -0800557 RTC_DCHECK(outgoing_);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700558 int opts = (remote_candidate().protocol() == SSLTCP_PROTOCOL_NAME)
hnsl04833622017-01-09 08:35:45 -0800559 ? rtc::PacketSocketFactory::OPT_TLS_FAKE
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700560 : 0;
Tomas Gunnarssonf15189d2022-04-13 09:03:52 +0000561
562 if (socket_) {
563 socket_->UnsubscribeClose(this);
564 }
565
Patrik Höglund662e31f2019-09-05 14:35:04 +0200566 rtc::PacketSocketTcpOptions tcp_opts;
567 tcp_opts.opts = opts;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700568 socket_.reset(port()->socket_factory()->CreateClientTcpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -0700569 rtc::SocketAddress(port()->Network()->GetBestIP(), 0),
570 remote_candidate().address(), port()->proxy(), port()->user_agent(),
Patrik Höglund662e31f2019-09-05 14:35:04 +0200571 tcp_opts));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700572 if (socket_) {
Yves Gerey665174f2018-06-19 15:03:05 +0200573 RTC_LOG(LS_VERBOSE) << ToString() << ": Connecting from "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200574 << socket_->GetLocalAddress().ToSensitiveString()
575 << " to "
576 << remote_candidate().address().ToSensitiveString();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700577 set_connected(false);
578 connection_pending_ = true;
579 ConnectSocketSignals(socket_.get());
580 } else {
Yves Gerey665174f2018-06-19 15:03:05 +0200581 RTC_LOG(LS_WARNING) << ToString() << ": Failed to create connection to "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200582 << remote_candidate().address().ToSensitiveString();
Mirko Bonadei0cb1cfa2022-02-25 10:45:32 +0000583 set_state(IceCandidatePairState::FAILED);
Jonas Oreland7a284e12020-01-28 09:21:54 +0100584 // We can't FailAndPrune directly here. FailAndPrune and deletes all
585 // the StunRequests from the request_map_. And if this is in the stack
586 // of Connection::Ping(), we are still using the request.
587 // Unwind the stack and defer the FailAndPrune.
Tommi1043fcd2022-05-26 13:54:35 +0200588 network_thread()->PostTask(
Mirko Bonadei0cb1cfa2022-02-25 10:45:32 +0000589 webrtc::ToQueuedTask(network_safety_, [this]() { FailAndPrune(); }));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700590 }
591}
592
593void TCPConnection::ConnectSocketSignals(rtc::AsyncPacketSocket* socket) {
594 if (outgoing_) {
595 socket->SignalConnect.connect(this, &TCPConnection::OnConnect);
596 }
597 socket->SignalReadPacket.connect(this, &TCPConnection::OnReadPacket);
598 socket->SignalReadyToSend.connect(this, &TCPConnection::OnReadyToSend);
Tommi1043fcd2022-05-26 13:54:35 +0200599 socket->SubscribeClose(this, [this, safety = network_safety_.flag()](
600 rtc::AsyncPacketSocket* s, int err) {
601 if (safety->alive())
602 OnClose(s, err);
603 });
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700604}
605
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000606} // namespace cricket