blob: ea805e58943ca921afb2cb021eabf402e6bd3ab5 [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"
Yves Gerey3e707812018-11-28 16:47:49 +010082#include "rtc_base/third_party/sigslot/sigslot.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000083
84namespace cricket {
85
86TCPPort::TCPPort(rtc::Thread* thread,
87 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +000088 rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +020089 uint16_t min_port,
90 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +000091 const std::string& username,
92 const std::string& password,
93 bool allow_listen)
Peter Boström0c4e06b2015-10-07 12:23:21 +020094 : Port(thread,
95 LOCAL_PORT_TYPE,
96 factory,
97 network,
Peter Boström0c4e06b2015-10-07 12:23:21 +020098 min_port,
99 max_port,
100 username,
101 password),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000102 allow_listen_(allow_listen),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000103 error_(0) {
104 // TODO(mallinath) - Set preference value as per RFC 6544.
105 // http://b/issue?id=7141794
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000106 if (allow_listen_) {
deadbeef1ee21252017-06-13 15:49:45 -0700107 TryCreateServerSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000108 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000109}
110
111TCPPort::~TCPPort() {
Niels Möller6d19d142021-10-06 11:19:03 +0200112 listen_socket_ = nullptr;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000113 std::list<Incoming>::iterator it;
114 for (it = incoming_.begin(); it != incoming_.end(); ++it)
115 delete it->socket;
116 incoming_.clear();
117}
118
119Connection* TCPPort::CreateConnection(const Candidate& address,
120 CandidateOrigin origin) {
Honghai Zhangf9945b22015-12-15 12:20:13 -0800121 if (!SupportsProtocol(address.protocol())) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000122 return NULL;
123 }
124
Philipp Hanckee283d1c2020-03-27 09:56:51 +0100125 if ((address.tcptype() == TCPTYPE_ACTIVE_STR &&
126 address.type() != PRFLX_PORT_TYPE) ||
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000127 (address.tcptype().empty() && address.address().port() == 0)) {
128 // It's active only candidate, we should not try to create connections
129 // for these candidates.
130 return NULL;
131 }
132
133 // We can't accept TCP connections incoming on other ports
134 if (origin == ORIGIN_OTHER_PORT)
135 return NULL;
136
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000137 // We don't know how to act as an ssl server yet
138 if ((address.protocol() == SSLTCP_PROTOCOL_NAME) &&
139 (origin == ORIGIN_THIS_PORT)) {
140 return NULL;
141 }
142
143 if (!IsCompatibleAddress(address.address())) {
144 return NULL;
145 }
146
147 TCPConnection* conn = NULL;
Yves Gerey665174f2018-06-19 15:03:05 +0200148 if (rtc::AsyncPacketSocket* socket = GetIncoming(address.address(), true)) {
deadbeef06878292017-04-21 14:22:23 -0700149 // Incoming connection; we already created a socket and connected signals,
150 // so we need to hand off the "read packet" responsibility to
151 // TCPConnection.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000152 socket->SignalReadPacket.disconnect(this);
153 conn = new TCPConnection(this, address, socket);
154 } else {
deadbeef06878292017-04-21 14:22:23 -0700155 // Outgoing connection, which will create a new socket for which we still
156 // need to connect SignalReadyToSend and SignalSentPacket.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000157 conn = new TCPConnection(this, address);
deadbeef06878292017-04-21 14:22:23 -0700158 if (conn->socket()) {
159 conn->socket()->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
160 conn->socket()->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
161 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000162 }
honghaiz36f50e82016-06-01 15:57:03 -0700163 AddOrReplaceConnection(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000164 return conn;
165}
166
167void TCPPort::PrepareAddress() {
Niels Möller6d19d142021-10-06 11:19:03 +0200168 if (listen_socket_) {
Niels Möller4a1c2c42021-09-28 10:17:07 +0200169 // Socket may be in the CLOSED state if Listen()
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000170 // failed, we still want to add the socket address.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100171 RTC_LOG(LS_VERBOSE) << "Preparing TCP address, current state: "
Niels Möllerd30ece12021-10-19 10:11:02 +0200172 << static_cast<int>(listen_socket_->GetState());
173 AddAddress(listen_socket_->GetLocalAddress(),
174 listen_socket_->GetLocalAddress(), rtc::SocketAddress(),
175 TCP_PROTOCOL_NAME, "", TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE,
176 ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000177 } else {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200178 RTC_LOG(LS_INFO) << ToString()
179 << ": Not listening due to firewall restrictions.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000180 // Note: We still add the address, since otherwise the remote side won't
Guo-wei Shieh310b0932015-11-17 19:15:50 -0800181 // recognize our incoming TCP connections. According to
182 // https://tools.ietf.org/html/rfc6544#section-4.5, for active candidate,
deadbeef5c3c1042017-08-04 15:01:57 -0700183 // the port must be set to the discard port, i.e. 9. We can't be 100% sure
184 // which IP address will actually be used, so GetBestIP is as good as we
185 // can do.
186 // TODO(deadbeef): We could do something like create a dummy socket just to
187 // see what IP we get. But that may be overkill.
188 AddAddress(rtc::SocketAddress(Network()->GetBestIP(), DISCARD_PORT),
189 rtc::SocketAddress(Network()->GetBestIP(), 0),
190 rtc::SocketAddress(), TCP_PROTOCOL_NAME, "", TCPTYPE_ACTIVE_STR,
191 LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000192 }
193}
194
Yves Gerey665174f2018-06-19 15:03:05 +0200195int TCPPort::SendTo(const void* data,
196 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000197 const rtc::SocketAddress& addr,
198 const rtc::PacketOptions& options,
199 bool payload) {
Yves Gerey665174f2018-06-19 15:03:05 +0200200 rtc::AsyncPacketSocket* socket = NULL;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700201 TCPConnection* conn = static_cast<TCPConnection*>(GetConnection(addr));
202
203 // For Connection, this is the code path used by Ping() to establish
204 // WRITABLE. It has to send through the socket directly as TCPConnection::Send
205 // checks writability.
206 if (conn) {
207 if (!conn->connected()) {
208 conn->MaybeReconnect();
209 return SOCKET_ERROR;
210 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000211 socket = conn->socket();
Harald Alvestranddc800172020-01-06 20:01:36 +0100212 if (!socket) {
213 // The failure to initialize should have been logged elsewhere,
214 // so this log is not important.
215 RTC_LOG(LS_INFO) << ToString()
216 << ": Attempted to send to an uninitialized socket: "
217 << addr.ToSensitiveString();
218 error_ = EHOSTUNREACH;
219 return SOCKET_ERROR;
220 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000221 } else {
222 socket = GetIncoming(addr);
Harald Alvestranddc800172020-01-06 20:01:36 +0100223 if (!socket) {
224 RTC_LOG(LS_ERROR) << ToString()
225 << ": Attempted to send to an unknown destination: "
226 << addr.ToSensitiveString();
227 error_ = EHOSTUNREACH;
228 return SOCKET_ERROR;
229 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000230 }
Qingsi Wang6e641e62018-04-11 20:14:17 -0700231 rtc::PacketOptions modified_options(options);
232 CopyPortInformationToPacketInfo(&modified_options.info_signaled_after_sent);
233 int sent = socket->Send(data, size, modified_options);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000234 if (sent < 0) {
235 error_ = socket->GetError();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700236 // Error from this code path for a Connection (instead of from a bare
237 // socket) will not trigger reconnecting. In theory, this shouldn't matter
238 // as OnClose should always be called and set connected to false.
Yves Gerey665174f2018-06-19 15:03:05 +0200239 RTC_LOG(LS_ERROR) << ToString() << ": TCP send of " << size
240 << " bytes failed with error " << error_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000241 }
242 return sent;
243}
244
245int TCPPort::GetOption(rtc::Socket::Option opt, int* value) {
Niels Möller6d19d142021-10-06 11:19:03 +0200246 if (listen_socket_) {
247 return listen_socket_->GetOption(opt, value);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000248 } else {
249 return SOCKET_ERROR;
250 }
251}
252
253int TCPPort::SetOption(rtc::Socket::Option opt, int value) {
Niels Möller6d19d142021-10-06 11:19:03 +0200254 if (listen_socket_) {
255 return listen_socket_->SetOption(opt, value);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000256 } else {
257 return SOCKET_ERROR;
258 }
259}
260
261int TCPPort::GetError() {
262 return error_;
263}
264
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700265bool TCPPort::SupportsProtocol(const std::string& protocol) const {
266 return protocol == TCP_PROTOCOL_NAME || protocol == SSLTCP_PROTOCOL_NAME;
267}
268
269ProtocolType TCPPort::GetProtocol() const {
270 return PROTO_TCP;
271}
272
Niels Möller6d19d142021-10-06 11:19:03 +0200273void TCPPort::OnNewConnection(rtc::AsyncListenSocket* socket,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000274 rtc::AsyncPacketSocket* new_socket) {
Niels Möller6d19d142021-10-06 11:19:03 +0200275 RTC_DCHECK(socket == listen_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000276
277 Incoming incoming;
278 incoming.addr = new_socket->GetRemoteAddress();
279 incoming.socket = new_socket;
280 incoming.socket->SignalReadPacket.connect(this, &TCPPort::OnReadPacket);
281 incoming.socket->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
Stefan Holmer55674ff2016-01-14 15:49:16 +0100282 incoming.socket->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000283
Yves Gerey665174f2018-06-19 15:03:05 +0200284 RTC_LOG(LS_VERBOSE) << ToString() << ": Accepted connection from "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200285 << incoming.addr.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000286 incoming_.push_back(incoming);
287}
288
deadbeef1ee21252017-06-13 15:49:45 -0700289void TCPPort::TryCreateServerSocket() {
Niels Möller6d19d142021-10-06 11:19:03 +0200290 listen_socket_ = absl::WrapUnique(socket_factory()->CreateServerTcpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -0700291 rtc::SocketAddress(Network()->GetBestIP(), 0), min_port(), max_port(),
Niels Möller6d19d142021-10-06 11:19:03 +0200292 false /* ssl */));
293 if (!listen_socket_) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200294 RTC_LOG(LS_WARNING)
295 << ToString()
296 << ": TCP server socket creation failed; continuing anyway.";
deadbeef1ee21252017-06-13 15:49:45 -0700297 return;
298 }
Niels Möller6d19d142021-10-06 11:19:03 +0200299 listen_socket_->SignalNewConnection.connect(this, &TCPPort::OnNewConnection);
deadbeef1ee21252017-06-13 15:49:45 -0700300}
301
Yves Gerey665174f2018-06-19 15:03:05 +0200302rtc::AsyncPacketSocket* TCPPort::GetIncoming(const rtc::SocketAddress& addr,
303 bool remove) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000304 rtc::AsyncPacketSocket* socket = NULL;
305 for (std::list<Incoming>::iterator it = incoming_.begin();
306 it != incoming_.end(); ++it) {
307 if (it->addr == addr) {
308 socket = it->socket;
309 if (remove)
310 incoming_.erase(it);
311 break;
312 }
313 }
314 return socket;
315}
316
317void TCPPort::OnReadPacket(rtc::AsyncPacketSocket* socket,
Yves Gerey665174f2018-06-19 15:03:05 +0200318 const char* data,
319 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000320 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +0100321 const int64_t& packet_time_us) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000322 Port::OnReadPacket(data, size, remote_addr, PROTO_TCP);
323}
324
Stefan Holmer55674ff2016-01-14 15:49:16 +0100325void TCPPort::OnSentPacket(rtc::AsyncPacketSocket* socket,
326 const rtc::SentPacket& sent_packet) {
Stefan Holmer55674ff2016-01-14 15:49:16 +0100327 PortInterface::SignalSentPacket(sent_packet);
328}
329
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000330void TCPPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
331 Port::OnReadyToSend();
332}
333
Artem Titov2dbb4c92021-07-26 15:12:41 +0200334// TODO(qingsi): `CONNECTION_WRITE_CONNECT_TIMEOUT` is overriden by
335// `ice_unwritable_timeout` in IceConfig when determining the writability state.
Qingsi Wang22e623a2018-03-13 10:53:57 -0700336// Replace this constant with the config parameter assuming the default value if
337// we decide it is also applicable here.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700338TCPConnection::TCPConnection(TCPPort* port,
339 const Candidate& candidate,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000340 rtc::AsyncPacketSocket* socket)
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700341 : Connection(port, 0, candidate),
342 socket_(socket),
343 error_(0),
344 outgoing_(socket == NULL),
345 connection_pending_(false),
346 pretending_to_be_writable_(false),
347 reconnection_timeout_(cricket::CONNECTION_WRITE_CONNECT_TIMEOUT) {
348 if (outgoing_) {
349 CreateOutgoingTcpSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000350 } else {
deadbeef5c3c1042017-08-04 15:01:57 -0700351 // Incoming connections should match one of the network addresses. Same as
352 // what's being checked in OnConnect, but just DCHECKing here.
Jonas Olssond7d762d2018-03-28 09:47:51 +0200353 RTC_LOG(LS_VERBOSE) << ToString() << ": socket ipaddr: "
Qingsi Wang20232a92019-09-06 12:51:17 -0700354 << socket_->GetLocalAddress().ToSensitiveString()
Jonas Olssond7d762d2018-03-28 09:47:51 +0200355 << ", port() Network:" << port->Network()->ToString();
Steve Antonae226f62019-01-29 12:47:38 -0800356 RTC_DCHECK(absl::c_any_of(
357 port_->Network()->GetIPs(), [this](const rtc::InterfaceAddress& addr) {
358 return socket_->GetLocalAddress().ipaddr() == addr;
359 }));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700360 ConnectSocketSignals(socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000361 }
362}
363
Yves Gerey665174f2018-06-19 15:03:05 +0200364TCPConnection::~TCPConnection() {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000365
Yves Gerey665174f2018-06-19 15:03:05 +0200366int TCPConnection::Send(const void* data,
367 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000368 const rtc::PacketOptions& options) {
369 if (!socket_) {
370 error_ = ENOTCONN;
371 return SOCKET_ERROR;
372 }
373
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700374 // Sending after OnClose on active side will trigger a reconnect for a
375 // outgoing connection. Note that the write state is still WRITABLE as we want
376 // to spend a few seconds attempting a reconnect before saying we're
377 // unwritable.
378 if (!connected()) {
379 MaybeReconnect();
380 return SOCKET_ERROR;
381 }
382
383 // Note that this is important to put this after the previous check to give
384 // the connection a chance to reconnect.
385 if (pretending_to_be_writable_ || write_state() != STATE_WRITABLE) {
Steve Anton6c38cc72017-11-29 10:25:58 -0800386 // TODO(?): Should STATE_WRITE_TIMEOUT return a non-blocking error?
skvladc309e0e2016-07-28 17:15:20 -0700387 error_ = ENOTCONN;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000388 return SOCKET_ERROR;
389 }
zhihuang5ecf16c2016-06-01 17:09:15 -0700390 stats_.sent_total_packets++;
Qingsi Wang6e641e62018-04-11 20:14:17 -0700391 rtc::PacketOptions modified_options(options);
392 static_cast<TCPPort*>(port_)->CopyPortInformationToPacketInfo(
393 &modified_options.info_signaled_after_sent);
394 int sent = socket_->Send(data, size, modified_options);
Jonas Oreland3c5d5822020-12-14 12:45:05 +0100395 int64_t now = rtc::TimeMillis();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000396 if (sent < 0) {
zhihuang5ecf16c2016-06-01 17:09:15 -0700397 stats_.sent_discarded_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000398 error_ = socket_->GetError();
399 } else {
Jonas Oreland3c5d5822020-12-14 12:45:05 +0100400 send_rate_tracker_.AddSamplesAtTime(now, sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000401 }
Jonas Oreland3c5d5822020-12-14 12:45:05 +0100402 last_send_data_ = now;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000403 return sent;
404}
405
406int TCPConnection::GetError() {
407 return error_;
408}
409
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700410void TCPConnection::OnConnectionRequestResponse(ConnectionRequest* req,
411 StunMessage* response) {
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700412 // Process the STUN response before we inform upper layer ready to send.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700413 Connection::OnConnectionRequestResponse(req, response);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700414
415 // If we're in the state of pretending to be writeable, we should inform the
416 // upper layer it's ready to send again as previous EWOULDLBLOCK from socket
417 // would have stopped the outgoing stream.
418 if (pretending_to_be_writable_) {
419 Connection::OnReadyToSend();
420 }
421 pretending_to_be_writable_ = false;
nisseede5da42017-01-12 05:15:36 -0800422 RTC_DCHECK(write_state() == STATE_WRITABLE);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700423}
424
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000425void TCPConnection::OnConnect(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800426 RTC_DCHECK(socket == socket_.get());
deadbeef5c3c1042017-08-04 15:01:57 -0700427 // Do not use this port if the socket bound to an address not associated with
428 // the desired network interface. This is seen in Chrome, where TCP sockets
429 // cannot be given a binding address, and the platform is expected to pick
430 // the correct local address.
431 //
432 // However, there are two situations in which we allow the bound address to
433 // not be one of the addresses of the requested interface:
434 // 1. The bound address is the loopback address. This happens when a proxy
435 // forces TCP to bind to only the localhost address (see issue 3927).
436 // 2. The bound address is the "any address". This happens when
437 // multiple_routes is disabled (see issue 4780).
438 //
439 // Note that, aside from minor differences in log statements, this logic is
440 // identical to that in TurnPort.
441 const rtc::SocketAddress& socket_address = socket->GetLocalAddress();
Steve Antonae226f62019-01-29 12:47:38 -0800442 if (absl::c_any_of(port_->Network()->GetIPs(),
443 [socket_address](const rtc::InterfaceAddress& addr) {
444 return socket_address.ipaddr() == addr;
445 })) {
Yves Gerey665174f2018-06-19 15:03:05 +0200446 RTC_LOG(LS_VERBOSE) << ToString() << ": Connection established to "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200447 << socket->GetRemoteAddress().ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000448 } else {
deadbeef5c3c1042017-08-04 15:01:57 -0700449 if (socket->GetLocalAddress().IsLoopbackIP()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100450 RTC_LOG(LS_WARNING) << "Socket is bound to the address:"
Qingsi Wang20232a92019-09-06 12:51:17 -0700451 << socket_address.ipaddr().ToSensitiveString()
Taylor Brandstetter3ba7a572018-03-02 10:58:25 -0800452 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100453 << port_->Network()->ToString()
454 << ". Still allowing it since it's localhost.";
deadbeef5c3c1042017-08-04 15:01:57 -0700455 } else if (IPIsAny(port_->Network()->GetBestIP())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100456 RTC_LOG(LS_WARNING)
457 << "Socket is bound to the address:"
Qingsi Wang20232a92019-09-06 12:51:17 -0700458 << socket_address.ipaddr().ToSensitiveString()
Taylor Brandstetter3ba7a572018-03-02 10:58:25 -0800459 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100460 << port_->Network()->ToString()
461 << ". Still allowing it since it's the 'any' address"
Jonas Olssond7d762d2018-03-28 09:47:51 +0200462 ", possibly caused by multiple_routes being disabled.";
deadbeef5c3c1042017-08-04 15:01:57 -0700463 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100464 RTC_LOG(LS_WARNING) << "Dropping connection as TCP socket bound to IP "
Qingsi Wang20232a92019-09-06 12:51:17 -0700465 << socket_address.ipaddr().ToSensitiveString()
Taylor Brandstetter3ba7a572018-03-02 10:58:25 -0800466 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100467 << port_->Network()->ToString();
deadbeef5c3c1042017-08-04 15:01:57 -0700468 OnClose(socket, 0);
469 return;
470 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000471 }
tommi5ce1a2a2016-05-14 03:19:31 -0700472
473 // Connection is established successfully.
474 set_connected(true);
475 connection_pending_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000476}
477
478void TCPConnection::OnClose(rtc::AsyncPacketSocket* socket, int error) {
nisseede5da42017-01-12 05:15:36 -0800479 RTC_DCHECK(socket == socket_.get());
Yves Gerey665174f2018-06-19 15:03:05 +0200480 RTC_LOG(LS_INFO) << ToString() << ": Connection closed with error " << error;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700481
482 // Guard against the condition where IPC socket will call OnClose for every
483 // packet it can't send.
484 if (connected()) {
485 set_connected(false);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700486
487 // Prevent the connection from being destroyed by redundant SignalClose
488 // events.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700489 pretending_to_be_writable_ = true;
490
491 // We don't attempt reconnect right here. This is to avoid a case where the
492 // shutdown is intentional and reconnect is not necessary. We only reconnect
493 // when the connection is used to Send() or Ping().
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700494 port()->thread()->PostDelayed(RTC_FROM_HERE, reconnection_timeout(), this,
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700495 MSG_TCPCONNECTION_DELAYED_ONCLOSE);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700496 } else if (!pretending_to_be_writable_) {
497 // OnClose could be called when the underneath socket times out during the
Artem Titov2dbb4c92021-07-26 15:12:41 +0200498 // initial connect() (i.e. `pretending_to_be_writable_` is false) . We have
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700499 // to manually destroy here as this connection, as never connected, will not
500 // be scheduled for ping to trigger destroy.
501 Destroy();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700502 }
503}
504
505void TCPConnection::OnMessage(rtc::Message* pmsg) {
506 switch (pmsg->message_id) {
507 case MSG_TCPCONNECTION_DELAYED_ONCLOSE:
508 // If this connection can't become connected and writable again in 5
509 // seconds, it's time to tear this down. This is the case for the original
510 // TCP connection on passive side during a reconnect.
511 if (pretending_to_be_writable_) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700512 Destroy();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700513 }
514 break;
Jonas Oreland7a284e12020-01-28 09:21:54 +0100515 case MSG_TCPCONNECTION_FAILED_CREATE_SOCKET:
516 FailAndPrune();
517 break;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700518 default:
519 Connection::OnMessage(pmsg);
520 }
521}
522
523void TCPConnection::MaybeReconnect() {
524 // Only reconnect for an outgoing TCPConnection when OnClose was signaled and
525 // no outstanding reconnect is pending.
526 if (connected() || connection_pending_ || !outgoing_) {
527 return;
528 }
529
Jonas Olssond7d762d2018-03-28 09:47:51 +0200530 RTC_LOG(LS_INFO) << ToString()
531 << ": TCP Connection with remote is closed, "
532 "trying to reconnect";
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700533
534 CreateOutgoingTcpSocket();
535 error_ = EPIPE;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000536}
537
Yves Gerey665174f2018-06-19 15:03:05 +0200538void TCPConnection::OnReadPacket(rtc::AsyncPacketSocket* socket,
539 const char* data,
540 size_t size,
541 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +0100542 const int64_t& packet_time_us) {
nisseede5da42017-01-12 05:15:36 -0800543 RTC_DCHECK(socket == socket_.get());
Niels Möllere6933812018-11-05 13:01:41 +0100544 Connection::OnReadPacket(data, size, packet_time_us);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000545}
546
547void TCPConnection::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800548 RTC_DCHECK(socket == socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000549 Connection::OnReadyToSend();
550}
551
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700552void TCPConnection::CreateOutgoingTcpSocket() {
nisseede5da42017-01-12 05:15:36 -0800553 RTC_DCHECK(outgoing_);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700554 int opts = (remote_candidate().protocol() == SSLTCP_PROTOCOL_NAME)
hnsl04833622017-01-09 08:35:45 -0800555 ? rtc::PacketSocketFactory::OPT_TLS_FAKE
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700556 : 0;
Patrik Höglund662e31f2019-09-05 14:35:04 +0200557 rtc::PacketSocketTcpOptions tcp_opts;
558 tcp_opts.opts = opts;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700559 socket_.reset(port()->socket_factory()->CreateClientTcpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -0700560 rtc::SocketAddress(port()->Network()->GetBestIP(), 0),
561 remote_candidate().address(), port()->proxy(), port()->user_agent(),
Patrik Höglund662e31f2019-09-05 14:35:04 +0200562 tcp_opts));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700563 if (socket_) {
Yves Gerey665174f2018-06-19 15:03:05 +0200564 RTC_LOG(LS_VERBOSE) << ToString() << ": Connecting from "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200565 << socket_->GetLocalAddress().ToSensitiveString()
566 << " to "
567 << remote_candidate().address().ToSensitiveString();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700568 set_connected(false);
569 connection_pending_ = true;
570 ConnectSocketSignals(socket_.get());
571 } else {
Yves Gerey665174f2018-06-19 15:03:05 +0200572 RTC_LOG(LS_WARNING) << ToString() << ": Failed to create connection to "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200573 << remote_candidate().address().ToSensitiveString();
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.
578 set_state(IceCandidatePairState::FAILED);
579 port()->thread()->Post(RTC_FROM_HERE, this,
580 MSG_TCPCONNECTION_FAILED_CREATE_SOCKET);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700581 }
582}
583
584void TCPConnection::ConnectSocketSignals(rtc::AsyncPacketSocket* socket) {
585 if (outgoing_) {
586 socket->SignalConnect.connect(this, &TCPConnection::OnConnect);
587 }
588 socket->SignalReadPacket.connect(this, &TCPConnection::OnReadPacket);
589 socket->SignalReadyToSend.connect(this, &TCPConnection::OnReadyToSend);
590 socket->SignalClose.connect(this, &TCPConnection::OnClose);
591}
592
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000593} // namespace cricket