blob: 9d542074a4cf6c72ea689b0fba9199ca53f942a5 [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:111/*
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 19:48:4711/*
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 13:12:4121 * - PendingTCP: `connection_pending_` indicates whether there is an
Guo-wei Shiehbe508a12015-04-06 19:48:4722 * outstanding TCP connection in progress.
23 *
Artem Titov2dbb4c92021-07-26 13:12:4124 * - PretendWri: Tracked by `pretending_to_be_writable_`. Marking connection as
Guo-wei Shiehbe508a12015-04-06 19:48:4725 * 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 18:02:5532 * 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 19:48:4758 * 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 17:11:0067#include "p2p/base/tcp_port.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:1168
Yves Gerey3e707812018-11-28 15:47:4969#include <errno.h>
Jonas Olssona4d87372019-07-05 17:08:3370
Steve Anton6c38cc72017-11-29 18:25:5871#include <vector>
72
Steve Antonae226f62019-01-29 20:47:3873#include "absl/algorithm/container.h"
Niels Möller6d19d142021-10-06 09:19:0374#include "absl/memory/memory.h"
Steve Anton10542f22019-01-11 17:11:0075#include "p2p/base/p2p_constants.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3176#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 17:11:0077#include "rtc_base/ip_address.h"
Yves Gerey3e707812018-11-28 15:47:4978#include "rtc_base/location.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3179#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 17:11:0080#include "rtc_base/net_helper.h"
81#include "rtc_base/rate_tracker.h"
Yves Gerey3e707812018-11-28 15:47:4982#include "rtc_base/third_party/sigslot/sigslot.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:1183
84namespace cricket {
85
86TCPPort::TCPPort(rtc::Thread* thread,
87 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:2288 rtc::Network* network,
Peter Boström0c4e06b2015-10-07 10:23:2189 uint16_t min_port,
90 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:2291 const std::string& username,
92 const std::string& password,
93 bool allow_listen)
Peter Boström0c4e06b2015-10-07 10:23:2194 : Port(thread,
95 LOCAL_PORT_TYPE,
96 factory,
97 network,
Peter Boström0c4e06b2015-10-07 10:23:2198 min_port,
99 max_port,
100 username,
101 password),
henrike@webrtc.org269fb4b2014-10-28 22:20:11102 allow_listen_(allow_listen),
henrike@webrtc.org269fb4b2014-10-28 22:20:11103 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:11106 if (allow_listen_) {
deadbeef1ee21252017-06-13 22:49:45107 TryCreateServerSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11108 }
Niels Möller646fddc2021-11-02 14:56:05109 // Set TCP_NODELAY (via OPT_NODELAY) for improved performance; this causes
110 // small media packets to be sent immediately rather than being buffered up,
111 // reducing latency.
112 SetOption(rtc::Socket::OPT_NODELAY, 1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11113}
114
115TCPPort::~TCPPort() {
Niels Möller6d19d142021-10-06 09:19:03116 listen_socket_ = nullptr;
henrike@webrtc.org269fb4b2014-10-28 22:20:11117 std::list<Incoming>::iterator it;
118 for (it = incoming_.begin(); it != incoming_.end(); ++it)
119 delete it->socket;
120 incoming_.clear();
121}
122
123Connection* TCPPort::CreateConnection(const Candidate& address,
124 CandidateOrigin origin) {
Honghai Zhangf9945b22015-12-15 20:20:13125 if (!SupportsProtocol(address.protocol())) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11126 return NULL;
127 }
128
Philipp Hanckee283d1c2020-03-27 08:56:51129 if ((address.tcptype() == TCPTYPE_ACTIVE_STR &&
130 address.type() != PRFLX_PORT_TYPE) ||
henrike@webrtc.org269fb4b2014-10-28 22:20:11131 (address.tcptype().empty() && address.address().port() == 0)) {
132 // It's active only candidate, we should not try to create connections
133 // for these candidates.
134 return NULL;
135 }
136
137 // We can't accept TCP connections incoming on other ports
138 if (origin == ORIGIN_OTHER_PORT)
139 return NULL;
140
henrike@webrtc.org269fb4b2014-10-28 22:20:11141 // We don't know how to act as an ssl server yet
142 if ((address.protocol() == SSLTCP_PROTOCOL_NAME) &&
143 (origin == ORIGIN_THIS_PORT)) {
144 return NULL;
145 }
146
147 if (!IsCompatibleAddress(address.address())) {
148 return NULL;
149 }
150
151 TCPConnection* conn = NULL;
Yves Gerey665174f2018-06-19 13:03:05152 if (rtc::AsyncPacketSocket* socket = GetIncoming(address.address(), true)) {
deadbeef06878292017-04-21 21:22:23153 // Incoming connection; we already created a socket and connected signals,
154 // so we need to hand off the "read packet" responsibility to
155 // TCPConnection.
henrike@webrtc.org269fb4b2014-10-28 22:20:11156 socket->SignalReadPacket.disconnect(this);
157 conn = new TCPConnection(this, address, socket);
158 } else {
deadbeef06878292017-04-21 21:22:23159 // Outgoing connection, which will create a new socket for which we still
160 // need to connect SignalReadyToSend and SignalSentPacket.
henrike@webrtc.org269fb4b2014-10-28 22:20:11161 conn = new TCPConnection(this, address);
deadbeef06878292017-04-21 21:22:23162 if (conn->socket()) {
163 conn->socket()->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
164 conn->socket()->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
165 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11166 }
honghaiz36f50e82016-06-01 22:57:03167 AddOrReplaceConnection(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11168 return conn;
169}
170
171void TCPPort::PrepareAddress() {
Niels Möller6d19d142021-10-06 09:19:03172 if (listen_socket_) {
Niels Möller4a1c2c42021-09-28 08:17:07173 // Socket may be in the CLOSED state if Listen()
henrike@webrtc.org269fb4b2014-10-28 22:20:11174 // failed, we still want to add the socket address.
Mirko Bonadei675513b2017-11-09 10:09:25175 RTC_LOG(LS_VERBOSE) << "Preparing TCP address, current state: "
Niels Möllerd30ece12021-10-19 08:11:02176 << static_cast<int>(listen_socket_->GetState());
177 AddAddress(listen_socket_->GetLocalAddress(),
178 listen_socket_->GetLocalAddress(), rtc::SocketAddress(),
179 TCP_PROTOCOL_NAME, "", TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE,
180 ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11181 } else {
Jonas Olssond7d762d2018-03-28 07:47:51182 RTC_LOG(LS_INFO) << ToString()
183 << ": Not listening due to firewall restrictions.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11184 // Note: We still add the address, since otherwise the remote side won't
Guo-wei Shieh310b0932015-11-18 03:15:50185 // recognize our incoming TCP connections. According to
186 // https://tools.ietf.org/html/rfc6544#section-4.5, for active candidate,
deadbeef5c3c1042017-08-04 22:01:57187 // the port must be set to the discard port, i.e. 9. We can't be 100% sure
188 // which IP address will actually be used, so GetBestIP is as good as we
189 // can do.
190 // TODO(deadbeef): We could do something like create a dummy socket just to
191 // see what IP we get. But that may be overkill.
192 AddAddress(rtc::SocketAddress(Network()->GetBestIP(), DISCARD_PORT),
193 rtc::SocketAddress(Network()->GetBestIP(), 0),
194 rtc::SocketAddress(), TCP_PROTOCOL_NAME, "", TCPTYPE_ACTIVE_STR,
195 LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11196 }
197}
198
Yves Gerey665174f2018-06-19 13:03:05199int TCPPort::SendTo(const void* data,
200 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11201 const rtc::SocketAddress& addr,
202 const rtc::PacketOptions& options,
203 bool payload) {
Yves Gerey665174f2018-06-19 13:03:05204 rtc::AsyncPacketSocket* socket = NULL;
Guo-wei Shiehbe508a12015-04-06 19:48:47205 TCPConnection* conn = static_cast<TCPConnection*>(GetConnection(addr));
206
207 // For Connection, this is the code path used by Ping() to establish
208 // WRITABLE. It has to send through the socket directly as TCPConnection::Send
209 // checks writability.
210 if (conn) {
211 if (!conn->connected()) {
212 conn->MaybeReconnect();
213 return SOCKET_ERROR;
214 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11215 socket = conn->socket();
Harald Alvestranddc800172020-01-06 19:01:36216 if (!socket) {
217 // The failure to initialize should have been logged elsewhere,
218 // so this log is not important.
219 RTC_LOG(LS_INFO) << ToString()
220 << ": Attempted to send to an uninitialized socket: "
221 << addr.ToSensitiveString();
222 error_ = EHOSTUNREACH;
223 return SOCKET_ERROR;
224 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11225 } else {
226 socket = GetIncoming(addr);
Harald Alvestranddc800172020-01-06 19:01:36227 if (!socket) {
228 RTC_LOG(LS_ERROR) << ToString()
229 << ": Attempted to send to an unknown destination: "
230 << addr.ToSensitiveString();
231 error_ = EHOSTUNREACH;
232 return SOCKET_ERROR;
233 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11234 }
Qingsi Wang6e641e62018-04-12 03:14:17235 rtc::PacketOptions modified_options(options);
236 CopyPortInformationToPacketInfo(&modified_options.info_signaled_after_sent);
237 int sent = socket->Send(data, size, modified_options);
henrike@webrtc.org269fb4b2014-10-28 22:20:11238 if (sent < 0) {
239 error_ = socket->GetError();
Guo-wei Shiehbe508a12015-04-06 19:48:47240 // Error from this code path for a Connection (instead of from a bare
241 // socket) will not trigger reconnecting. In theory, this shouldn't matter
242 // as OnClose should always be called and set connected to false.
Yves Gerey665174f2018-06-19 13:03:05243 RTC_LOG(LS_ERROR) << ToString() << ": TCP send of " << size
244 << " bytes failed with error " << error_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11245 }
246 return sent;
247}
248
249int TCPPort::GetOption(rtc::Socket::Option opt, int* value) {
Niels Möller646fddc2021-11-02 14:56:05250 auto const& it = socket_options_.find(opt);
251 if (it == socket_options_.end()) {
252 return -1;
henrike@webrtc.org269fb4b2014-10-28 22:20:11253 }
Niels Möller646fddc2021-11-02 14:56:05254 *value = it->second;
255 return 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11256}
257
258int TCPPort::SetOption(rtc::Socket::Option opt, int value) {
Niels Möller646fddc2021-11-02 14:56:05259 socket_options_[opt] = value;
260 return 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11261}
262
263int TCPPort::GetError() {
264 return error_;
265}
266
Steve Anton1cf1b7d2017-10-30 17:00:15267bool TCPPort::SupportsProtocol(const std::string& protocol) const {
268 return protocol == TCP_PROTOCOL_NAME || protocol == SSLTCP_PROTOCOL_NAME;
269}
270
271ProtocolType TCPPort::GetProtocol() const {
272 return PROTO_TCP;
273}
274
Niels Möller6d19d142021-10-06 09:19:03275void TCPPort::OnNewConnection(rtc::AsyncListenSocket* socket,
henrike@webrtc.org269fb4b2014-10-28 22:20:11276 rtc::AsyncPacketSocket* new_socket) {
Niels Möller6d19d142021-10-06 09:19:03277 RTC_DCHECK(socket == listen_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11278
Niels Möller646fddc2021-11-02 14:56:05279 for (const auto& option : socket_options_) {
280 new_socket->SetOption(option.first, option.second);
281 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11282 Incoming incoming;
283 incoming.addr = new_socket->GetRemoteAddress();
284 incoming.socket = new_socket;
285 incoming.socket->SignalReadPacket.connect(this, &TCPPort::OnReadPacket);
286 incoming.socket->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
Stefan Holmer55674ff2016-01-14 14:49:16287 incoming.socket->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11288
Yves Gerey665174f2018-06-19 13:03:05289 RTC_LOG(LS_VERBOSE) << ToString() << ": Accepted connection from "
Jonas Olssond7d762d2018-03-28 07:47:51290 << incoming.addr.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11291 incoming_.push_back(incoming);
292}
293
deadbeef1ee21252017-06-13 22:49:45294void TCPPort::TryCreateServerSocket() {
Niels Möller6d19d142021-10-06 09:19:03295 listen_socket_ = absl::WrapUnique(socket_factory()->CreateServerTcpSocket(
deadbeef5c3c1042017-08-04 22:01:57296 rtc::SocketAddress(Network()->GetBestIP(), 0), min_port(), max_port(),
Niels Möller6d19d142021-10-06 09:19:03297 false /* ssl */));
298 if (!listen_socket_) {
Jonas Olssond7d762d2018-03-28 07:47:51299 RTC_LOG(LS_WARNING)
300 << ToString()
301 << ": TCP server socket creation failed; continuing anyway.";
deadbeef1ee21252017-06-13 22:49:45302 return;
303 }
Niels Möller6d19d142021-10-06 09:19:03304 listen_socket_->SignalNewConnection.connect(this, &TCPPort::OnNewConnection);
deadbeef1ee21252017-06-13 22:49:45305}
306
Yves Gerey665174f2018-06-19 13:03:05307rtc::AsyncPacketSocket* TCPPort::GetIncoming(const rtc::SocketAddress& addr,
308 bool remove) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11309 rtc::AsyncPacketSocket* socket = NULL;
310 for (std::list<Incoming>::iterator it = incoming_.begin();
311 it != incoming_.end(); ++it) {
312 if (it->addr == addr) {
313 socket = it->socket;
314 if (remove)
315 incoming_.erase(it);
316 break;
317 }
318 }
319 return socket;
320}
321
322void TCPPort::OnReadPacket(rtc::AsyncPacketSocket* socket,
Yves Gerey665174f2018-06-19 13:03:05323 const char* data,
324 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11325 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 12:01:41326 const int64_t& packet_time_us) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11327 Port::OnReadPacket(data, size, remote_addr, PROTO_TCP);
328}
329
Stefan Holmer55674ff2016-01-14 14:49:16330void TCPPort::OnSentPacket(rtc::AsyncPacketSocket* socket,
331 const rtc::SentPacket& sent_packet) {
Stefan Holmer55674ff2016-01-14 14:49:16332 PortInterface::SignalSentPacket(sent_packet);
333}
334
henrike@webrtc.org269fb4b2014-10-28 22:20:11335void TCPPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
336 Port::OnReadyToSend();
337}
338
Artem Titov2dbb4c92021-07-26 13:12:41339// TODO(qingsi): `CONNECTION_WRITE_CONNECT_TIMEOUT` is overriden by
340// `ice_unwritable_timeout` in IceConfig when determining the writability state.
Qingsi Wang22e623a2018-03-13 17:53:57341// Replace this constant with the config parameter assuming the default value if
342// we decide it is also applicable here.
Guo-wei Shiehbe508a12015-04-06 19:48:47343TCPConnection::TCPConnection(TCPPort* port,
344 const Candidate& candidate,
henrike@webrtc.org269fb4b2014-10-28 22:20:11345 rtc::AsyncPacketSocket* socket)
Guo-wei Shiehbe508a12015-04-06 19:48:47346 : Connection(port, 0, candidate),
347 socket_(socket),
348 error_(0),
349 outgoing_(socket == NULL),
350 connection_pending_(false),
351 pretending_to_be_writable_(false),
352 reconnection_timeout_(cricket::CONNECTION_WRITE_CONNECT_TIMEOUT) {
353 if (outgoing_) {
354 CreateOutgoingTcpSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11355 } else {
deadbeef5c3c1042017-08-04 22:01:57356 // Incoming connections should match one of the network addresses. Same as
357 // what's being checked in OnConnect, but just DCHECKing here.
Jonas Olssond7d762d2018-03-28 07:47:51358 RTC_LOG(LS_VERBOSE) << ToString() << ": socket ipaddr: "
Qingsi Wang20232a92019-09-06 19:51:17359 << socket_->GetLocalAddress().ToSensitiveString()
Jonas Olssond7d762d2018-03-28 07:47:51360 << ", port() Network:" << port->Network()->ToString();
Steve Antonae226f62019-01-29 20:47:38361 RTC_DCHECK(absl::c_any_of(
362 port_->Network()->GetIPs(), [this](const rtc::InterfaceAddress& addr) {
363 return socket_->GetLocalAddress().ipaddr() == addr;
364 }));
Guo-wei Shiehbe508a12015-04-06 19:48:47365 ConnectSocketSignals(socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11366 }
367}
368
Yves Gerey665174f2018-06-19 13:03:05369TCPConnection::~TCPConnection() {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11370
Yves Gerey665174f2018-06-19 13:03:05371int TCPConnection::Send(const void* data,
372 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11373 const rtc::PacketOptions& options) {
374 if (!socket_) {
375 error_ = ENOTCONN;
376 return SOCKET_ERROR;
377 }
378
Guo-wei Shiehbe508a12015-04-06 19:48:47379 // Sending after OnClose on active side will trigger a reconnect for a
380 // outgoing connection. Note that the write state is still WRITABLE as we want
381 // to spend a few seconds attempting a reconnect before saying we're
382 // unwritable.
383 if (!connected()) {
384 MaybeReconnect();
385 return SOCKET_ERROR;
386 }
387
388 // Note that this is important to put this after the previous check to give
389 // the connection a chance to reconnect.
390 if (pretending_to_be_writable_ || write_state() != STATE_WRITABLE) {
Steve Anton6c38cc72017-11-29 18:25:58391 // TODO(?): Should STATE_WRITE_TIMEOUT return a non-blocking error?
skvladc309e0e2016-07-29 00:15:20392 error_ = ENOTCONN;
henrike@webrtc.org269fb4b2014-10-28 22:20:11393 return SOCKET_ERROR;
394 }
zhihuang5ecf16c2016-06-02 00:09:15395 stats_.sent_total_packets++;
Qingsi Wang6e641e62018-04-12 03:14:17396 rtc::PacketOptions modified_options(options);
397 static_cast<TCPPort*>(port_)->CopyPortInformationToPacketInfo(
398 &modified_options.info_signaled_after_sent);
399 int sent = socket_->Send(data, size, modified_options);
Jonas Oreland3c5d5822020-12-14 11:45:05400 int64_t now = rtc::TimeMillis();
henrike@webrtc.org269fb4b2014-10-28 22:20:11401 if (sent < 0) {
zhihuang5ecf16c2016-06-02 00:09:15402 stats_.sent_discarded_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11403 error_ = socket_->GetError();
404 } else {
Jonas Oreland3c5d5822020-12-14 11:45:05405 send_rate_tracker_.AddSamplesAtTime(now, sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11406 }
Jonas Oreland3c5d5822020-12-14 11:45:05407 last_send_data_ = now;
henrike@webrtc.org269fb4b2014-10-28 22:20:11408 return sent;
409}
410
411int TCPConnection::GetError() {
412 return error_;
413}
414
Guo-wei Shiehbe508a12015-04-06 19:48:47415void TCPConnection::OnConnectionRequestResponse(ConnectionRequest* req,
416 StunMessage* response) {
Guo-wei Shiehb5940412015-08-24 18:58:03417 // Process the STUN response before we inform upper layer ready to send.
Guo-wei Shiehbe508a12015-04-06 19:48:47418 Connection::OnConnectionRequestResponse(req, response);
Guo-wei Shiehb5940412015-08-24 18:58:03419
420 // If we're in the state of pretending to be writeable, we should inform the
421 // upper layer it's ready to send again as previous EWOULDLBLOCK from socket
422 // would have stopped the outgoing stream.
423 if (pretending_to_be_writable_) {
424 Connection::OnReadyToSend();
425 }
426 pretending_to_be_writable_ = false;
nisseede5da42017-01-12 13:15:36427 RTC_DCHECK(write_state() == STATE_WRITABLE);
Guo-wei Shiehbe508a12015-04-06 19:48:47428}
429
henrike@webrtc.org269fb4b2014-10-28 22:20:11430void TCPConnection::OnConnect(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 13:15:36431 RTC_DCHECK(socket == socket_.get());
deadbeef5c3c1042017-08-04 22:01:57432 // Do not use this port if the socket bound to an address not associated with
433 // the desired network interface. This is seen in Chrome, where TCP sockets
434 // cannot be given a binding address, and the platform is expected to pick
435 // the correct local address.
436 //
437 // However, there are two situations in which we allow the bound address to
438 // not be one of the addresses of the requested interface:
439 // 1. The bound address is the loopback address. This happens when a proxy
440 // forces TCP to bind to only the localhost address (see issue 3927).
441 // 2. The bound address is the "any address". This happens when
442 // multiple_routes is disabled (see issue 4780).
443 //
444 // Note that, aside from minor differences in log statements, this logic is
445 // identical to that in TurnPort.
446 const rtc::SocketAddress& socket_address = socket->GetLocalAddress();
Steve Antonae226f62019-01-29 20:47:38447 if (absl::c_any_of(port_->Network()->GetIPs(),
448 [socket_address](const rtc::InterfaceAddress& addr) {
449 return socket_address.ipaddr() == addr;
450 })) {
Yves Gerey665174f2018-06-19 13:03:05451 RTC_LOG(LS_VERBOSE) << ToString() << ": Connection established to "
Jonas Olssond7d762d2018-03-28 07:47:51452 << socket->GetRemoteAddress().ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11453 } else {
deadbeef5c3c1042017-08-04 22:01:57454 if (socket->GetLocalAddress().IsLoopbackIP()) {
Mirko Bonadei675513b2017-11-09 10:09:25455 RTC_LOG(LS_WARNING) << "Socket is bound to the address:"
Qingsi Wang20232a92019-09-06 19:51:17456 << socket_address.ipaddr().ToSensitiveString()
Taylor Brandstetter3ba7a572018-03-02 18:58:25457 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 10:09:25458 << port_->Network()->ToString()
459 << ". Still allowing it since it's localhost.";
deadbeef5c3c1042017-08-04 22:01:57460 } else if (IPIsAny(port_->Network()->GetBestIP())) {
Mirko Bonadei675513b2017-11-09 10:09:25461 RTC_LOG(LS_WARNING)
462 << "Socket is bound to the address:"
Qingsi Wang20232a92019-09-06 19:51:17463 << socket_address.ipaddr().ToSensitiveString()
Taylor Brandstetter3ba7a572018-03-02 18:58:25464 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 10:09:25465 << port_->Network()->ToString()
466 << ". Still allowing it since it's the 'any' address"
Jonas Olssond7d762d2018-03-28 07:47:51467 ", possibly caused by multiple_routes being disabled.";
deadbeef5c3c1042017-08-04 22:01:57468 } else {
Mirko Bonadei675513b2017-11-09 10:09:25469 RTC_LOG(LS_WARNING) << "Dropping connection as TCP socket bound to IP "
Qingsi Wang20232a92019-09-06 19:51:17470 << socket_address.ipaddr().ToSensitiveString()
Taylor Brandstetter3ba7a572018-03-02 18:58:25471 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 10:09:25472 << port_->Network()->ToString();
deadbeef5c3c1042017-08-04 22:01:57473 OnClose(socket, 0);
474 return;
475 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11476 }
tommi5ce1a2a2016-05-14 10:19:31477
478 // Connection is established successfully.
479 set_connected(true);
480 connection_pending_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11481}
482
483void TCPConnection::OnClose(rtc::AsyncPacketSocket* socket, int error) {
nisseede5da42017-01-12 13:15:36484 RTC_DCHECK(socket == socket_.get());
Yves Gerey665174f2018-06-19 13:03:05485 RTC_LOG(LS_INFO) << ToString() << ": Connection closed with error " << error;
Guo-wei Shiehbe508a12015-04-06 19:48:47486
487 // Guard against the condition where IPC socket will call OnClose for every
488 // packet it can't send.
489 if (connected()) {
490 set_connected(false);
Guo-wei Shieh1eb87c72015-08-25 18:02:55491
492 // Prevent the connection from being destroyed by redundant SignalClose
493 // events.
Guo-wei Shiehbe508a12015-04-06 19:48:47494 pretending_to_be_writable_ = true;
495
496 // We don't attempt reconnect right here. This is to avoid a case where the
497 // shutdown is intentional and reconnect is not necessary. We only reconnect
498 // when the connection is used to Send() or Ping().
Taylor Brandstetter5d97a9a2016-06-10 21:17:27499 port()->thread()->PostDelayed(RTC_FROM_HERE, reconnection_timeout(), this,
Guo-wei Shiehbe508a12015-04-06 19:48:47500 MSG_TCPCONNECTION_DELAYED_ONCLOSE);
Guo-wei Shieh1eb87c72015-08-25 18:02:55501 } else if (!pretending_to_be_writable_) {
502 // OnClose could be called when the underneath socket times out during the
Artem Titov2dbb4c92021-07-26 13:12:41503 // initial connect() (i.e. `pretending_to_be_writable_` is false) . We have
Guo-wei Shieh1eb87c72015-08-25 18:02:55504 // to manually destroy here as this connection, as never connected, will not
505 // be scheduled for ping to trigger destroy.
506 Destroy();
Guo-wei Shiehbe508a12015-04-06 19:48:47507 }
508}
509
510void TCPConnection::OnMessage(rtc::Message* pmsg) {
511 switch (pmsg->message_id) {
512 case MSG_TCPCONNECTION_DELAYED_ONCLOSE:
513 // If this connection can't become connected and writable again in 5
514 // seconds, it's time to tear this down. This is the case for the original
515 // TCP connection on passive side during a reconnect.
516 if (pretending_to_be_writable_) {
Guo-wei Shieh1eb87c72015-08-25 18:02:55517 Destroy();
Guo-wei Shiehbe508a12015-04-06 19:48:47518 }
519 break;
Jonas Oreland7a284e12020-01-28 08:21:54520 case MSG_TCPCONNECTION_FAILED_CREATE_SOCKET:
521 FailAndPrune();
522 break;
Guo-wei Shiehbe508a12015-04-06 19:48:47523 default:
524 Connection::OnMessage(pmsg);
525 }
526}
527
528void TCPConnection::MaybeReconnect() {
529 // Only reconnect for an outgoing TCPConnection when OnClose was signaled and
530 // no outstanding reconnect is pending.
531 if (connected() || connection_pending_ || !outgoing_) {
532 return;
533 }
534
Jonas Olssond7d762d2018-03-28 07:47:51535 RTC_LOG(LS_INFO) << ToString()
536 << ": TCP Connection with remote is closed, "
537 "trying to reconnect";
Guo-wei Shiehbe508a12015-04-06 19:48:47538
539 CreateOutgoingTcpSocket();
540 error_ = EPIPE;
henrike@webrtc.org269fb4b2014-10-28 22:20:11541}
542
Yves Gerey665174f2018-06-19 13:03:05543void TCPConnection::OnReadPacket(rtc::AsyncPacketSocket* socket,
544 const char* data,
545 size_t size,
546 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 12:01:41547 const int64_t& packet_time_us) {
nisseede5da42017-01-12 13:15:36548 RTC_DCHECK(socket == socket_.get());
Niels Möllere6933812018-11-05 12:01:41549 Connection::OnReadPacket(data, size, packet_time_us);
henrike@webrtc.org269fb4b2014-10-28 22:20:11550}
551
552void TCPConnection::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 13:15:36553 RTC_DCHECK(socket == socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11554 Connection::OnReadyToSend();
555}
556
Guo-wei Shiehbe508a12015-04-06 19:48:47557void TCPConnection::CreateOutgoingTcpSocket() {
nisseede5da42017-01-12 13:15:36558 RTC_DCHECK(outgoing_);
Guo-wei Shiehbe508a12015-04-06 19:48:47559 int opts = (remote_candidate().protocol() == SSLTCP_PROTOCOL_NAME)
hnsl04833622017-01-09 16:35:45560 ? rtc::PacketSocketFactory::OPT_TLS_FAKE
Guo-wei Shiehbe508a12015-04-06 19:48:47561 : 0;
Patrik Höglund662e31f2019-09-05 12:35:04562 rtc::PacketSocketTcpOptions tcp_opts;
563 tcp_opts.opts = opts;
Guo-wei Shiehbe508a12015-04-06 19:48:47564 socket_.reset(port()->socket_factory()->CreateClientTcpSocket(
deadbeef5c3c1042017-08-04 22:01:57565 rtc::SocketAddress(port()->Network()->GetBestIP(), 0),
566 remote_candidate().address(), port()->proxy(), port()->user_agent(),
Patrik Höglund662e31f2019-09-05 12:35:04567 tcp_opts));
Guo-wei Shiehbe508a12015-04-06 19:48:47568 if (socket_) {
Yves Gerey665174f2018-06-19 13:03:05569 RTC_LOG(LS_VERBOSE) << ToString() << ": Connecting from "
Jonas Olssond7d762d2018-03-28 07:47:51570 << socket_->GetLocalAddress().ToSensitiveString()
571 << " to "
572 << remote_candidate().address().ToSensitiveString();
Guo-wei Shiehbe508a12015-04-06 19:48:47573 set_connected(false);
574 connection_pending_ = true;
575 ConnectSocketSignals(socket_.get());
576 } else {
Yves Gerey665174f2018-06-19 13:03:05577 RTC_LOG(LS_WARNING) << ToString() << ": Failed to create connection to "
Jonas Olssond7d762d2018-03-28 07:47:51578 << remote_candidate().address().ToSensitiveString();
Jonas Oreland7a284e12020-01-28 08:21:54579 // We can't FailAndPrune directly here. FailAndPrune and deletes all
580 // the StunRequests from the request_map_. And if this is in the stack
581 // of Connection::Ping(), we are still using the request.
582 // Unwind the stack and defer the FailAndPrune.
583 set_state(IceCandidatePairState::FAILED);
584 port()->thread()->Post(RTC_FROM_HERE, this,
585 MSG_TCPCONNECTION_FAILED_CREATE_SOCKET);
Guo-wei Shiehbe508a12015-04-06 19:48:47586 }
587}
588
589void TCPConnection::ConnectSocketSignals(rtc::AsyncPacketSocket* socket) {
590 if (outgoing_) {
591 socket->SignalConnect.connect(this, &TCPConnection::OnConnect);
592 }
593 socket->SignalReadPacket.connect(this, &TCPConnection::OnReadPacket);
594 socket->SignalReadyToSend.connect(this, &TCPConnection::OnReadyToSend);
595 socket->SignalClose.connect(this, &TCPConnection::OnClose);
596}
597
henrike@webrtc.org269fb4b2014-10-28 22:20:11598} // namespace cricket