blob: fbda2999f9f4c1a61b400d36cb34d794bdd06eec [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"
Ali Tofighea5a9442022-06-14 15:20:15 +020076#include "absl/strings/string_view.h"
Danil Chapovalov7b190362022-07-07 14:13:02 +020077#include "api/task_queue/pending_task_safety_flag.h"
78#include "api/units/time_delta.h"
Steve Anton10542f22019-01-11 09:11:00 -080079#include "p2p/base/p2p_constants.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020080#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080081#include "rtc_base/ip_address.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020082#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080083#include "rtc_base/net_helper.h"
84#include "rtc_base/rate_tracker.h"
Yves Gerey3e707812018-11-28 16:47:49 +010085#include "rtc_base/third_party/sigslot/sigslot.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000086
87namespace cricket {
Danil Chapovalov7b190362022-07-07 14:13:02 +020088using ::webrtc::SafeTask;
89using ::webrtc::TimeDelta;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000090
91TCPPort::TCPPort(rtc::Thread* thread,
92 rtc::PacketSocketFactory* factory,
Niels Möllere0c6bdf2022-03-24 15:18:02 +010093 const rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +020094 uint16_t min_port,
95 uint16_t max_port,
Ali Tofighde2ac5a2022-06-30 11:58:26 +020096 absl::string_view username,
97 absl::string_view password,
Jonas Orelandc06fe8b2022-03-28 14:58:26 +020098 bool allow_listen,
Jonas Orelande62c2f22022-03-29 11:04:48 +020099 const webrtc::FieldTrialsView* field_trials)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200100 : Port(thread,
101 LOCAL_PORT_TYPE,
102 factory,
103 network,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200104 min_port,
105 max_port,
106 username,
Jonas Orelandc06fe8b2022-03-28 14:58:26 +0200107 password,
108 field_trials),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000109 allow_listen_(allow_listen),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000110 error_(0) {
111 // TODO(mallinath) - Set preference value as per RFC 6544.
112 // http://b/issue?id=7141794
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000113 if (allow_listen_) {
deadbeef1ee21252017-06-13 15:49:45 -0700114 TryCreateServerSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000115 }
Niels Möller646fddc2021-11-02 15:56:05 +0100116 // Set TCP_NODELAY (via OPT_NODELAY) for improved performance; this causes
117 // small media packets to be sent immediately rather than being buffered up,
118 // reducing latency.
119 SetOption(rtc::Socket::OPT_NODELAY, 1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000120}
121
122TCPPort::~TCPPort() {
Niels Möller6d19d142021-10-06 11:19:03 +0200123 listen_socket_ = nullptr;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000124 std::list<Incoming>::iterator it;
125 for (it = incoming_.begin(); it != incoming_.end(); ++it)
126 delete it->socket;
127 incoming_.clear();
128}
129
130Connection* TCPPort::CreateConnection(const Candidate& address,
131 CandidateOrigin origin) {
Honghai Zhangf9945b22015-12-15 12:20:13 -0800132 if (!SupportsProtocol(address.protocol())) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000133 return NULL;
134 }
135
Philipp Hanckee283d1c2020-03-27 09:56:51 +0100136 if ((address.tcptype() == TCPTYPE_ACTIVE_STR &&
137 address.type() != PRFLX_PORT_TYPE) ||
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000138 (address.tcptype().empty() && address.address().port() == 0)) {
139 // It's active only candidate, we should not try to create connections
140 // for these candidates.
141 return NULL;
142 }
143
144 // We can't accept TCP connections incoming on other ports
145 if (origin == ORIGIN_OTHER_PORT)
146 return NULL;
147
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000148 // 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;
Yves Gerey665174f2018-06-19 15:03:05 +0200159 if (rtc::AsyncPacketSocket* socket = GetIncoming(address.address(), true)) {
deadbeef06878292017-04-21 14:22:23 -0700160 // Incoming connection; we already created a socket and connected signals,
161 // so we need to hand off the "read packet" responsibility to
162 // TCPConnection.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000163 socket->SignalReadPacket.disconnect(this);
Tommid7e5cfb2022-03-30 20:13:06 +0200164 conn = new TCPConnection(NewWeakPtr(), address, socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000165 } else {
deadbeef06878292017-04-21 14:22:23 -0700166 // Outgoing connection, which will create a new socket for which we still
167 // need to connect SignalReadyToSend and SignalSentPacket.
Tommid7e5cfb2022-03-30 20:13:06 +0200168 conn = new TCPConnection(NewWeakPtr(), address);
deadbeef06878292017-04-21 14:22:23 -0700169 if (conn->socket()) {
170 conn->socket()->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
171 conn->socket()->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
172 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000173 }
honghaiz36f50e82016-06-01 15:57:03 -0700174 AddOrReplaceConnection(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000175 return conn;
176}
177
178void TCPPort::PrepareAddress() {
Niels Möller6d19d142021-10-06 11:19:03 +0200179 if (listen_socket_) {
Niels Möller4a1c2c42021-09-28 10:17:07 +0200180 // Socket may be in the CLOSED state if Listen()
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000181 // failed, we still want to add the socket address.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100182 RTC_LOG(LS_VERBOSE) << "Preparing TCP address, current state: "
Niels Möllerd30ece12021-10-19 10:11:02 +0200183 << static_cast<int>(listen_socket_->GetState());
184 AddAddress(listen_socket_->GetLocalAddress(),
185 listen_socket_->GetLocalAddress(), rtc::SocketAddress(),
186 TCP_PROTOCOL_NAME, "", TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE,
187 ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000188 } else {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200189 RTC_LOG(LS_INFO) << ToString()
190 << ": Not listening due to firewall restrictions.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000191 // Note: We still add the address, since otherwise the remote side won't
Guo-wei Shieh310b0932015-11-17 19:15:50 -0800192 // recognize our incoming TCP connections. According to
193 // https://tools.ietf.org/html/rfc6544#section-4.5, for active candidate,
deadbeef5c3c1042017-08-04 15:01:57 -0700194 // the port must be set to the discard port, i.e. 9. We can't be 100% sure
195 // which IP address will actually be used, so GetBestIP is as good as we
196 // can do.
197 // TODO(deadbeef): We could do something like create a dummy socket just to
198 // see what IP we get. But that may be overkill.
199 AddAddress(rtc::SocketAddress(Network()->GetBestIP(), DISCARD_PORT),
200 rtc::SocketAddress(Network()->GetBestIP(), 0),
201 rtc::SocketAddress(), TCP_PROTOCOL_NAME, "", TCPTYPE_ACTIVE_STR,
202 LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000203 }
204}
205
Yves Gerey665174f2018-06-19 15:03:05 +0200206int TCPPort::SendTo(const void* data,
207 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000208 const rtc::SocketAddress& addr,
209 const rtc::PacketOptions& options,
210 bool payload) {
Yves Gerey665174f2018-06-19 15:03:05 +0200211 rtc::AsyncPacketSocket* socket = NULL;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700212 TCPConnection* conn = static_cast<TCPConnection*>(GetConnection(addr));
213
214 // For Connection, this is the code path used by Ping() to establish
215 // WRITABLE. It has to send through the socket directly as TCPConnection::Send
216 // checks writability.
217 if (conn) {
218 if (!conn->connected()) {
219 conn->MaybeReconnect();
220 return SOCKET_ERROR;
221 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000222 socket = conn->socket();
Harald Alvestranddc800172020-01-06 20:01:36 +0100223 if (!socket) {
224 // The failure to initialize should have been logged elsewhere,
225 // so this log is not important.
226 RTC_LOG(LS_INFO) << ToString()
227 << ": Attempted to send to an uninitialized socket: "
228 << addr.ToSensitiveString();
229 error_ = EHOSTUNREACH;
230 return SOCKET_ERROR;
231 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000232 } else {
233 socket = GetIncoming(addr);
Harald Alvestranddc800172020-01-06 20:01:36 +0100234 if (!socket) {
235 RTC_LOG(LS_ERROR) << ToString()
236 << ": Attempted to send to an unknown destination: "
237 << addr.ToSensitiveString();
238 error_ = EHOSTUNREACH;
239 return SOCKET_ERROR;
240 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000241 }
Qingsi Wang6e641e62018-04-11 20:14:17 -0700242 rtc::PacketOptions modified_options(options);
243 CopyPortInformationToPacketInfo(&modified_options.info_signaled_after_sent);
244 int sent = socket->Send(data, size, modified_options);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000245 if (sent < 0) {
246 error_ = socket->GetError();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700247 // Error from this code path for a Connection (instead of from a bare
248 // socket) will not trigger reconnecting. In theory, this shouldn't matter
249 // as OnClose should always be called and set connected to false.
Yves Gerey665174f2018-06-19 15:03:05 +0200250 RTC_LOG(LS_ERROR) << ToString() << ": TCP send of " << size
251 << " bytes failed with error " << error_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000252 }
253 return sent;
254}
255
256int TCPPort::GetOption(rtc::Socket::Option opt, int* value) {
Niels Möller646fddc2021-11-02 15:56:05 +0100257 auto const& it = socket_options_.find(opt);
258 if (it == socket_options_.end()) {
259 return -1;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000260 }
Niels Möller646fddc2021-11-02 15:56:05 +0100261 *value = it->second;
262 return 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000263}
264
265int TCPPort::SetOption(rtc::Socket::Option opt, int value) {
Niels Möller646fddc2021-11-02 15:56:05 +0100266 socket_options_[opt] = value;
267 return 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000268}
269
270int TCPPort::GetError() {
271 return error_;
272}
273
Ali Tofighea5a9442022-06-14 15:20:15 +0200274bool TCPPort::SupportsProtocol(absl::string_view protocol) const {
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700275 return protocol == TCP_PROTOCOL_NAME || protocol == SSLTCP_PROTOCOL_NAME;
276}
277
278ProtocolType TCPPort::GetProtocol() const {
279 return PROTO_TCP;
280}
281
Niels Möller6d19d142021-10-06 11:19:03 +0200282void TCPPort::OnNewConnection(rtc::AsyncListenSocket* socket,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000283 rtc::AsyncPacketSocket* new_socket) {
Tommi9095e0e2022-07-19 12:46:51 +0200284 RTC_DCHECK_EQ(socket, listen_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000285
Niels Möller646fddc2021-11-02 15:56:05 +0100286 for (const auto& option : socket_options_) {
287 new_socket->SetOption(option.first, option.second);
288 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000289 Incoming incoming;
290 incoming.addr = new_socket->GetRemoteAddress();
291 incoming.socket = new_socket;
292 incoming.socket->SignalReadPacket.connect(this, &TCPPort::OnReadPacket);
293 incoming.socket->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
Stefan Holmer55674ff2016-01-14 15:49:16 +0100294 incoming.socket->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000295
Yves Gerey665174f2018-06-19 15:03:05 +0200296 RTC_LOG(LS_VERBOSE) << ToString() << ": Accepted connection from "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200297 << incoming.addr.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000298 incoming_.push_back(incoming);
299}
300
deadbeef1ee21252017-06-13 15:49:45 -0700301void TCPPort::TryCreateServerSocket() {
Niels Möller6d19d142021-10-06 11:19:03 +0200302 listen_socket_ = absl::WrapUnique(socket_factory()->CreateServerTcpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -0700303 rtc::SocketAddress(Network()->GetBestIP(), 0), min_port(), max_port(),
Niels Möller6d19d142021-10-06 11:19:03 +0200304 false /* ssl */));
305 if (!listen_socket_) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200306 RTC_LOG(LS_WARNING)
307 << ToString()
308 << ": TCP server socket creation failed; continuing anyway.";
deadbeef1ee21252017-06-13 15:49:45 -0700309 return;
310 }
Niels Möller6d19d142021-10-06 11:19:03 +0200311 listen_socket_->SignalNewConnection.connect(this, &TCPPort::OnNewConnection);
deadbeef1ee21252017-06-13 15:49:45 -0700312}
313
Yves Gerey665174f2018-06-19 15:03:05 +0200314rtc::AsyncPacketSocket* TCPPort::GetIncoming(const rtc::SocketAddress& addr,
315 bool remove) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000316 rtc::AsyncPacketSocket* socket = NULL;
317 for (std::list<Incoming>::iterator it = incoming_.begin();
318 it != incoming_.end(); ++it) {
319 if (it->addr == addr) {
320 socket = it->socket;
321 if (remove)
322 incoming_.erase(it);
323 break;
324 }
325 }
326 return socket;
327}
328
329void TCPPort::OnReadPacket(rtc::AsyncPacketSocket* socket,
Yves Gerey665174f2018-06-19 15:03:05 +0200330 const char* data,
331 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000332 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +0100333 const int64_t& packet_time_us) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000334 Port::OnReadPacket(data, size, remote_addr, PROTO_TCP);
335}
336
Stefan Holmer55674ff2016-01-14 15:49:16 +0100337void TCPPort::OnSentPacket(rtc::AsyncPacketSocket* socket,
338 const rtc::SentPacket& sent_packet) {
Stefan Holmer55674ff2016-01-14 15:49:16 +0100339 PortInterface::SignalSentPacket(sent_packet);
340}
341
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000342void TCPPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
343 Port::OnReadyToSend();
344}
345
Artem Titov2dbb4c92021-07-26 15:12:41 +0200346// TODO(qingsi): `CONNECTION_WRITE_CONNECT_TIMEOUT` is overriden by
347// `ice_unwritable_timeout` in IceConfig when determining the writability state.
Qingsi Wang22e623a2018-03-13 10:53:57 -0700348// Replace this constant with the config parameter assuming the default value if
349// we decide it is also applicable here.
Tommid7e5cfb2022-03-30 20:13:06 +0200350TCPConnection::TCPConnection(rtc::WeakPtr<Port> tcp_port,
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700351 const Candidate& candidate,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000352 rtc::AsyncPacketSocket* socket)
Tommid7e5cfb2022-03-30 20:13:06 +0200353 : Connection(std::move(tcp_port), 0, candidate),
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700354 socket_(socket),
355 error_(0),
356 outgoing_(socket == NULL),
357 connection_pending_(false),
358 pretending_to_be_writable_(false),
359 reconnection_timeout_(cricket::CONNECTION_WRITE_CONNECT_TIMEOUT) {
Tommid7e5cfb2022-03-30 20:13:06 +0200360 RTC_DCHECK_EQ(port()->GetProtocol(), PROTO_TCP); // Needs to be TCPPort.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700361 if (outgoing_) {
362 CreateOutgoingTcpSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000363 } else {
deadbeef5c3c1042017-08-04 15:01:57 -0700364 // Incoming connections should match one of the network addresses. Same as
365 // what's being checked in OnConnect, but just DCHECKing here.
Jonas Olssond7d762d2018-03-28 09:47:51 +0200366 RTC_LOG(LS_VERBOSE) << ToString() << ": socket ipaddr: "
Qingsi Wang20232a92019-09-06 12:51:17 -0700367 << socket_->GetLocalAddress().ToSensitiveString()
Tommid7e5cfb2022-03-30 20:13:06 +0200368 << ", port() Network:" << port()->Network()->ToString();
Steve Antonae226f62019-01-29 12:47:38 -0800369 RTC_DCHECK(absl::c_any_of(
370 port_->Network()->GetIPs(), [this](const rtc::InterfaceAddress& addr) {
371 return socket_->GetLocalAddress().ipaddr() == addr;
372 }));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700373 ConnectSocketSignals(socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000374 }
375}
376
Mirko Bonadei0cb1cfa2022-02-25 10:45:32 +0000377TCPConnection::~TCPConnection() {
378 RTC_DCHECK_RUN_ON(network_thread_);
379}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000380
Yves Gerey665174f2018-06-19 15:03:05 +0200381int TCPConnection::Send(const void* data,
382 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000383 const rtc::PacketOptions& options) {
384 if (!socket_) {
385 error_ = ENOTCONN;
386 return SOCKET_ERROR;
387 }
388
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700389 // Sending after OnClose on active side will trigger a reconnect for a
390 // outgoing connection. Note that the write state is still WRITABLE as we want
391 // to spend a few seconds attempting a reconnect before saying we're
392 // unwritable.
393 if (!connected()) {
394 MaybeReconnect();
395 return SOCKET_ERROR;
396 }
397
398 // Note that this is important to put this after the previous check to give
399 // the connection a chance to reconnect.
400 if (pretending_to_be_writable_ || write_state() != STATE_WRITABLE) {
Steve Anton6c38cc72017-11-29 10:25:58 -0800401 // TODO(?): Should STATE_WRITE_TIMEOUT return a non-blocking error?
skvladc309e0e2016-07-28 17:15:20 -0700402 error_ = ENOTCONN;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000403 return SOCKET_ERROR;
404 }
zhihuang5ecf16c2016-06-01 17:09:15 -0700405 stats_.sent_total_packets++;
Qingsi Wang6e641e62018-04-11 20:14:17 -0700406 rtc::PacketOptions modified_options(options);
Tommid7e5cfb2022-03-30 20:13:06 +0200407 tcp_port()->CopyPortInformationToPacketInfo(
Qingsi Wang6e641e62018-04-11 20:14:17 -0700408 &modified_options.info_signaled_after_sent);
409 int sent = socket_->Send(data, size, modified_options);
Jonas Oreland3c5d5822020-12-14 12:45:05 +0100410 int64_t now = rtc::TimeMillis();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000411 if (sent < 0) {
zhihuang5ecf16c2016-06-01 17:09:15 -0700412 stats_.sent_discarded_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000413 error_ = socket_->GetError();
414 } else {
Jonas Oreland3c5d5822020-12-14 12:45:05 +0100415 send_rate_tracker_.AddSamplesAtTime(now, sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000416 }
Jonas Oreland3c5d5822020-12-14 12:45:05 +0100417 last_send_data_ = now;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000418 return sent;
419}
420
421int TCPConnection::GetError() {
422 return error_;
423}
424
Tommic85e4732022-05-27 16:37:42 +0200425void TCPConnection::OnConnectionRequestResponse(StunRequest* req,
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700426 StunMessage* response) {
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700427 // Process the STUN response before we inform upper layer ready to send.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700428 Connection::OnConnectionRequestResponse(req, response);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700429
430 // If we're in the state of pretending to be writeable, we should inform the
431 // upper layer it's ready to send again as previous EWOULDLBLOCK from socket
432 // would have stopped the outgoing stream.
433 if (pretending_to_be_writable_) {
434 Connection::OnReadyToSend();
435 }
436 pretending_to_be_writable_ = false;
nisseede5da42017-01-12 05:15:36 -0800437 RTC_DCHECK(write_state() == STATE_WRITABLE);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700438}
439
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000440void TCPConnection::OnConnect(rtc::AsyncPacketSocket* socket) {
Tommi9095e0e2022-07-19 12:46:51 +0200441 RTC_DCHECK_EQ(socket, socket_.get());
442
443 if (!port_) {
444 RTC_LOG(LS_ERROR) << "TCPConnection: Port has been deleted.";
445 return;
446 }
447
deadbeef5c3c1042017-08-04 15:01:57 -0700448 // Do not use this port if the socket bound to an address not associated with
449 // the desired network interface. This is seen in Chrome, where TCP sockets
450 // cannot be given a binding address, and the platform is expected to pick
451 // the correct local address.
452 //
453 // However, there are two situations in which we allow the bound address to
454 // not be one of the addresses of the requested interface:
455 // 1. The bound address is the loopback address. This happens when a proxy
456 // forces TCP to bind to only the localhost address (see issue 3927).
457 // 2. The bound address is the "any address". This happens when
458 // multiple_routes is disabled (see issue 4780).
459 //
460 // Note that, aside from minor differences in log statements, this logic is
461 // identical to that in TurnPort.
462 const rtc::SocketAddress& socket_address = socket->GetLocalAddress();
Steve Antonae226f62019-01-29 12:47:38 -0800463 if (absl::c_any_of(port_->Network()->GetIPs(),
464 [socket_address](const rtc::InterfaceAddress& addr) {
465 return socket_address.ipaddr() == addr;
466 })) {
Yves Gerey665174f2018-06-19 15:03:05 +0200467 RTC_LOG(LS_VERBOSE) << ToString() << ": Connection established to "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200468 << socket->GetRemoteAddress().ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000469 } else {
deadbeef5c3c1042017-08-04 15:01:57 -0700470 if (socket->GetLocalAddress().IsLoopbackIP()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100471 RTC_LOG(LS_WARNING) << "Socket is bound to the address:"
Qingsi Wang20232a92019-09-06 12:51:17 -0700472 << socket_address.ipaddr().ToSensitiveString()
Taylor Brandstetter3ba7a572018-03-02 10:58:25 -0800473 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100474 << port_->Network()->ToString()
475 << ". Still allowing it since it's localhost.";
deadbeef5c3c1042017-08-04 15:01:57 -0700476 } else if (IPIsAny(port_->Network()->GetBestIP())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100477 RTC_LOG(LS_WARNING)
478 << "Socket is bound to the address:"
Qingsi Wang20232a92019-09-06 12:51:17 -0700479 << socket_address.ipaddr().ToSensitiveString()
Taylor Brandstetter3ba7a572018-03-02 10:58:25 -0800480 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100481 << port_->Network()->ToString()
482 << ". Still allowing it since it's the 'any' address"
Jonas Olssond7d762d2018-03-28 09:47:51 +0200483 ", possibly caused by multiple_routes being disabled.";
deadbeef5c3c1042017-08-04 15:01:57 -0700484 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100485 RTC_LOG(LS_WARNING) << "Dropping connection as TCP socket bound to IP "
Qingsi Wang20232a92019-09-06 12:51:17 -0700486 << socket_address.ipaddr().ToSensitiveString()
Taylor Brandstetter3ba7a572018-03-02 10:58:25 -0800487 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100488 << port_->Network()->ToString();
deadbeef5c3c1042017-08-04 15:01:57 -0700489 OnClose(socket, 0);
490 return;
491 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000492 }
tommi5ce1a2a2016-05-14 03:19:31 -0700493
494 // Connection is established successfully.
495 set_connected(true);
496 connection_pending_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000497}
498
499void TCPConnection::OnClose(rtc::AsyncPacketSocket* socket, int error) {
Tommi9095e0e2022-07-19 12:46:51 +0200500 RTC_DCHECK_EQ(socket, socket_.get());
Yves Gerey665174f2018-06-19 15:03:05 +0200501 RTC_LOG(LS_INFO) << ToString() << ": Connection closed with error " << error;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700502
Tommi9095e0e2022-07-19 12:46:51 +0200503 if (!port_) {
504 RTC_LOG(LS_ERROR) << "TCPConnection: Port has been deleted.";
505 return;
506 }
Tommi6fd77f32022-06-09 21:45:56 +0200507
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700508 // Guard against the condition where IPC socket will call OnClose for every
509 // packet it can't send.
510 if (connected()) {
511 set_connected(false);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700512
513 // Prevent the connection from being destroyed by redundant SignalClose
514 // events.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700515 pretending_to_be_writable_ = true;
516
Mirko Bonadei0cb1cfa2022-02-25 10:45:32 +0000517 // If this connection can't become connected and writable again in 5
518 // seconds, it's time to tear this down. This is the case for the original
519 // TCP connection on passive side during a reconnect.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700520 // We don't attempt reconnect right here. This is to avoid a case where the
521 // shutdown is intentional and reconnect is not necessary. We only reconnect
522 // when the connection is used to Send() or Ping().
Tommi1043fcd2022-05-26 13:54:35 +0200523 network_thread()->PostDelayedTask(
Danil Chapovalov7b190362022-07-07 14:13:02 +0200524 SafeTask(network_safety_.flag(),
525 [this]() {
526 if (pretending_to_be_writable_) {
527 Destroy();
528 }
529 }),
530 TimeDelta::Millis(reconnection_timeout()));
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700531 } else if (!pretending_to_be_writable_) {
532 // OnClose could be called when the underneath socket times out during the
Artem Titov2dbb4c92021-07-26 15:12:41 +0200533 // initial connect() (i.e. `pretending_to_be_writable_` is false) . We have
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700534 // to manually destroy here as this connection, as never connected, will not
535 // be scheduled for ping to trigger destroy.
Tomas Gunnarssonf15189d2022-04-13 09:03:52 +0000536 socket_->UnsubscribeClose(this);
Tommi6fd77f32022-06-09 21:45:56 +0200537 port()->DestroyConnectionAsync(this);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700538 }
539}
540
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700541void TCPConnection::MaybeReconnect() {
542 // Only reconnect for an outgoing TCPConnection when OnClose was signaled and
543 // no outstanding reconnect is pending.
544 if (connected() || connection_pending_ || !outgoing_) {
545 return;
546 }
547
Jonas Olssond7d762d2018-03-28 09:47:51 +0200548 RTC_LOG(LS_INFO) << ToString()
549 << ": TCP Connection with remote is closed, "
550 "trying to reconnect";
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700551
552 CreateOutgoingTcpSocket();
553 error_ = EPIPE;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000554}
555
Yves Gerey665174f2018-06-19 15:03:05 +0200556void TCPConnection::OnReadPacket(rtc::AsyncPacketSocket* socket,
557 const char* data,
558 size_t size,
559 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +0100560 const int64_t& packet_time_us) {
Tommi9095e0e2022-07-19 12:46:51 +0200561 RTC_DCHECK_EQ(socket, socket_.get());
Niels Möllere6933812018-11-05 13:01:41 +0100562 Connection::OnReadPacket(data, size, packet_time_us);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000563}
564
565void TCPConnection::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
Tommi9095e0e2022-07-19 12:46:51 +0200566 RTC_DCHECK_EQ(socket, socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000567 Connection::OnReadyToSend();
568}
569
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700570void TCPConnection::CreateOutgoingTcpSocket() {
nisseede5da42017-01-12 05:15:36 -0800571 RTC_DCHECK(outgoing_);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700572 int opts = (remote_candidate().protocol() == SSLTCP_PROTOCOL_NAME)
hnsl04833622017-01-09 08:35:45 -0800573 ? rtc::PacketSocketFactory::OPT_TLS_FAKE
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700574 : 0;
Tomas Gunnarssonf15189d2022-04-13 09:03:52 +0000575
576 if (socket_) {
577 socket_->UnsubscribeClose(this);
578 }
579
Patrik Höglund662e31f2019-09-05 14:35:04 +0200580 rtc::PacketSocketTcpOptions tcp_opts;
581 tcp_opts.opts = opts;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700582 socket_.reset(port()->socket_factory()->CreateClientTcpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -0700583 rtc::SocketAddress(port()->Network()->GetBestIP(), 0),
584 remote_candidate().address(), port()->proxy(), port()->user_agent(),
Patrik Höglund662e31f2019-09-05 14:35:04 +0200585 tcp_opts));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700586 if (socket_) {
Yves Gerey665174f2018-06-19 15:03:05 +0200587 RTC_LOG(LS_VERBOSE) << ToString() << ": Connecting from "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200588 << socket_->GetLocalAddress().ToSensitiveString()
589 << " to "
590 << remote_candidate().address().ToSensitiveString();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700591 set_connected(false);
592 connection_pending_ = true;
593 ConnectSocketSignals(socket_.get());
594 } else {
Yves Gerey665174f2018-06-19 15:03:05 +0200595 RTC_LOG(LS_WARNING) << ToString() << ": Failed to create connection to "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200596 << remote_candidate().address().ToSensitiveString();
Mirko Bonadei0cb1cfa2022-02-25 10:45:32 +0000597 set_state(IceCandidatePairState::FAILED);
Jonas Oreland7a284e12020-01-28 09:21:54 +0100598 // We can't FailAndPrune directly here. FailAndPrune and deletes all
599 // the StunRequests from the request_map_. And if this is in the stack
600 // of Connection::Ping(), we are still using the request.
601 // Unwind the stack and defer the FailAndPrune.
Tommi1043fcd2022-05-26 13:54:35 +0200602 network_thread()->PostTask(
Danil Chapovalov7b190362022-07-07 14:13:02 +0200603 SafeTask(network_safety_.flag(), [this]() { FailAndPrune(); }));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700604 }
605}
606
607void TCPConnection::ConnectSocketSignals(rtc::AsyncPacketSocket* socket) {
608 if (outgoing_) {
609 socket->SignalConnect.connect(this, &TCPConnection::OnConnect);
610 }
611 socket->SignalReadPacket.connect(this, &TCPConnection::OnReadPacket);
612 socket->SignalReadyToSend.connect(this, &TCPConnection::OnReadyToSend);
Tommi1043fcd2022-05-26 13:54:35 +0200613 socket->SubscribeClose(this, [this, safety = network_safety_.flag()](
614 rtc::AsyncPacketSocket* s, int err) {
615 if (safety->alive())
616 OnClose(s, err);
617 });
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700618}
619
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000620} // namespace cricket