blob: 87165ac73f490eaa7c35e10252b8e692d8ef77f8 [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"
Artem Titovc374d112022-06-16 21:27:45 +020077#include "api/task_queue/to_queued_task.h"
Steve Anton10542f22019-01-11 09:11:00 -080078#include "p2p/base/p2p_constants.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020079#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080080#include "rtc_base/ip_address.h"
Yves Gerey3e707812018-11-28 16:47:49 +010081#include "rtc_base/location.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 {
88
89TCPPort::TCPPort(rtc::Thread* thread,
90 rtc::PacketSocketFactory* factory,
Niels Möllere0c6bdf2022-03-24 15:18:02 +010091 const rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +020092 uint16_t min_port,
93 uint16_t max_port,
Ali Tofighde2ac5a2022-06-30 11:58:26 +020094 absl::string_view username,
95 absl::string_view password,
Jonas Orelandc06fe8b2022-03-28 14:58:26 +020096 bool allow_listen,
Jonas Orelande62c2f22022-03-29 11:04:48 +020097 const webrtc::FieldTrialsView* field_trials)
Peter Boström0c4e06b2015-10-07 12:23:21 +020098 : Port(thread,
99 LOCAL_PORT_TYPE,
100 factory,
101 network,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200102 min_port,
103 max_port,
104 username,
Jonas Orelandc06fe8b2022-03-28 14:58:26 +0200105 password,
106 field_trials),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000107 allow_listen_(allow_listen),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000108 error_(0) {
109 // TODO(mallinath) - Set preference value as per RFC 6544.
110 // http://b/issue?id=7141794
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000111 if (allow_listen_) {
deadbeef1ee21252017-06-13 15:49:45 -0700112 TryCreateServerSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000113 }
Niels Möller646fddc2021-11-02 15:56:05 +0100114 // Set TCP_NODELAY (via OPT_NODELAY) for improved performance; this causes
115 // small media packets to be sent immediately rather than being buffered up,
116 // reducing latency.
117 SetOption(rtc::Socket::OPT_NODELAY, 1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000118}
119
120TCPPort::~TCPPort() {
Niels Möller6d19d142021-10-06 11:19:03 +0200121 listen_socket_ = nullptr;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000122 std::list<Incoming>::iterator it;
123 for (it = incoming_.begin(); it != incoming_.end(); ++it)
124 delete it->socket;
125 incoming_.clear();
126}
127
128Connection* TCPPort::CreateConnection(const Candidate& address,
129 CandidateOrigin origin) {
Honghai Zhangf9945b22015-12-15 12:20:13 -0800130 if (!SupportsProtocol(address.protocol())) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000131 return NULL;
132 }
133
Philipp Hanckee283d1c2020-03-27 09:56:51 +0100134 if ((address.tcptype() == TCPTYPE_ACTIVE_STR &&
135 address.type() != PRFLX_PORT_TYPE) ||
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000136 (address.tcptype().empty() && address.address().port() == 0)) {
137 // It's active only candidate, we should not try to create connections
138 // for these candidates.
139 return NULL;
140 }
141
142 // We can't accept TCP connections incoming on other ports
143 if (origin == ORIGIN_OTHER_PORT)
144 return NULL;
145
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000146 // We don't know how to act as an ssl server yet
147 if ((address.protocol() == SSLTCP_PROTOCOL_NAME) &&
148 (origin == ORIGIN_THIS_PORT)) {
149 return NULL;
150 }
151
152 if (!IsCompatibleAddress(address.address())) {
153 return NULL;
154 }
155
156 TCPConnection* conn = NULL;
Yves Gerey665174f2018-06-19 15:03:05 +0200157 if (rtc::AsyncPacketSocket* socket = GetIncoming(address.address(), true)) {
deadbeef06878292017-04-21 14:22:23 -0700158 // Incoming connection; we already created a socket and connected signals,
159 // so we need to hand off the "read packet" responsibility to
160 // TCPConnection.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000161 socket->SignalReadPacket.disconnect(this);
Tommid7e5cfb2022-03-30 20:13:06 +0200162 conn = new TCPConnection(NewWeakPtr(), address, socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000163 } else {
deadbeef06878292017-04-21 14:22:23 -0700164 // Outgoing connection, which will create a new socket for which we still
165 // need to connect SignalReadyToSend and SignalSentPacket.
Tommid7e5cfb2022-03-30 20:13:06 +0200166 conn = new TCPConnection(NewWeakPtr(), address);
deadbeef06878292017-04-21 14:22:23 -0700167 if (conn->socket()) {
168 conn->socket()->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
169 conn->socket()->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
170 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000171 }
honghaiz36f50e82016-06-01 15:57:03 -0700172 AddOrReplaceConnection(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000173 return conn;
174}
175
176void TCPPort::PrepareAddress() {
Niels Möller6d19d142021-10-06 11:19:03 +0200177 if (listen_socket_) {
Niels Möller4a1c2c42021-09-28 10:17:07 +0200178 // Socket may be in the CLOSED state if Listen()
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000179 // failed, we still want to add the socket address.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100180 RTC_LOG(LS_VERBOSE) << "Preparing TCP address, current state: "
Niels Möllerd30ece12021-10-19 10:11:02 +0200181 << static_cast<int>(listen_socket_->GetState());
182 AddAddress(listen_socket_->GetLocalAddress(),
183 listen_socket_->GetLocalAddress(), rtc::SocketAddress(),
184 TCP_PROTOCOL_NAME, "", TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE,
185 ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000186 } else {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200187 RTC_LOG(LS_INFO) << ToString()
188 << ": Not listening due to firewall restrictions.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000189 // Note: We still add the address, since otherwise the remote side won't
Guo-wei Shieh310b0932015-11-17 19:15:50 -0800190 // recognize our incoming TCP connections. According to
191 // https://tools.ietf.org/html/rfc6544#section-4.5, for active candidate,
deadbeef5c3c1042017-08-04 15:01:57 -0700192 // the port must be set to the discard port, i.e. 9. We can't be 100% sure
193 // which IP address will actually be used, so GetBestIP is as good as we
194 // can do.
195 // TODO(deadbeef): We could do something like create a dummy socket just to
196 // see what IP we get. But that may be overkill.
197 AddAddress(rtc::SocketAddress(Network()->GetBestIP(), DISCARD_PORT),
198 rtc::SocketAddress(Network()->GetBestIP(), 0),
199 rtc::SocketAddress(), TCP_PROTOCOL_NAME, "", TCPTYPE_ACTIVE_STR,
200 LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000201 }
202}
203
Yves Gerey665174f2018-06-19 15:03:05 +0200204int TCPPort::SendTo(const void* data,
205 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000206 const rtc::SocketAddress& addr,
207 const rtc::PacketOptions& options,
208 bool payload) {
Yves Gerey665174f2018-06-19 15:03:05 +0200209 rtc::AsyncPacketSocket* socket = NULL;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700210 TCPConnection* conn = static_cast<TCPConnection*>(GetConnection(addr));
211
212 // For Connection, this is the code path used by Ping() to establish
213 // WRITABLE. It has to send through the socket directly as TCPConnection::Send
214 // checks writability.
215 if (conn) {
216 if (!conn->connected()) {
217 conn->MaybeReconnect();
218 return SOCKET_ERROR;
219 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000220 socket = conn->socket();
Harald Alvestranddc800172020-01-06 20:01:36 +0100221 if (!socket) {
222 // The failure to initialize should have been logged elsewhere,
223 // so this log is not important.
224 RTC_LOG(LS_INFO) << ToString()
225 << ": Attempted to send to an uninitialized socket: "
226 << addr.ToSensitiveString();
227 error_ = EHOSTUNREACH;
228 return SOCKET_ERROR;
229 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000230 } else {
231 socket = GetIncoming(addr);
Harald Alvestranddc800172020-01-06 20:01:36 +0100232 if (!socket) {
233 RTC_LOG(LS_ERROR) << ToString()
234 << ": Attempted to send to an unknown destination: "
235 << addr.ToSensitiveString();
236 error_ = EHOSTUNREACH;
237 return SOCKET_ERROR;
238 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000239 }
Qingsi Wang6e641e62018-04-11 20:14:17 -0700240 rtc::PacketOptions modified_options(options);
241 CopyPortInformationToPacketInfo(&modified_options.info_signaled_after_sent);
242 int sent = socket->Send(data, size, modified_options);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000243 if (sent < 0) {
244 error_ = socket->GetError();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700245 // Error from this code path for a Connection (instead of from a bare
246 // socket) will not trigger reconnecting. In theory, this shouldn't matter
247 // as OnClose should always be called and set connected to false.
Yves Gerey665174f2018-06-19 15:03:05 +0200248 RTC_LOG(LS_ERROR) << ToString() << ": TCP send of " << size
249 << " bytes failed with error " << error_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000250 }
251 return sent;
252}
253
254int TCPPort::GetOption(rtc::Socket::Option opt, int* value) {
Niels Möller646fddc2021-11-02 15:56:05 +0100255 auto const& it = socket_options_.find(opt);
256 if (it == socket_options_.end()) {
257 return -1;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000258 }
Niels Möller646fddc2021-11-02 15:56:05 +0100259 *value = it->second;
260 return 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000261}
262
263int TCPPort::SetOption(rtc::Socket::Option opt, int value) {
Niels Möller646fddc2021-11-02 15:56:05 +0100264 socket_options_[opt] = value;
265 return 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000266}
267
268int TCPPort::GetError() {
269 return error_;
270}
271
Ali Tofighea5a9442022-06-14 15:20:15 +0200272bool TCPPort::SupportsProtocol(absl::string_view protocol) const {
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700273 return protocol == TCP_PROTOCOL_NAME || protocol == SSLTCP_PROTOCOL_NAME;
274}
275
276ProtocolType TCPPort::GetProtocol() const {
277 return PROTO_TCP;
278}
279
Niels Möller6d19d142021-10-06 11:19:03 +0200280void TCPPort::OnNewConnection(rtc::AsyncListenSocket* socket,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000281 rtc::AsyncPacketSocket* new_socket) {
Niels Möller6d19d142021-10-06 11:19:03 +0200282 RTC_DCHECK(socket == listen_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000283
Niels Möller646fddc2021-11-02 15:56:05 +0100284 for (const auto& option : socket_options_) {
285 new_socket->SetOption(option.first, option.second);
286 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000287 Incoming incoming;
288 incoming.addr = new_socket->GetRemoteAddress();
289 incoming.socket = new_socket;
290 incoming.socket->SignalReadPacket.connect(this, &TCPPort::OnReadPacket);
291 incoming.socket->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
Stefan Holmer55674ff2016-01-14 15:49:16 +0100292 incoming.socket->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000293
Yves Gerey665174f2018-06-19 15:03:05 +0200294 RTC_LOG(LS_VERBOSE) << ToString() << ": Accepted connection from "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200295 << incoming.addr.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000296 incoming_.push_back(incoming);
297}
298
deadbeef1ee21252017-06-13 15:49:45 -0700299void TCPPort::TryCreateServerSocket() {
Niels Möller6d19d142021-10-06 11:19:03 +0200300 listen_socket_ = absl::WrapUnique(socket_factory()->CreateServerTcpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -0700301 rtc::SocketAddress(Network()->GetBestIP(), 0), min_port(), max_port(),
Niels Möller6d19d142021-10-06 11:19:03 +0200302 false /* ssl */));
303 if (!listen_socket_) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200304 RTC_LOG(LS_WARNING)
305 << ToString()
306 << ": TCP server socket creation failed; continuing anyway.";
deadbeef1ee21252017-06-13 15:49:45 -0700307 return;
308 }
Niels Möller6d19d142021-10-06 11:19:03 +0200309 listen_socket_->SignalNewConnection.connect(this, &TCPPort::OnNewConnection);
deadbeef1ee21252017-06-13 15:49:45 -0700310}
311
Yves Gerey665174f2018-06-19 15:03:05 +0200312rtc::AsyncPacketSocket* TCPPort::GetIncoming(const rtc::SocketAddress& addr,
313 bool remove) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000314 rtc::AsyncPacketSocket* socket = NULL;
315 for (std::list<Incoming>::iterator it = incoming_.begin();
316 it != incoming_.end(); ++it) {
317 if (it->addr == addr) {
318 socket = it->socket;
319 if (remove)
320 incoming_.erase(it);
321 break;
322 }
323 }
324 return socket;
325}
326
327void TCPPort::OnReadPacket(rtc::AsyncPacketSocket* socket,
Yves Gerey665174f2018-06-19 15:03:05 +0200328 const char* data,
329 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000330 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +0100331 const int64_t& packet_time_us) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000332 Port::OnReadPacket(data, size, remote_addr, PROTO_TCP);
333}
334
Stefan Holmer55674ff2016-01-14 15:49:16 +0100335void TCPPort::OnSentPacket(rtc::AsyncPacketSocket* socket,
336 const rtc::SentPacket& sent_packet) {
Stefan Holmer55674ff2016-01-14 15:49:16 +0100337 PortInterface::SignalSentPacket(sent_packet);
338}
339
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000340void TCPPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
341 Port::OnReadyToSend();
342}
343
Artem Titov2dbb4c92021-07-26 15:12:41 +0200344// TODO(qingsi): `CONNECTION_WRITE_CONNECT_TIMEOUT` is overriden by
345// `ice_unwritable_timeout` in IceConfig when determining the writability state.
Qingsi Wang22e623a2018-03-13 10:53:57 -0700346// Replace this constant with the config parameter assuming the default value if
347// we decide it is also applicable here.
Tommid7e5cfb2022-03-30 20:13:06 +0200348TCPConnection::TCPConnection(rtc::WeakPtr<Port> tcp_port,
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700349 const Candidate& candidate,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000350 rtc::AsyncPacketSocket* socket)
Tommid7e5cfb2022-03-30 20:13:06 +0200351 : Connection(std::move(tcp_port), 0, candidate),
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700352 socket_(socket),
353 error_(0),
354 outgoing_(socket == NULL),
355 connection_pending_(false),
356 pretending_to_be_writable_(false),
357 reconnection_timeout_(cricket::CONNECTION_WRITE_CONNECT_TIMEOUT) {
Tommid7e5cfb2022-03-30 20:13:06 +0200358 RTC_DCHECK_EQ(port()->GetProtocol(), PROTO_TCP); // Needs to be TCPPort.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700359 if (outgoing_) {
360 CreateOutgoingTcpSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000361 } else {
deadbeef5c3c1042017-08-04 15:01:57 -0700362 // Incoming connections should match one of the network addresses. Same as
363 // what's being checked in OnConnect, but just DCHECKing here.
Jonas Olssond7d762d2018-03-28 09:47:51 +0200364 RTC_LOG(LS_VERBOSE) << ToString() << ": socket ipaddr: "
Qingsi Wang20232a92019-09-06 12:51:17 -0700365 << socket_->GetLocalAddress().ToSensitiveString()
Tommid7e5cfb2022-03-30 20:13:06 +0200366 << ", port() Network:" << port()->Network()->ToString();
Steve Antonae226f62019-01-29 12:47:38 -0800367 RTC_DCHECK(absl::c_any_of(
368 port_->Network()->GetIPs(), [this](const rtc::InterfaceAddress& addr) {
369 return socket_->GetLocalAddress().ipaddr() == addr;
370 }));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700371 ConnectSocketSignals(socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000372 }
373}
374
Mirko Bonadei0cb1cfa2022-02-25 10:45:32 +0000375TCPConnection::~TCPConnection() {
376 RTC_DCHECK_RUN_ON(network_thread_);
377}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000378
Yves Gerey665174f2018-06-19 15:03:05 +0200379int TCPConnection::Send(const void* data,
380 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000381 const rtc::PacketOptions& options) {
382 if (!socket_) {
383 error_ = ENOTCONN;
384 return SOCKET_ERROR;
385 }
386
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700387 // Sending after OnClose on active side will trigger a reconnect for a
388 // outgoing connection. Note that the write state is still WRITABLE as we want
389 // to spend a few seconds attempting a reconnect before saying we're
390 // unwritable.
391 if (!connected()) {
392 MaybeReconnect();
393 return SOCKET_ERROR;
394 }
395
396 // Note that this is important to put this after the previous check to give
397 // the connection a chance to reconnect.
398 if (pretending_to_be_writable_ || write_state() != STATE_WRITABLE) {
Steve Anton6c38cc72017-11-29 10:25:58 -0800399 // TODO(?): Should STATE_WRITE_TIMEOUT return a non-blocking error?
skvladc309e0e2016-07-28 17:15:20 -0700400 error_ = ENOTCONN;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000401 return SOCKET_ERROR;
402 }
zhihuang5ecf16c2016-06-01 17:09:15 -0700403 stats_.sent_total_packets++;
Qingsi Wang6e641e62018-04-11 20:14:17 -0700404 rtc::PacketOptions modified_options(options);
Tommid7e5cfb2022-03-30 20:13:06 +0200405 tcp_port()->CopyPortInformationToPacketInfo(
Qingsi Wang6e641e62018-04-11 20:14:17 -0700406 &modified_options.info_signaled_after_sent);
407 int sent = socket_->Send(data, size, modified_options);
Jonas Oreland3c5d5822020-12-14 12:45:05 +0100408 int64_t now = rtc::TimeMillis();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000409 if (sent < 0) {
zhihuang5ecf16c2016-06-01 17:09:15 -0700410 stats_.sent_discarded_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000411 error_ = socket_->GetError();
412 } else {
Jonas Oreland3c5d5822020-12-14 12:45:05 +0100413 send_rate_tracker_.AddSamplesAtTime(now, sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000414 }
Jonas Oreland3c5d5822020-12-14 12:45:05 +0100415 last_send_data_ = now;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000416 return sent;
417}
418
419int TCPConnection::GetError() {
420 return error_;
421}
422
Tommic85e4732022-05-27 16:37:42 +0200423void TCPConnection::OnConnectionRequestResponse(StunRequest* req,
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700424 StunMessage* response) {
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700425 // Process the STUN response before we inform upper layer ready to send.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700426 Connection::OnConnectionRequestResponse(req, response);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700427
428 // If we're in the state of pretending to be writeable, we should inform the
429 // upper layer it's ready to send again as previous EWOULDLBLOCK from socket
430 // would have stopped the outgoing stream.
431 if (pretending_to_be_writable_) {
432 Connection::OnReadyToSend();
433 }
434 pretending_to_be_writable_ = false;
nisseede5da42017-01-12 05:15:36 -0800435 RTC_DCHECK(write_state() == STATE_WRITABLE);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700436}
437
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000438void TCPConnection::OnConnect(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800439 RTC_DCHECK(socket == socket_.get());
deadbeef5c3c1042017-08-04 15:01:57 -0700440 // Do not use this port if the socket bound to an address not associated with
441 // the desired network interface. This is seen in Chrome, where TCP sockets
442 // cannot be given a binding address, and the platform is expected to pick
443 // the correct local address.
444 //
445 // However, there are two situations in which we allow the bound address to
446 // not be one of the addresses of the requested interface:
447 // 1. The bound address is the loopback address. This happens when a proxy
448 // forces TCP to bind to only the localhost address (see issue 3927).
449 // 2. The bound address is the "any address". This happens when
450 // multiple_routes is disabled (see issue 4780).
451 //
452 // Note that, aside from minor differences in log statements, this logic is
453 // identical to that in TurnPort.
454 const rtc::SocketAddress& socket_address = socket->GetLocalAddress();
Steve Antonae226f62019-01-29 12:47:38 -0800455 if (absl::c_any_of(port_->Network()->GetIPs(),
456 [socket_address](const rtc::InterfaceAddress& addr) {
457 return socket_address.ipaddr() == addr;
458 })) {
Yves Gerey665174f2018-06-19 15:03:05 +0200459 RTC_LOG(LS_VERBOSE) << ToString() << ": Connection established to "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200460 << socket->GetRemoteAddress().ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000461 } else {
deadbeef5c3c1042017-08-04 15:01:57 -0700462 if (socket->GetLocalAddress().IsLoopbackIP()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100463 RTC_LOG(LS_WARNING) << "Socket is bound to the address:"
Qingsi Wang20232a92019-09-06 12:51:17 -0700464 << socket_address.ipaddr().ToSensitiveString()
Taylor Brandstetter3ba7a572018-03-02 10:58:25 -0800465 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100466 << port_->Network()->ToString()
467 << ". Still allowing it since it's localhost.";
deadbeef5c3c1042017-08-04 15:01:57 -0700468 } else if (IPIsAny(port_->Network()->GetBestIP())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100469 RTC_LOG(LS_WARNING)
470 << "Socket is bound to the address:"
Qingsi Wang20232a92019-09-06 12:51:17 -0700471 << socket_address.ipaddr().ToSensitiveString()
Taylor Brandstetter3ba7a572018-03-02 10:58:25 -0800472 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100473 << port_->Network()->ToString()
474 << ". Still allowing it since it's the 'any' address"
Jonas Olssond7d762d2018-03-28 09:47:51 +0200475 ", possibly caused by multiple_routes being disabled.";
deadbeef5c3c1042017-08-04 15:01:57 -0700476 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100477 RTC_LOG(LS_WARNING) << "Dropping connection as TCP socket bound to IP "
Qingsi Wang20232a92019-09-06 12:51:17 -0700478 << socket_address.ipaddr().ToSensitiveString()
Taylor Brandstetter3ba7a572018-03-02 10:58:25 -0800479 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100480 << port_->Network()->ToString();
deadbeef5c3c1042017-08-04 15:01:57 -0700481 OnClose(socket, 0);
482 return;
483 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000484 }
tommi5ce1a2a2016-05-14 03:19:31 -0700485
486 // Connection is established successfully.
487 set_connected(true);
488 connection_pending_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000489}
490
491void TCPConnection::OnClose(rtc::AsyncPacketSocket* socket, int error) {
nisseede5da42017-01-12 05:15:36 -0800492 RTC_DCHECK(socket == socket_.get());
Yves Gerey665174f2018-06-19 15:03:05 +0200493 RTC_LOG(LS_INFO) << ToString() << ": Connection closed with error " << error;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700494
Tommi6fd77f32022-06-09 21:45:56 +0200495 RTC_DCHECK(port());
496
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700497 // Guard against the condition where IPC socket will call OnClose for every
498 // packet it can't send.
499 if (connected()) {
500 set_connected(false);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700501
502 // Prevent the connection from being destroyed by redundant SignalClose
503 // events.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700504 pretending_to_be_writable_ = true;
505
Mirko Bonadei0cb1cfa2022-02-25 10:45:32 +0000506 // If this connection can't become connected and writable again in 5
507 // seconds, it's time to tear this down. This is the case for the original
508 // TCP connection on passive side during a reconnect.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700509 // We don't attempt reconnect right here. This is to avoid a case where the
510 // shutdown is intentional and reconnect is not necessary. We only reconnect
511 // when the connection is used to Send() or Ping().
Tommi1043fcd2022-05-26 13:54:35 +0200512 network_thread()->PostDelayedTask(
Mirko Bonadei0cb1cfa2022-02-25 10:45:32 +0000513 webrtc::ToQueuedTask(network_safety_,
514 [this]() {
Tomas Gunnarsson869c87a2022-05-02 19:08:43 +0000515 if (pretending_to_be_writable_) {
516 Destroy();
517 }
Mirko Bonadei0cb1cfa2022-02-25 10:45:32 +0000518 }),
519 reconnection_timeout());
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700520 } else if (!pretending_to_be_writable_) {
521 // OnClose could be called when the underneath socket times out during the
Artem Titov2dbb4c92021-07-26 15:12:41 +0200522 // initial connect() (i.e. `pretending_to_be_writable_` is false) . We have
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700523 // to manually destroy here as this connection, as never connected, will not
524 // be scheduled for ping to trigger destroy.
Tomas Gunnarssonf15189d2022-04-13 09:03:52 +0000525 socket_->UnsubscribeClose(this);
Tommi6fd77f32022-06-09 21:45:56 +0200526 port()->DestroyConnectionAsync(this);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700527 }
528}
529
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700530void TCPConnection::MaybeReconnect() {
531 // Only reconnect for an outgoing TCPConnection when OnClose was signaled and
532 // no outstanding reconnect is pending.
533 if (connected() || connection_pending_ || !outgoing_) {
534 return;
535 }
536
Jonas Olssond7d762d2018-03-28 09:47:51 +0200537 RTC_LOG(LS_INFO) << ToString()
538 << ": TCP Connection with remote is closed, "
539 "trying to reconnect";
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700540
541 CreateOutgoingTcpSocket();
542 error_ = EPIPE;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000543}
544
Yves Gerey665174f2018-06-19 15:03:05 +0200545void TCPConnection::OnReadPacket(rtc::AsyncPacketSocket* socket,
546 const char* data,
547 size_t size,
548 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +0100549 const int64_t& packet_time_us) {
nisseede5da42017-01-12 05:15:36 -0800550 RTC_DCHECK(socket == socket_.get());
Niels Möllere6933812018-11-05 13:01:41 +0100551 Connection::OnReadPacket(data, size, packet_time_us);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000552}
553
554void TCPConnection::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800555 RTC_DCHECK(socket == socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000556 Connection::OnReadyToSend();
557}
558
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700559void TCPConnection::CreateOutgoingTcpSocket() {
nisseede5da42017-01-12 05:15:36 -0800560 RTC_DCHECK(outgoing_);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700561 int opts = (remote_candidate().protocol() == SSLTCP_PROTOCOL_NAME)
hnsl04833622017-01-09 08:35:45 -0800562 ? rtc::PacketSocketFactory::OPT_TLS_FAKE
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700563 : 0;
Tomas Gunnarssonf15189d2022-04-13 09:03:52 +0000564
565 if (socket_) {
566 socket_->UnsubscribeClose(this);
567 }
568
Patrik Höglund662e31f2019-09-05 14:35:04 +0200569 rtc::PacketSocketTcpOptions tcp_opts;
570 tcp_opts.opts = opts;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700571 socket_.reset(port()->socket_factory()->CreateClientTcpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -0700572 rtc::SocketAddress(port()->Network()->GetBestIP(), 0),
573 remote_candidate().address(), port()->proxy(), port()->user_agent(),
Patrik Höglund662e31f2019-09-05 14:35:04 +0200574 tcp_opts));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700575 if (socket_) {
Yves Gerey665174f2018-06-19 15:03:05 +0200576 RTC_LOG(LS_VERBOSE) << ToString() << ": Connecting from "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200577 << socket_->GetLocalAddress().ToSensitiveString()
578 << " to "
579 << remote_candidate().address().ToSensitiveString();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700580 set_connected(false);
581 connection_pending_ = true;
582 ConnectSocketSignals(socket_.get());
583 } else {
Yves Gerey665174f2018-06-19 15:03:05 +0200584 RTC_LOG(LS_WARNING) << ToString() << ": Failed to create connection to "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200585 << remote_candidate().address().ToSensitiveString();
Mirko Bonadei0cb1cfa2022-02-25 10:45:32 +0000586 set_state(IceCandidatePairState::FAILED);
Jonas Oreland7a284e12020-01-28 09:21:54 +0100587 // We can't FailAndPrune directly here. FailAndPrune and deletes all
588 // the StunRequests from the request_map_. And if this is in the stack
589 // of Connection::Ping(), we are still using the request.
590 // Unwind the stack and defer the FailAndPrune.
Tommi1043fcd2022-05-26 13:54:35 +0200591 network_thread()->PostTask(
Mirko Bonadei0cb1cfa2022-02-25 10:45:32 +0000592 webrtc::ToQueuedTask(network_safety_, [this]() { FailAndPrune(); }));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700593 }
594}
595
596void TCPConnection::ConnectSocketSignals(rtc::AsyncPacketSocket* socket) {
597 if (outgoing_) {
598 socket->SignalConnect.connect(this, &TCPConnection::OnConnect);
599 }
600 socket->SignalReadPacket.connect(this, &TCPConnection::OnReadPacket);
601 socket->SignalReadyToSend.connect(this, &TCPConnection::OnReadyToSend);
Tommi1043fcd2022-05-26 13:54:35 +0200602 socket->SubscribeClose(this, [this, safety = network_safety_.flag()](
603 rtc::AsyncPacketSocket* s, int err) {
604 if (safety->alive())
605 OnClose(s, err);
606 });
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700607}
608
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000609} // namespace cricket