blob: 52f74e7a10a7457e84df8793d7089aea36e79b18 [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
Steve Anton6c38cc72017-11-29 10:25:58 -080071#include <vector>
72
Steve Antonae226f62019-01-29 12:47:38 -080073#include "absl/algorithm/container.h"
Niels Möller6d19d142021-10-06 11:19:03 +020074#include "absl/memory/memory.h"
Steve Anton10542f22019-01-11 09:11:00 -080075#include "p2p/base/p2p_constants.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020076#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080077#include "rtc_base/ip_address.h"
Yves Gerey3e707812018-11-28 16:47:49 +010078#include "rtc_base/location.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020079#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080080#include "rtc_base/net_helper.h"
81#include "rtc_base/rate_tracker.h"
Mirko Bonadei0cb1cfa2022-02-25 10:45:32 +000082#include "rtc_base/task_utils/to_queued_task.h"
Yves Gerey3e707812018-11-28 16:47:49 +010083#include "rtc_base/third_party/sigslot/sigslot.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000084
85namespace cricket {
86
87TCPPort::TCPPort(rtc::Thread* thread,
88 rtc::PacketSocketFactory* factory,
Niels Möllere0c6bdf2022-03-24 15:18:02 +010089 const rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +020090 uint16_t min_port,
91 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +000092 const std::string& username,
93 const std::string& password,
94 bool allow_listen)
Peter Boström0c4e06b2015-10-07 12:23:21 +020095 : Port(thread,
96 LOCAL_PORT_TYPE,
97 factory,
98 network,
Peter Boström0c4e06b2015-10-07 12:23:21 +020099 min_port,
100 max_port,
101 username,
102 password),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000103 allow_listen_(allow_listen),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000104 error_(0) {
105 // TODO(mallinath) - Set preference value as per RFC 6544.
106 // http://b/issue?id=7141794
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000107 if (allow_listen_) {
deadbeef1ee21252017-06-13 15:49:45 -0700108 TryCreateServerSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000109 }
Niels Möller646fddc2021-11-02 15:56:05 +0100110 // Set TCP_NODELAY (via OPT_NODELAY) for improved performance; this causes
111 // small media packets to be sent immediately rather than being buffered up,
112 // reducing latency.
113 SetOption(rtc::Socket::OPT_NODELAY, 1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000114}
115
116TCPPort::~TCPPort() {
Niels Möller6d19d142021-10-06 11:19:03 +0200117 listen_socket_ = nullptr;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000118 std::list<Incoming>::iterator it;
119 for (it = incoming_.begin(); it != incoming_.end(); ++it)
120 delete it->socket;
121 incoming_.clear();
122}
123
124Connection* TCPPort::CreateConnection(const Candidate& address,
125 CandidateOrigin origin) {
Honghai Zhangf9945b22015-12-15 12:20:13 -0800126 if (!SupportsProtocol(address.protocol())) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000127 return NULL;
128 }
129
Philipp Hanckee283d1c2020-03-27 09:56:51 +0100130 if ((address.tcptype() == TCPTYPE_ACTIVE_STR &&
131 address.type() != PRFLX_PORT_TYPE) ||
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000132 (address.tcptype().empty() && address.address().port() == 0)) {
133 // It's active only candidate, we should not try to create connections
134 // for these candidates.
135 return NULL;
136 }
137
138 // We can't accept TCP connections incoming on other ports
139 if (origin == ORIGIN_OTHER_PORT)
140 return NULL;
141
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000142 // We don't know how to act as an ssl server yet
143 if ((address.protocol() == SSLTCP_PROTOCOL_NAME) &&
144 (origin == ORIGIN_THIS_PORT)) {
145 return NULL;
146 }
147
148 if (!IsCompatibleAddress(address.address())) {
149 return NULL;
150 }
151
152 TCPConnection* conn = NULL;
Yves Gerey665174f2018-06-19 15:03:05 +0200153 if (rtc::AsyncPacketSocket* socket = GetIncoming(address.address(), true)) {
deadbeef06878292017-04-21 14:22:23 -0700154 // Incoming connection; we already created a socket and connected signals,
155 // so we need to hand off the "read packet" responsibility to
156 // TCPConnection.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000157 socket->SignalReadPacket.disconnect(this);
158 conn = new TCPConnection(this, address, socket);
159 } else {
deadbeef06878292017-04-21 14:22:23 -0700160 // Outgoing connection, which will create a new socket for which we still
161 // need to connect SignalReadyToSend and SignalSentPacket.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000162 conn = new TCPConnection(this, address);
deadbeef06878292017-04-21 14:22:23 -0700163 if (conn->socket()) {
164 conn->socket()->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
165 conn->socket()->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
166 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000167 }
honghaiz36f50e82016-06-01 15:57:03 -0700168 AddOrReplaceConnection(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000169 return conn;
170}
171
172void TCPPort::PrepareAddress() {
Niels Möller6d19d142021-10-06 11:19:03 +0200173 if (listen_socket_) {
Niels Möller4a1c2c42021-09-28 10:17:07 +0200174 // Socket may be in the CLOSED state if Listen()
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000175 // failed, we still want to add the socket address.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100176 RTC_LOG(LS_VERBOSE) << "Preparing TCP address, current state: "
Niels Möllerd30ece12021-10-19 10:11:02 +0200177 << static_cast<int>(listen_socket_->GetState());
178 AddAddress(listen_socket_->GetLocalAddress(),
179 listen_socket_->GetLocalAddress(), rtc::SocketAddress(),
180 TCP_PROTOCOL_NAME, "", TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE,
181 ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000182 } else {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200183 RTC_LOG(LS_INFO) << ToString()
184 << ": Not listening due to firewall restrictions.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000185 // Note: We still add the address, since otherwise the remote side won't
Guo-wei Shieh310b0932015-11-17 19:15:50 -0800186 // recognize our incoming TCP connections. According to
187 // https://tools.ietf.org/html/rfc6544#section-4.5, for active candidate,
deadbeef5c3c1042017-08-04 15:01:57 -0700188 // the port must be set to the discard port, i.e. 9. We can't be 100% sure
189 // which IP address will actually be used, so GetBestIP is as good as we
190 // can do.
191 // TODO(deadbeef): We could do something like create a dummy socket just to
192 // see what IP we get. But that may be overkill.
193 AddAddress(rtc::SocketAddress(Network()->GetBestIP(), DISCARD_PORT),
194 rtc::SocketAddress(Network()->GetBestIP(), 0),
195 rtc::SocketAddress(), TCP_PROTOCOL_NAME, "", TCPTYPE_ACTIVE_STR,
196 LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000197 }
198}
199
Yves Gerey665174f2018-06-19 15:03:05 +0200200int TCPPort::SendTo(const void* data,
201 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000202 const rtc::SocketAddress& addr,
203 const rtc::PacketOptions& options,
204 bool payload) {
Yves Gerey665174f2018-06-19 15:03:05 +0200205 rtc::AsyncPacketSocket* socket = NULL;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700206 TCPConnection* conn = static_cast<TCPConnection*>(GetConnection(addr));
207
208 // For Connection, this is the code path used by Ping() to establish
209 // WRITABLE. It has to send through the socket directly as TCPConnection::Send
210 // checks writability.
211 if (conn) {
212 if (!conn->connected()) {
213 conn->MaybeReconnect();
214 return SOCKET_ERROR;
215 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000216 socket = conn->socket();
Harald Alvestranddc800172020-01-06 20:01:36 +0100217 if (!socket) {
218 // The failure to initialize should have been logged elsewhere,
219 // so this log is not important.
220 RTC_LOG(LS_INFO) << ToString()
221 << ": Attempted to send to an uninitialized socket: "
222 << addr.ToSensitiveString();
223 error_ = EHOSTUNREACH;
224 return SOCKET_ERROR;
225 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000226 } else {
227 socket = GetIncoming(addr);
Harald Alvestranddc800172020-01-06 20:01:36 +0100228 if (!socket) {
229 RTC_LOG(LS_ERROR) << ToString()
230 << ": Attempted to send to an unknown destination: "
231 << addr.ToSensitiveString();
232 error_ = EHOSTUNREACH;
233 return SOCKET_ERROR;
234 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000235 }
Qingsi Wang6e641e62018-04-11 20:14:17 -0700236 rtc::PacketOptions modified_options(options);
237 CopyPortInformationToPacketInfo(&modified_options.info_signaled_after_sent);
238 int sent = socket->Send(data, size, modified_options);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000239 if (sent < 0) {
240 error_ = socket->GetError();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700241 // Error from this code path for a Connection (instead of from a bare
242 // socket) will not trigger reconnecting. In theory, this shouldn't matter
243 // as OnClose should always be called and set connected to false.
Yves Gerey665174f2018-06-19 15:03:05 +0200244 RTC_LOG(LS_ERROR) << ToString() << ": TCP send of " << size
245 << " bytes failed with error " << error_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000246 }
247 return sent;
248}
249
250int TCPPort::GetOption(rtc::Socket::Option opt, int* value) {
Niels Möller646fddc2021-11-02 15:56:05 +0100251 auto const& it = socket_options_.find(opt);
252 if (it == socket_options_.end()) {
253 return -1;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000254 }
Niels Möller646fddc2021-11-02 15:56:05 +0100255 *value = it->second;
256 return 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000257}
258
259int TCPPort::SetOption(rtc::Socket::Option opt, int value) {
Niels Möller646fddc2021-11-02 15:56:05 +0100260 socket_options_[opt] = value;
261 return 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000262}
263
264int TCPPort::GetError() {
265 return error_;
266}
267
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700268bool TCPPort::SupportsProtocol(const std::string& protocol) const {
269 return protocol == TCP_PROTOCOL_NAME || protocol == SSLTCP_PROTOCOL_NAME;
270}
271
272ProtocolType TCPPort::GetProtocol() const {
273 return PROTO_TCP;
274}
275
Niels Möller6d19d142021-10-06 11:19:03 +0200276void TCPPort::OnNewConnection(rtc::AsyncListenSocket* socket,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000277 rtc::AsyncPacketSocket* new_socket) {
Niels Möller6d19d142021-10-06 11:19:03 +0200278 RTC_DCHECK(socket == listen_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000279
Niels Möller646fddc2021-11-02 15:56:05 +0100280 for (const auto& option : socket_options_) {
281 new_socket->SetOption(option.first, option.second);
282 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000283 Incoming incoming;
284 incoming.addr = new_socket->GetRemoteAddress();
285 incoming.socket = new_socket;
286 incoming.socket->SignalReadPacket.connect(this, &TCPPort::OnReadPacket);
287 incoming.socket->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
Stefan Holmer55674ff2016-01-14 15:49:16 +0100288 incoming.socket->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000289
Yves Gerey665174f2018-06-19 15:03:05 +0200290 RTC_LOG(LS_VERBOSE) << ToString() << ": Accepted connection from "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200291 << incoming.addr.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000292 incoming_.push_back(incoming);
293}
294
deadbeef1ee21252017-06-13 15:49:45 -0700295void TCPPort::TryCreateServerSocket() {
Niels Möller6d19d142021-10-06 11:19:03 +0200296 listen_socket_ = absl::WrapUnique(socket_factory()->CreateServerTcpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -0700297 rtc::SocketAddress(Network()->GetBestIP(), 0), min_port(), max_port(),
Niels Möller6d19d142021-10-06 11:19:03 +0200298 false /* ssl */));
299 if (!listen_socket_) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200300 RTC_LOG(LS_WARNING)
301 << ToString()
302 << ": TCP server socket creation failed; continuing anyway.";
deadbeef1ee21252017-06-13 15:49:45 -0700303 return;
304 }
Niels Möller6d19d142021-10-06 11:19:03 +0200305 listen_socket_->SignalNewConnection.connect(this, &TCPPort::OnNewConnection);
deadbeef1ee21252017-06-13 15:49:45 -0700306}
307
Yves Gerey665174f2018-06-19 15:03:05 +0200308rtc::AsyncPacketSocket* TCPPort::GetIncoming(const rtc::SocketAddress& addr,
309 bool remove) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000310 rtc::AsyncPacketSocket* socket = NULL;
311 for (std::list<Incoming>::iterator it = incoming_.begin();
312 it != incoming_.end(); ++it) {
313 if (it->addr == addr) {
314 socket = it->socket;
315 if (remove)
316 incoming_.erase(it);
317 break;
318 }
319 }
320 return socket;
321}
322
323void TCPPort::OnReadPacket(rtc::AsyncPacketSocket* socket,
Yves Gerey665174f2018-06-19 15:03:05 +0200324 const char* data,
325 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000326 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +0100327 const int64_t& packet_time_us) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000328 Port::OnReadPacket(data, size, remote_addr, PROTO_TCP);
329}
330
Stefan Holmer55674ff2016-01-14 15:49:16 +0100331void TCPPort::OnSentPacket(rtc::AsyncPacketSocket* socket,
332 const rtc::SentPacket& sent_packet) {
Stefan Holmer55674ff2016-01-14 15:49:16 +0100333 PortInterface::SignalSentPacket(sent_packet);
334}
335
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000336void TCPPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
337 Port::OnReadyToSend();
338}
339
Artem Titov2dbb4c92021-07-26 15:12:41 +0200340// TODO(qingsi): `CONNECTION_WRITE_CONNECT_TIMEOUT` is overriden by
341// `ice_unwritable_timeout` in IceConfig when determining the writability state.
Qingsi Wang22e623a2018-03-13 10:53:57 -0700342// Replace this constant with the config parameter assuming the default value if
343// we decide it is also applicable here.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700344TCPConnection::TCPConnection(TCPPort* port,
345 const Candidate& candidate,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000346 rtc::AsyncPacketSocket* socket)
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700347 : Connection(port, 0, candidate),
348 socket_(socket),
349 error_(0),
350 outgoing_(socket == NULL),
351 connection_pending_(false),
352 pretending_to_be_writable_(false),
353 reconnection_timeout_(cricket::CONNECTION_WRITE_CONNECT_TIMEOUT) {
354 if (outgoing_) {
355 CreateOutgoingTcpSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000356 } else {
deadbeef5c3c1042017-08-04 15:01:57 -0700357 // Incoming connections should match one of the network addresses. Same as
358 // what's being checked in OnConnect, but just DCHECKing here.
Jonas Olssond7d762d2018-03-28 09:47:51 +0200359 RTC_LOG(LS_VERBOSE) << ToString() << ": socket ipaddr: "
Qingsi Wang20232a92019-09-06 12:51:17 -0700360 << socket_->GetLocalAddress().ToSensitiveString()
Jonas Olssond7d762d2018-03-28 09:47:51 +0200361 << ", port() Network:" << port->Network()->ToString();
Steve Antonae226f62019-01-29 12:47:38 -0800362 RTC_DCHECK(absl::c_any_of(
363 port_->Network()->GetIPs(), [this](const rtc::InterfaceAddress& addr) {
364 return socket_->GetLocalAddress().ipaddr() == addr;
365 }));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700366 ConnectSocketSignals(socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000367 }
368}
369
Mirko Bonadei0cb1cfa2022-02-25 10:45:32 +0000370TCPConnection::~TCPConnection() {
371 RTC_DCHECK_RUN_ON(network_thread_);
372}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000373
Yves Gerey665174f2018-06-19 15:03:05 +0200374int TCPConnection::Send(const void* data,
375 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000376 const rtc::PacketOptions& options) {
377 if (!socket_) {
378 error_ = ENOTCONN;
379 return SOCKET_ERROR;
380 }
381
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700382 // Sending after OnClose on active side will trigger a reconnect for a
383 // outgoing connection. Note that the write state is still WRITABLE as we want
384 // to spend a few seconds attempting a reconnect before saying we're
385 // unwritable.
386 if (!connected()) {
387 MaybeReconnect();
388 return SOCKET_ERROR;
389 }
390
391 // Note that this is important to put this after the previous check to give
392 // the connection a chance to reconnect.
393 if (pretending_to_be_writable_ || write_state() != STATE_WRITABLE) {
Steve Anton6c38cc72017-11-29 10:25:58 -0800394 // TODO(?): Should STATE_WRITE_TIMEOUT return a non-blocking error?
skvladc309e0e2016-07-28 17:15:20 -0700395 error_ = ENOTCONN;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000396 return SOCKET_ERROR;
397 }
zhihuang5ecf16c2016-06-01 17:09:15 -0700398 stats_.sent_total_packets++;
Qingsi Wang6e641e62018-04-11 20:14:17 -0700399 rtc::PacketOptions modified_options(options);
400 static_cast<TCPPort*>(port_)->CopyPortInformationToPacketInfo(
401 &modified_options.info_signaled_after_sent);
402 int sent = socket_->Send(data, size, modified_options);
Jonas Oreland3c5d5822020-12-14 12:45:05 +0100403 int64_t now = rtc::TimeMillis();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000404 if (sent < 0) {
zhihuang5ecf16c2016-06-01 17:09:15 -0700405 stats_.sent_discarded_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000406 error_ = socket_->GetError();
407 } else {
Jonas Oreland3c5d5822020-12-14 12:45:05 +0100408 send_rate_tracker_.AddSamplesAtTime(now, sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000409 }
Jonas Oreland3c5d5822020-12-14 12:45:05 +0100410 last_send_data_ = now;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000411 return sent;
412}
413
414int TCPConnection::GetError() {
415 return error_;
416}
417
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700418void TCPConnection::OnConnectionRequestResponse(ConnectionRequest* req,
419 StunMessage* response) {
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700420 // Process the STUN response before we inform upper layer ready to send.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700421 Connection::OnConnectionRequestResponse(req, response);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700422
423 // If we're in the state of pretending to be writeable, we should inform the
424 // upper layer it's ready to send again as previous EWOULDLBLOCK from socket
425 // would have stopped the outgoing stream.
426 if (pretending_to_be_writable_) {
427 Connection::OnReadyToSend();
428 }
429 pretending_to_be_writable_ = false;
nisseede5da42017-01-12 05:15:36 -0800430 RTC_DCHECK(write_state() == STATE_WRITABLE);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700431}
432
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000433void TCPConnection::OnConnect(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800434 RTC_DCHECK(socket == socket_.get());
deadbeef5c3c1042017-08-04 15:01:57 -0700435 // Do not use this port if the socket bound to an address not associated with
436 // the desired network interface. This is seen in Chrome, where TCP sockets
437 // cannot be given a binding address, and the platform is expected to pick
438 // the correct local address.
439 //
440 // However, there are two situations in which we allow the bound address to
441 // not be one of the addresses of the requested interface:
442 // 1. The bound address is the loopback address. This happens when a proxy
443 // forces TCP to bind to only the localhost address (see issue 3927).
444 // 2. The bound address is the "any address". This happens when
445 // multiple_routes is disabled (see issue 4780).
446 //
447 // Note that, aside from minor differences in log statements, this logic is
448 // identical to that in TurnPort.
449 const rtc::SocketAddress& socket_address = socket->GetLocalAddress();
Steve Antonae226f62019-01-29 12:47:38 -0800450 if (absl::c_any_of(port_->Network()->GetIPs(),
451 [socket_address](const rtc::InterfaceAddress& addr) {
452 return socket_address.ipaddr() == addr;
453 })) {
Yves Gerey665174f2018-06-19 15:03:05 +0200454 RTC_LOG(LS_VERBOSE) << ToString() << ": Connection established to "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200455 << socket->GetRemoteAddress().ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000456 } else {
deadbeef5c3c1042017-08-04 15:01:57 -0700457 if (socket->GetLocalAddress().IsLoopbackIP()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100458 RTC_LOG(LS_WARNING) << "Socket is bound to the address:"
Qingsi Wang20232a92019-09-06 12:51:17 -0700459 << socket_address.ipaddr().ToSensitiveString()
Taylor Brandstetter3ba7a572018-03-02 10:58:25 -0800460 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100461 << port_->Network()->ToString()
462 << ". Still allowing it since it's localhost.";
deadbeef5c3c1042017-08-04 15:01:57 -0700463 } else if (IPIsAny(port_->Network()->GetBestIP())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100464 RTC_LOG(LS_WARNING)
465 << "Socket is bound to the address:"
Qingsi Wang20232a92019-09-06 12:51:17 -0700466 << socket_address.ipaddr().ToSensitiveString()
Taylor Brandstetter3ba7a572018-03-02 10:58:25 -0800467 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100468 << port_->Network()->ToString()
469 << ". Still allowing it since it's the 'any' address"
Jonas Olssond7d762d2018-03-28 09:47:51 +0200470 ", possibly caused by multiple_routes being disabled.";
deadbeef5c3c1042017-08-04 15:01:57 -0700471 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100472 RTC_LOG(LS_WARNING) << "Dropping connection as TCP socket bound to IP "
Qingsi Wang20232a92019-09-06 12:51:17 -0700473 << socket_address.ipaddr().ToSensitiveString()
Taylor Brandstetter3ba7a572018-03-02 10:58:25 -0800474 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100475 << port_->Network()->ToString();
deadbeef5c3c1042017-08-04 15:01:57 -0700476 OnClose(socket, 0);
477 return;
478 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000479 }
tommi5ce1a2a2016-05-14 03:19:31 -0700480
481 // Connection is established successfully.
482 set_connected(true);
483 connection_pending_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000484}
485
486void TCPConnection::OnClose(rtc::AsyncPacketSocket* socket, int error) {
nisseede5da42017-01-12 05:15:36 -0800487 RTC_DCHECK(socket == socket_.get());
Yves Gerey665174f2018-06-19 15:03:05 +0200488 RTC_LOG(LS_INFO) << ToString() << ": Connection closed with error " << error;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700489
490 // Guard against the condition where IPC socket will call OnClose for every
491 // packet it can't send.
492 if (connected()) {
493 set_connected(false);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700494
495 // Prevent the connection from being destroyed by redundant SignalClose
496 // events.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700497 pretending_to_be_writable_ = true;
498
Mirko Bonadei0cb1cfa2022-02-25 10:45:32 +0000499 // If this connection can't become connected and writable again in 5
500 // seconds, it's time to tear this down. This is the case for the original
501 // TCP connection on passive side during a reconnect.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700502 // We don't attempt reconnect right here. This is to avoid a case where the
503 // shutdown is intentional and reconnect is not necessary. We only reconnect
504 // when the connection is used to Send() or Ping().
Mirko Bonadei0cb1cfa2022-02-25 10:45:32 +0000505 port()->thread()->PostDelayedTask(
506 webrtc::ToQueuedTask(network_safety_,
507 [this]() {
508 if (pretending_to_be_writable_) {
509 Destroy();
510 }
511 }),
512 reconnection_timeout());
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700513 } else if (!pretending_to_be_writable_) {
514 // OnClose could be called when the underneath socket times out during the
Artem Titov2dbb4c92021-07-26 15:12:41 +0200515 // initial connect() (i.e. `pretending_to_be_writable_` is false) . We have
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700516 // to manually destroy here as this connection, as never connected, will not
517 // be scheduled for ping to trigger destroy.
518 Destroy();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700519 }
520}
521
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700522void TCPConnection::MaybeReconnect() {
523 // Only reconnect for an outgoing TCPConnection when OnClose was signaled and
524 // no outstanding reconnect is pending.
525 if (connected() || connection_pending_ || !outgoing_) {
526 return;
527 }
528
Jonas Olssond7d762d2018-03-28 09:47:51 +0200529 RTC_LOG(LS_INFO) << ToString()
530 << ": TCP Connection with remote is closed, "
531 "trying to reconnect";
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700532
533 CreateOutgoingTcpSocket();
534 error_ = EPIPE;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000535}
536
Yves Gerey665174f2018-06-19 15:03:05 +0200537void TCPConnection::OnReadPacket(rtc::AsyncPacketSocket* socket,
538 const char* data,
539 size_t size,
540 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +0100541 const int64_t& packet_time_us) {
nisseede5da42017-01-12 05:15:36 -0800542 RTC_DCHECK(socket == socket_.get());
Niels Möllere6933812018-11-05 13:01:41 +0100543 Connection::OnReadPacket(data, size, packet_time_us);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000544}
545
546void TCPConnection::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800547 RTC_DCHECK(socket == socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000548 Connection::OnReadyToSend();
549}
550
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700551void TCPConnection::CreateOutgoingTcpSocket() {
nisseede5da42017-01-12 05:15:36 -0800552 RTC_DCHECK(outgoing_);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700553 int opts = (remote_candidate().protocol() == SSLTCP_PROTOCOL_NAME)
hnsl04833622017-01-09 08:35:45 -0800554 ? rtc::PacketSocketFactory::OPT_TLS_FAKE
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700555 : 0;
Patrik Höglund662e31f2019-09-05 14:35:04 +0200556 rtc::PacketSocketTcpOptions tcp_opts;
557 tcp_opts.opts = opts;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700558 socket_.reset(port()->socket_factory()->CreateClientTcpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -0700559 rtc::SocketAddress(port()->Network()->GetBestIP(), 0),
560 remote_candidate().address(), port()->proxy(), port()->user_agent(),
Patrik Höglund662e31f2019-09-05 14:35:04 +0200561 tcp_opts));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700562 if (socket_) {
Yves Gerey665174f2018-06-19 15:03:05 +0200563 RTC_LOG(LS_VERBOSE) << ToString() << ": Connecting from "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200564 << socket_->GetLocalAddress().ToSensitiveString()
565 << " to "
566 << remote_candidate().address().ToSensitiveString();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700567 set_connected(false);
568 connection_pending_ = true;
569 ConnectSocketSignals(socket_.get());
570 } else {
Yves Gerey665174f2018-06-19 15:03:05 +0200571 RTC_LOG(LS_WARNING) << ToString() << ": Failed to create connection to "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200572 << remote_candidate().address().ToSensitiveString();
Mirko Bonadei0cb1cfa2022-02-25 10:45:32 +0000573 set_state(IceCandidatePairState::FAILED);
Jonas Oreland7a284e12020-01-28 09:21:54 +0100574 // We can't FailAndPrune directly here. FailAndPrune and deletes all
575 // the StunRequests from the request_map_. And if this is in the stack
576 // of Connection::Ping(), we are still using the request.
577 // Unwind the stack and defer the FailAndPrune.
Mirko Bonadei0cb1cfa2022-02-25 10:45:32 +0000578 port()->thread()->PostTask(
579 webrtc::ToQueuedTask(network_safety_, [this]() { FailAndPrune(); }));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700580 }
581}
582
583void TCPConnection::ConnectSocketSignals(rtc::AsyncPacketSocket* socket) {
584 if (outgoing_) {
585 socket->SignalConnect.connect(this, &TCPConnection::OnConnect);
586 }
587 socket->SignalReadPacket.connect(this, &TCPConnection::OnReadPacket);
588 socket->SignalReadyToSend.connect(this, &TCPConnection::OnReadyToSend);
589 socket->SignalClose.connect(this, &TCPConnection::OnClose);
590}
591
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000592} // namespace cricket