blob: efbf62e49602f7d0455dd4826c3fd0b127219113 [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 *
21 * - PendingTCP: |connection_pending_| indicates whether there is an
22 * outstanding TCP connection in progress.
23 *
24 * - PretendWri: Tracked by |pretending_to_be_writable_|. Marking connection as
25 * 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"
Steve Anton10542f22019-01-11 17:11:0074#include "p2p/base/p2p_constants.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3175#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 17:11:0076#include "rtc_base/ip_address.h"
Yves Gerey3e707812018-11-28 15:47:4977#include "rtc_base/location.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3178#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 17:11:0079#include "rtc_base/net_helper.h"
80#include "rtc_base/rate_tracker.h"
Yves Gerey3e707812018-11-28 15:47:4981#include "rtc_base/third_party/sigslot/sigslot.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:1182
83namespace cricket {
84
85TCPPort::TCPPort(rtc::Thread* thread,
86 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:2287 rtc::Network* network,
Peter Boström0c4e06b2015-10-07 10:23:2188 uint16_t min_port,
89 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:2290 const std::string& username,
91 const std::string& password,
92 bool allow_listen)
Peter Boström0c4e06b2015-10-07 10:23:2193 : Port(thread,
94 LOCAL_PORT_TYPE,
95 factory,
96 network,
Peter Boström0c4e06b2015-10-07 10:23:2197 min_port,
98 max_port,
99 username,
100 password),
henrike@webrtc.org269fb4b2014-10-28 22:20:11101 allow_listen_(allow_listen),
102 socket_(NULL),
103 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 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11109}
110
111TCPPort::~TCPPort() {
112 delete socket_;
113 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 20:20:13121 if (!SupportsProtocol(address.protocol())) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11122 return NULL;
123 }
124
Philipp Hanckee283d1c2020-03-27 08:56:51125 if ((address.tcptype() == TCPTYPE_ACTIVE_STR &&
126 address.type() != PRFLX_PORT_TYPE) ||
henrike@webrtc.org269fb4b2014-10-28 22:20:11127 (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:11137 // 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 13:03:05148 if (rtc::AsyncPacketSocket* socket = GetIncoming(address.address(), true)) {
deadbeef06878292017-04-21 21:22:23149 // 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:11152 socket->SignalReadPacket.disconnect(this);
153 conn = new TCPConnection(this, address, socket);
154 } else {
deadbeef06878292017-04-21 21:22:23155 // 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:11157 conn = new TCPConnection(this, address);
deadbeef06878292017-04-21 21:22:23158 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:11162 }
honghaiz36f50e82016-06-01 22:57:03163 AddOrReplaceConnection(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11164 return conn;
165}
166
167void TCPPort::PrepareAddress() {
168 if (socket_) {
169 // If socket isn't bound yet the address will be added in
170 // OnAddressReady(). Socket may be in the CLOSED state if Listen()
171 // failed, we still want to add the socket address.
Mirko Bonadei675513b2017-11-09 10:09:25172 RTC_LOG(LS_VERBOSE) << "Preparing TCP address, current state: "
173 << socket_->GetState();
henrike@webrtc.org269fb4b2014-10-28 22:20:11174 if (socket_->GetState() == rtc::AsyncPacketSocket::STATE_BOUND ||
175 socket_->GetState() == rtc::AsyncPacketSocket::STATE_CLOSED)
176 AddAddress(socket_->GetLocalAddress(), socket_->GetLocalAddress(),
Guo-wei Shieh3d564c12015-08-19 23:51:15177 rtc::SocketAddress(), TCP_PROTOCOL_NAME, "",
178 TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE,
zhihuang26d99c22017-02-13 20:47:27179 ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11180 } else {
Jonas Olssond7d762d2018-03-28 07:47:51181 RTC_LOG(LS_INFO) << ToString()
182 << ": Not listening due to firewall restrictions.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11183 // Note: We still add the address, since otherwise the remote side won't
Guo-wei Shieh310b0932015-11-18 03:15:50184 // recognize our incoming TCP connections. According to
185 // https://tools.ietf.org/html/rfc6544#section-4.5, for active candidate,
deadbeef5c3c1042017-08-04 22:01:57186 // the port must be set to the discard port, i.e. 9. We can't be 100% sure
187 // which IP address will actually be used, so GetBestIP is as good as we
188 // can do.
189 // TODO(deadbeef): We could do something like create a dummy socket just to
190 // see what IP we get. But that may be overkill.
191 AddAddress(rtc::SocketAddress(Network()->GetBestIP(), DISCARD_PORT),
192 rtc::SocketAddress(Network()->GetBestIP(), 0),
193 rtc::SocketAddress(), TCP_PROTOCOL_NAME, "", TCPTYPE_ACTIVE_STR,
194 LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11195 }
196}
197
Yves Gerey665174f2018-06-19 13:03:05198int TCPPort::SendTo(const void* data,
199 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11200 const rtc::SocketAddress& addr,
201 const rtc::PacketOptions& options,
202 bool payload) {
Yves Gerey665174f2018-06-19 13:03:05203 rtc::AsyncPacketSocket* socket = NULL;
Guo-wei Shiehbe508a12015-04-06 19:48:47204 TCPConnection* conn = static_cast<TCPConnection*>(GetConnection(addr));
205
206 // For Connection, this is the code path used by Ping() to establish
207 // WRITABLE. It has to send through the socket directly as TCPConnection::Send
208 // checks writability.
209 if (conn) {
210 if (!conn->connected()) {
211 conn->MaybeReconnect();
212 return SOCKET_ERROR;
213 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11214 socket = conn->socket();
Harald Alvestranddc800172020-01-06 19:01:36215 if (!socket) {
216 // The failure to initialize should have been logged elsewhere,
217 // so this log is not important.
218 RTC_LOG(LS_INFO) << ToString()
219 << ": Attempted to send to an uninitialized socket: "
220 << addr.ToSensitiveString();
221 error_ = EHOSTUNREACH;
222 return SOCKET_ERROR;
223 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11224 } else {
225 socket = GetIncoming(addr);
Harald Alvestranddc800172020-01-06 19:01:36226 if (!socket) {
227 RTC_LOG(LS_ERROR) << ToString()
228 << ": Attempted to send to an unknown destination: "
229 << addr.ToSensitiveString();
230 error_ = EHOSTUNREACH;
231 return SOCKET_ERROR;
232 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11233 }
Qingsi Wang6e641e62018-04-12 03:14:17234 rtc::PacketOptions modified_options(options);
235 CopyPortInformationToPacketInfo(&modified_options.info_signaled_after_sent);
236 int sent = socket->Send(data, size, modified_options);
henrike@webrtc.org269fb4b2014-10-28 22:20:11237 if (sent < 0) {
238 error_ = socket->GetError();
Guo-wei Shiehbe508a12015-04-06 19:48:47239 // Error from this code path for a Connection (instead of from a bare
240 // socket) will not trigger reconnecting. In theory, this shouldn't matter
241 // as OnClose should always be called and set connected to false.
Yves Gerey665174f2018-06-19 13:03:05242 RTC_LOG(LS_ERROR) << ToString() << ": TCP send of " << size
243 << " bytes failed with error " << error_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11244 }
245 return sent;
246}
247
248int TCPPort::GetOption(rtc::Socket::Option opt, int* value) {
249 if (socket_) {
250 return socket_->GetOption(opt, value);
251 } else {
252 return SOCKET_ERROR;
253 }
254}
255
256int TCPPort::SetOption(rtc::Socket::Option opt, int value) {
257 if (socket_) {
258 return socket_->SetOption(opt, value);
259 } else {
260 return SOCKET_ERROR;
261 }
262}
263
264int TCPPort::GetError() {
265 return error_;
266}
267
Steve Anton1cf1b7d2017-10-30 17:00:15268bool 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
henrike@webrtc.org269fb4b2014-10-28 22:20:11276void TCPPort::OnNewConnection(rtc::AsyncPacketSocket* socket,
277 rtc::AsyncPacketSocket* new_socket) {
nisseede5da42017-01-12 13:15:36278 RTC_DCHECK(socket == socket_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11279
280 Incoming incoming;
281 incoming.addr = new_socket->GetRemoteAddress();
282 incoming.socket = new_socket;
283 incoming.socket->SignalReadPacket.connect(this, &TCPPort::OnReadPacket);
284 incoming.socket->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
Stefan Holmer55674ff2016-01-14 14:49:16285 incoming.socket->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11286
Yves Gerey665174f2018-06-19 13:03:05287 RTC_LOG(LS_VERBOSE) << ToString() << ": Accepted connection from "
Jonas Olssond7d762d2018-03-28 07:47:51288 << incoming.addr.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11289 incoming_.push_back(incoming);
290}
291
deadbeef1ee21252017-06-13 22:49:45292void TCPPort::TryCreateServerSocket() {
293 socket_ = socket_factory()->CreateServerTcpSocket(
deadbeef5c3c1042017-08-04 22:01:57294 rtc::SocketAddress(Network()->GetBestIP(), 0), min_port(), max_port(),
295 false /* ssl */);
deadbeef1ee21252017-06-13 22:49:45296 if (!socket_) {
Jonas Olssond7d762d2018-03-28 07:47:51297 RTC_LOG(LS_WARNING)
298 << ToString()
299 << ": TCP server socket creation failed; continuing anyway.";
deadbeef1ee21252017-06-13 22:49:45300 return;
301 }
302 socket_->SignalNewConnection.connect(this, &TCPPort::OnNewConnection);
303 socket_->SignalAddressReady.connect(this, &TCPPort::OnAddressReady);
304}
305
Yves Gerey665174f2018-06-19 13:03:05306rtc::AsyncPacketSocket* TCPPort::GetIncoming(const rtc::SocketAddress& addr,
307 bool remove) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11308 rtc::AsyncPacketSocket* socket = NULL;
309 for (std::list<Incoming>::iterator it = incoming_.begin();
310 it != incoming_.end(); ++it) {
311 if (it->addr == addr) {
312 socket = it->socket;
313 if (remove)
314 incoming_.erase(it);
315 break;
316 }
317 }
318 return socket;
319}
320
321void TCPPort::OnReadPacket(rtc::AsyncPacketSocket* socket,
Yves Gerey665174f2018-06-19 13:03:05322 const char* data,
323 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11324 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 12:01:41325 const int64_t& packet_time_us) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11326 Port::OnReadPacket(data, size, remote_addr, PROTO_TCP);
327}
328
Stefan Holmer55674ff2016-01-14 14:49:16329void TCPPort::OnSentPacket(rtc::AsyncPacketSocket* socket,
330 const rtc::SentPacket& sent_packet) {
Stefan Holmer55674ff2016-01-14 14:49:16331 PortInterface::SignalSentPacket(sent_packet);
332}
333
henrike@webrtc.org269fb4b2014-10-28 22:20:11334void TCPPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
335 Port::OnReadyToSend();
336}
337
338void TCPPort::OnAddressReady(rtc::AsyncPacketSocket* socket,
339 const rtc::SocketAddress& address) {
Guo-wei Shieh3d564c12015-08-19 23:51:15340 AddAddress(address, address, rtc::SocketAddress(), TCP_PROTOCOL_NAME, "",
341 TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP,
zhihuang26d99c22017-02-13 20:47:27342 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11343}
344
Qingsi Wang22e623a2018-03-13 17:53:57345// TODO(qingsi): |CONNECTION_WRITE_CONNECT_TIMEOUT| is overriden by
346// |ice_unwritable_timeout| in IceConfig when determining the writability state.
347// Replace this constant with the config parameter assuming the default value if
348// we decide it is also applicable here.
Guo-wei Shiehbe508a12015-04-06 19:48:47349TCPConnection::TCPConnection(TCPPort* port,
350 const Candidate& candidate,
henrike@webrtc.org269fb4b2014-10-28 22:20:11351 rtc::AsyncPacketSocket* socket)
Guo-wei Shiehbe508a12015-04-06 19:48:47352 : Connection(port, 0, candidate),
353 socket_(socket),
354 error_(0),
355 outgoing_(socket == NULL),
356 connection_pending_(false),
357 pretending_to_be_writable_(false),
358 reconnection_timeout_(cricket::CONNECTION_WRITE_CONNECT_TIMEOUT) {
359 if (outgoing_) {
360 CreateOutgoingTcpSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11361 } else {
deadbeef5c3c1042017-08-04 22:01:57362 // Incoming connections should match one of the network addresses. Same as
363 // what's being checked in OnConnect, but just DCHECKing here.
Jonas Olssond7d762d2018-03-28 07:47:51364 RTC_LOG(LS_VERBOSE) << ToString() << ": socket ipaddr: "
Qingsi Wang20232a92019-09-06 19:51:17365 << socket_->GetLocalAddress().ToSensitiveString()
Jonas Olssond7d762d2018-03-28 07:47:51366 << ", port() Network:" << port->Network()->ToString();
Steve Antonae226f62019-01-29 20:47:38367 RTC_DCHECK(absl::c_any_of(
368 port_->Network()->GetIPs(), [this](const rtc::InterfaceAddress& addr) {
369 return socket_->GetLocalAddress().ipaddr() == addr;
370 }));
Guo-wei Shiehbe508a12015-04-06 19:48:47371 ConnectSocketSignals(socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11372 }
373}
374
Yves Gerey665174f2018-06-19 13:03:05375TCPConnection::~TCPConnection() {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11376
Yves Gerey665174f2018-06-19 13:03:05377int TCPConnection::Send(const void* data,
378 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11379 const rtc::PacketOptions& options) {
380 if (!socket_) {
381 error_ = ENOTCONN;
382 return SOCKET_ERROR;
383 }
384
Guo-wei Shiehbe508a12015-04-06 19:48:47385 // Sending after OnClose on active side will trigger a reconnect for a
386 // outgoing connection. Note that the write state is still WRITABLE as we want
387 // to spend a few seconds attempting a reconnect before saying we're
388 // unwritable.
389 if (!connected()) {
390 MaybeReconnect();
391 return SOCKET_ERROR;
392 }
393
394 // Note that this is important to put this after the previous check to give
395 // the connection a chance to reconnect.
396 if (pretending_to_be_writable_ || write_state() != STATE_WRITABLE) {
Steve Anton6c38cc72017-11-29 18:25:58397 // TODO(?): Should STATE_WRITE_TIMEOUT return a non-blocking error?
skvladc309e0e2016-07-29 00:15:20398 error_ = ENOTCONN;
henrike@webrtc.org269fb4b2014-10-28 22:20:11399 return SOCKET_ERROR;
400 }
zhihuang5ecf16c2016-06-02 00:09:15401 stats_.sent_total_packets++;
Qingsi Wang6e641e62018-04-12 03:14:17402 rtc::PacketOptions modified_options(options);
403 static_cast<TCPPort*>(port_)->CopyPortInformationToPacketInfo(
404 &modified_options.info_signaled_after_sent);
405 int sent = socket_->Send(data, size, modified_options);
henrike@webrtc.org269fb4b2014-10-28 22:20:11406 if (sent < 0) {
zhihuang5ecf16c2016-06-02 00:09:15407 stats_.sent_discarded_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11408 error_ = socket_->GetError();
409 } else {
Tim Psiaki63046262015-09-14 17:38:08410 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11411 }
412 return sent;
413}
414
415int TCPConnection::GetError() {
416 return error_;
417}
418
Guo-wei Shiehbe508a12015-04-06 19:48:47419void TCPConnection::OnConnectionRequestResponse(ConnectionRequest* req,
420 StunMessage* response) {
Guo-wei Shiehb5940412015-08-24 18:58:03421 // Process the STUN response before we inform upper layer ready to send.
Guo-wei Shiehbe508a12015-04-06 19:48:47422 Connection::OnConnectionRequestResponse(req, response);
Guo-wei Shiehb5940412015-08-24 18:58:03423
424 // If we're in the state of pretending to be writeable, we should inform the
425 // upper layer it's ready to send again as previous EWOULDLBLOCK from socket
426 // would have stopped the outgoing stream.
427 if (pretending_to_be_writable_) {
428 Connection::OnReadyToSend();
429 }
430 pretending_to_be_writable_ = false;
nisseede5da42017-01-12 13:15:36431 RTC_DCHECK(write_state() == STATE_WRITABLE);
Guo-wei Shiehbe508a12015-04-06 19:48:47432}
433
henrike@webrtc.org269fb4b2014-10-28 22:20:11434void TCPConnection::OnConnect(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 13:15:36435 RTC_DCHECK(socket == socket_.get());
deadbeef5c3c1042017-08-04 22:01:57436 // Do not use this port if the socket bound to an address not associated with
437 // the desired network interface. This is seen in Chrome, where TCP sockets
438 // cannot be given a binding address, and the platform is expected to pick
439 // the correct local address.
440 //
441 // However, there are two situations in which we allow the bound address to
442 // not be one of the addresses of the requested interface:
443 // 1. The bound address is the loopback address. This happens when a proxy
444 // forces TCP to bind to only the localhost address (see issue 3927).
445 // 2. The bound address is the "any address". This happens when
446 // multiple_routes is disabled (see issue 4780).
447 //
448 // Note that, aside from minor differences in log statements, this logic is
449 // identical to that in TurnPort.
450 const rtc::SocketAddress& socket_address = socket->GetLocalAddress();
Steve Antonae226f62019-01-29 20:47:38451 if (absl::c_any_of(port_->Network()->GetIPs(),
452 [socket_address](const rtc::InterfaceAddress& addr) {
453 return socket_address.ipaddr() == addr;
454 })) {
Yves Gerey665174f2018-06-19 13:03:05455 RTC_LOG(LS_VERBOSE) << ToString() << ": Connection established to "
Jonas Olssond7d762d2018-03-28 07:47:51456 << socket->GetRemoteAddress().ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11457 } else {
deadbeef5c3c1042017-08-04 22:01:57458 if (socket->GetLocalAddress().IsLoopbackIP()) {
Mirko Bonadei675513b2017-11-09 10:09:25459 RTC_LOG(LS_WARNING) << "Socket is bound to the address:"
Qingsi Wang20232a92019-09-06 19:51:17460 << socket_address.ipaddr().ToSensitiveString()
Taylor Brandstetter3ba7a572018-03-02 18:58:25461 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 10:09:25462 << port_->Network()->ToString()
463 << ". Still allowing it since it's localhost.";
deadbeef5c3c1042017-08-04 22:01:57464 } else if (IPIsAny(port_->Network()->GetBestIP())) {
Mirko Bonadei675513b2017-11-09 10:09:25465 RTC_LOG(LS_WARNING)
466 << "Socket is bound to the address:"
Qingsi Wang20232a92019-09-06 19:51:17467 << socket_address.ipaddr().ToSensitiveString()
Taylor Brandstetter3ba7a572018-03-02 18:58:25468 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 10:09:25469 << port_->Network()->ToString()
470 << ". Still allowing it since it's the 'any' address"
Jonas Olssond7d762d2018-03-28 07:47:51471 ", possibly caused by multiple_routes being disabled.";
deadbeef5c3c1042017-08-04 22:01:57472 } else {
Mirko Bonadei675513b2017-11-09 10:09:25473 RTC_LOG(LS_WARNING) << "Dropping connection as TCP socket bound to IP "
Qingsi Wang20232a92019-09-06 19:51:17474 << socket_address.ipaddr().ToSensitiveString()
Taylor Brandstetter3ba7a572018-03-02 18:58:25475 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 10:09:25476 << port_->Network()->ToString();
deadbeef5c3c1042017-08-04 22:01:57477 OnClose(socket, 0);
478 return;
479 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11480 }
tommi5ce1a2a2016-05-14 10:19:31481
482 // Connection is established successfully.
483 set_connected(true);
484 connection_pending_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11485}
486
487void TCPConnection::OnClose(rtc::AsyncPacketSocket* socket, int error) {
nisseede5da42017-01-12 13:15:36488 RTC_DCHECK(socket == socket_.get());
Yves Gerey665174f2018-06-19 13:03:05489 RTC_LOG(LS_INFO) << ToString() << ": Connection closed with error " << error;
Guo-wei Shiehbe508a12015-04-06 19:48:47490
491 // Guard against the condition where IPC socket will call OnClose for every
492 // packet it can't send.
493 if (connected()) {
494 set_connected(false);
Guo-wei Shieh1eb87c72015-08-25 18:02:55495
496 // Prevent the connection from being destroyed by redundant SignalClose
497 // events.
Guo-wei Shiehbe508a12015-04-06 19:48:47498 pretending_to_be_writable_ = true;
499
500 // We don't attempt reconnect right here. This is to avoid a case where the
501 // shutdown is intentional and reconnect is not necessary. We only reconnect
502 // when the connection is used to Send() or Ping().
Taylor Brandstetter5d97a9a2016-06-10 21:17:27503 port()->thread()->PostDelayed(RTC_FROM_HERE, reconnection_timeout(), this,
Guo-wei Shiehbe508a12015-04-06 19:48:47504 MSG_TCPCONNECTION_DELAYED_ONCLOSE);
Guo-wei Shieh1eb87c72015-08-25 18:02:55505 } else if (!pretending_to_be_writable_) {
506 // OnClose could be called when the underneath socket times out during the
507 // initial connect() (i.e. |pretending_to_be_writable_| is false) . We have
508 // to manually destroy here as this connection, as never connected, will not
509 // be scheduled for ping to trigger destroy.
510 Destroy();
Guo-wei Shiehbe508a12015-04-06 19:48:47511 }
512}
513
514void TCPConnection::OnMessage(rtc::Message* pmsg) {
515 switch (pmsg->message_id) {
516 case MSG_TCPCONNECTION_DELAYED_ONCLOSE:
517 // If this connection can't become connected and writable again in 5
518 // seconds, it's time to tear this down. This is the case for the original
519 // TCP connection on passive side during a reconnect.
520 if (pretending_to_be_writable_) {
Guo-wei Shieh1eb87c72015-08-25 18:02:55521 Destroy();
Guo-wei Shiehbe508a12015-04-06 19:48:47522 }
523 break;
Jonas Oreland7a284e12020-01-28 08:21:54524 case MSG_TCPCONNECTION_FAILED_CREATE_SOCKET:
525 FailAndPrune();
526 break;
Guo-wei Shiehbe508a12015-04-06 19:48:47527 default:
528 Connection::OnMessage(pmsg);
529 }
530}
531
532void TCPConnection::MaybeReconnect() {
533 // Only reconnect for an outgoing TCPConnection when OnClose was signaled and
534 // no outstanding reconnect is pending.
535 if (connected() || connection_pending_ || !outgoing_) {
536 return;
537 }
538
Jonas Olssond7d762d2018-03-28 07:47:51539 RTC_LOG(LS_INFO) << ToString()
540 << ": TCP Connection with remote is closed, "
541 "trying to reconnect";
Guo-wei Shiehbe508a12015-04-06 19:48:47542
543 CreateOutgoingTcpSocket();
544 error_ = EPIPE;
henrike@webrtc.org269fb4b2014-10-28 22:20:11545}
546
Yves Gerey665174f2018-06-19 13:03:05547void TCPConnection::OnReadPacket(rtc::AsyncPacketSocket* socket,
548 const char* data,
549 size_t size,
550 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 12:01:41551 const int64_t& packet_time_us) {
nisseede5da42017-01-12 13:15:36552 RTC_DCHECK(socket == socket_.get());
Niels Möllere6933812018-11-05 12:01:41553 Connection::OnReadPacket(data, size, packet_time_us);
henrike@webrtc.org269fb4b2014-10-28 22:20:11554}
555
556void TCPConnection::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 13:15:36557 RTC_DCHECK(socket == socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11558 Connection::OnReadyToSend();
559}
560
Guo-wei Shiehbe508a12015-04-06 19:48:47561void TCPConnection::CreateOutgoingTcpSocket() {
nisseede5da42017-01-12 13:15:36562 RTC_DCHECK(outgoing_);
Guo-wei Shiehbe508a12015-04-06 19:48:47563 int opts = (remote_candidate().protocol() == SSLTCP_PROTOCOL_NAME)
hnsl04833622017-01-09 16:35:45564 ? rtc::PacketSocketFactory::OPT_TLS_FAKE
Guo-wei Shiehbe508a12015-04-06 19:48:47565 : 0;
Patrik Höglund662e31f2019-09-05 12:35:04566 rtc::PacketSocketTcpOptions tcp_opts;
567 tcp_opts.opts = opts;
Guo-wei Shiehbe508a12015-04-06 19:48:47568 socket_.reset(port()->socket_factory()->CreateClientTcpSocket(
deadbeef5c3c1042017-08-04 22:01:57569 rtc::SocketAddress(port()->Network()->GetBestIP(), 0),
570 remote_candidate().address(), port()->proxy(), port()->user_agent(),
Patrik Höglund662e31f2019-09-05 12:35:04571 tcp_opts));
Guo-wei Shiehbe508a12015-04-06 19:48:47572 if (socket_) {
Yves Gerey665174f2018-06-19 13:03:05573 RTC_LOG(LS_VERBOSE) << ToString() << ": Connecting from "
Jonas Olssond7d762d2018-03-28 07:47:51574 << socket_->GetLocalAddress().ToSensitiveString()
575 << " to "
576 << remote_candidate().address().ToSensitiveString();
Guo-wei Shiehbe508a12015-04-06 19:48:47577 set_connected(false);
578 connection_pending_ = true;
579 ConnectSocketSignals(socket_.get());
580 } else {
Yves Gerey665174f2018-06-19 13:03:05581 RTC_LOG(LS_WARNING) << ToString() << ": Failed to create connection to "
Jonas Olssond7d762d2018-03-28 07:47:51582 << remote_candidate().address().ToSensitiveString();
Jonas Oreland7a284e12020-01-28 08:21:54583 // We can't FailAndPrune directly here. FailAndPrune and deletes all
584 // the StunRequests from the request_map_. And if this is in the stack
585 // of Connection::Ping(), we are still using the request.
586 // Unwind the stack and defer the FailAndPrune.
587 set_state(IceCandidatePairState::FAILED);
588 port()->thread()->Post(RTC_FROM_HERE, this,
589 MSG_TCPCONNECTION_FAILED_CREATE_SOCKET);
Guo-wei Shiehbe508a12015-04-06 19:48:47590 }
591}
592
593void TCPConnection::ConnectSocketSignals(rtc::AsyncPacketSocket* socket) {
594 if (outgoing_) {
595 socket->SignalConnect.connect(this, &TCPConnection::OnConnect);
596 }
597 socket->SignalReadPacket.connect(this, &TCPConnection::OnReadPacket);
598 socket->SignalReadyToSend.connect(this, &TCPConnection::OnReadyToSend);
599 socket->SignalClose.connect(this, &TCPConnection::OnClose);
600}
601
henrike@webrtc.org269fb4b2014-10-28 22:20:11602} // namespace cricket