blob: af4938936430159ba5b6c29a00094e7e7d560d11 [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 *
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 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>
70#include <algorithm>
Steve Anton6c38cc72017-11-29 10:25:58 -080071#include <vector>
72
Steve Anton10542f22019-01-11 09:11:00 -080073#include "p2p/base/p2p_constants.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020074#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080075#include "rtc_base/ip_address.h"
Yves Gerey3e707812018-11-28 16:47:49 +010076#include "rtc_base/location.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020077#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080078#include "rtc_base/net_helper.h"
79#include "rtc_base/rate_tracker.h"
Yves Gerey3e707812018-11-28 16:47:49 +010080#include "rtc_base/third_party/sigslot/sigslot.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000081
82namespace cricket {
83
84TCPPort::TCPPort(rtc::Thread* thread,
85 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +000086 rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +020087 uint16_t min_port,
88 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +000089 const std::string& username,
90 const std::string& password,
91 bool allow_listen)
Peter Boström0c4e06b2015-10-07 12:23:21 +020092 : Port(thread,
93 LOCAL_PORT_TYPE,
94 factory,
95 network,
Peter Boström0c4e06b2015-10-07 12:23:21 +020096 min_port,
97 max_port,
98 username,
99 password),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000100 incoming_only_(false),
101 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: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() {
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 12:20:13 -0800121 if (!SupportsProtocol(address.protocol())) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000122 return NULL;
123 }
124
125 if (address.tcptype() == TCPTYPE_ACTIVE_STR ||
126 (address.tcptype().empty() && address.address().port() == 0)) {
127 // It's active only candidate, we should not try to create connections
128 // for these candidates.
129 return NULL;
130 }
131
132 // We can't accept TCP connections incoming on other ports
133 if (origin == ORIGIN_OTHER_PORT)
134 return NULL;
135
136 // Check if we are allowed to make outgoing TCP connections
137 if (incoming_only_ && (origin == ORIGIN_MESSAGE))
138 return NULL;
139
140 // We don't know how to act as an ssl server yet
141 if ((address.protocol() == SSLTCP_PROTOCOL_NAME) &&
142 (origin == ORIGIN_THIS_PORT)) {
143 return NULL;
144 }
145
146 if (!IsCompatibleAddress(address.address())) {
147 return NULL;
148 }
149
150 TCPConnection* conn = NULL;
Yves Gerey665174f2018-06-19 15:03:05 +0200151 if (rtc::AsyncPacketSocket* socket = GetIncoming(address.address(), true)) {
deadbeef06878292017-04-21 14:22:23 -0700152 // Incoming connection; we already created a socket and connected signals,
153 // so we need to hand off the "read packet" responsibility to
154 // TCPConnection.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000155 socket->SignalReadPacket.disconnect(this);
156 conn = new TCPConnection(this, address, socket);
157 } else {
deadbeef06878292017-04-21 14:22:23 -0700158 // Outgoing connection, which will create a new socket for which we still
159 // need to connect SignalReadyToSend and SignalSentPacket.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000160 conn = new TCPConnection(this, address);
deadbeef06878292017-04-21 14:22:23 -0700161 if (conn->socket()) {
162 conn->socket()->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
163 conn->socket()->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
164 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000165 }
honghaiz36f50e82016-06-01 15:57:03 -0700166 AddOrReplaceConnection(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000167 return conn;
168}
169
170void TCPPort::PrepareAddress() {
171 if (socket_) {
172 // If socket isn't bound yet the address will be added in
173 // OnAddressReady(). Socket may be in the CLOSED state if Listen()
174 // failed, we still want to add the socket address.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100175 RTC_LOG(LS_VERBOSE) << "Preparing TCP address, current state: "
176 << socket_->GetState();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000177 if (socket_->GetState() == rtc::AsyncPacketSocket::STATE_BOUND ||
178 socket_->GetState() == rtc::AsyncPacketSocket::STATE_CLOSED)
179 AddAddress(socket_->GetLocalAddress(), socket_->GetLocalAddress(),
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700180 rtc::SocketAddress(), TCP_PROTOCOL_NAME, "",
181 TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE,
zhihuang26d99c22017-02-13 12:47:27 -0800182 ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000183 } else {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200184 RTC_LOG(LS_INFO) << ToString()
185 << ": Not listening due to firewall restrictions.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000186 // Note: We still add the address, since otherwise the remote side won't
Guo-wei Shieh310b0932015-11-17 19:15:50 -0800187 // recognize our incoming TCP connections. According to
188 // https://tools.ietf.org/html/rfc6544#section-4.5, for active candidate,
deadbeef5c3c1042017-08-04 15:01:57 -0700189 // the port must be set to the discard port, i.e. 9. We can't be 100% sure
190 // which IP address will actually be used, so GetBestIP is as good as we
191 // can do.
192 // TODO(deadbeef): We could do something like create a dummy socket just to
193 // see what IP we get. But that may be overkill.
194 AddAddress(rtc::SocketAddress(Network()->GetBestIP(), DISCARD_PORT),
195 rtc::SocketAddress(Network()->GetBestIP(), 0),
196 rtc::SocketAddress(), TCP_PROTOCOL_NAME, "", TCPTYPE_ACTIVE_STR,
197 LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000198 }
199}
200
Yves Gerey665174f2018-06-19 15:03:05 +0200201int TCPPort::SendTo(const void* data,
202 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000203 const rtc::SocketAddress& addr,
204 const rtc::PacketOptions& options,
205 bool payload) {
Yves Gerey665174f2018-06-19 15:03:05 +0200206 rtc::AsyncPacketSocket* socket = NULL;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700207 TCPConnection* conn = static_cast<TCPConnection*>(GetConnection(addr));
208
209 // For Connection, this is the code path used by Ping() to establish
210 // WRITABLE. It has to send through the socket directly as TCPConnection::Send
211 // checks writability.
212 if (conn) {
213 if (!conn->connected()) {
214 conn->MaybeReconnect();
215 return SOCKET_ERROR;
216 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000217 socket = conn->socket();
218 } else {
219 socket = GetIncoming(addr);
220 }
221 if (!socket) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200222 RTC_LOG(LS_ERROR) << ToString()
223 << ": Attempted to send to an unknown destination: "
224 << addr.ToSensitiveString();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700225 return SOCKET_ERROR; // TODO(tbd): Set error_
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000226 }
Qingsi Wang6e641e62018-04-11 20:14:17 -0700227 rtc::PacketOptions modified_options(options);
228 CopyPortInformationToPacketInfo(&modified_options.info_signaled_after_sent);
229 int sent = socket->Send(data, size, modified_options);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000230 if (sent < 0) {
231 error_ = socket->GetError();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700232 // Error from this code path for a Connection (instead of from a bare
233 // socket) will not trigger reconnecting. In theory, this shouldn't matter
234 // as OnClose should always be called and set connected to false.
Yves Gerey665174f2018-06-19 15:03:05 +0200235 RTC_LOG(LS_ERROR) << ToString() << ": TCP send of " << size
236 << " bytes failed with error " << error_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000237 }
238 return sent;
239}
240
241int TCPPort::GetOption(rtc::Socket::Option opt, int* value) {
242 if (socket_) {
243 return socket_->GetOption(opt, value);
244 } else {
245 return SOCKET_ERROR;
246 }
247}
248
249int TCPPort::SetOption(rtc::Socket::Option opt, int value) {
250 if (socket_) {
251 return socket_->SetOption(opt, value);
252 } else {
253 return SOCKET_ERROR;
254 }
255}
256
257int TCPPort::GetError() {
258 return error_;
259}
260
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700261bool TCPPort::SupportsProtocol(const std::string& protocol) const {
262 return protocol == TCP_PROTOCOL_NAME || protocol == SSLTCP_PROTOCOL_NAME;
263}
264
265ProtocolType TCPPort::GetProtocol() const {
266 return PROTO_TCP;
267}
268
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000269void TCPPort::OnNewConnection(rtc::AsyncPacketSocket* socket,
270 rtc::AsyncPacketSocket* new_socket) {
nisseede5da42017-01-12 05:15:36 -0800271 RTC_DCHECK(socket == socket_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000272
273 Incoming incoming;
274 incoming.addr = new_socket->GetRemoteAddress();
275 incoming.socket = new_socket;
276 incoming.socket->SignalReadPacket.connect(this, &TCPPort::OnReadPacket);
277 incoming.socket->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
Stefan Holmer55674ff2016-01-14 15:49:16 +0100278 incoming.socket->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000279
Yves Gerey665174f2018-06-19 15:03:05 +0200280 RTC_LOG(LS_VERBOSE) << ToString() << ": Accepted connection from "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200281 << incoming.addr.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000282 incoming_.push_back(incoming);
283}
284
deadbeef1ee21252017-06-13 15:49:45 -0700285void TCPPort::TryCreateServerSocket() {
286 socket_ = socket_factory()->CreateServerTcpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -0700287 rtc::SocketAddress(Network()->GetBestIP(), 0), min_port(), max_port(),
288 false /* ssl */);
deadbeef1ee21252017-06-13 15:49:45 -0700289 if (!socket_) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200290 RTC_LOG(LS_WARNING)
291 << ToString()
292 << ": TCP server socket creation failed; continuing anyway.";
deadbeef1ee21252017-06-13 15:49:45 -0700293 return;
294 }
295 socket_->SignalNewConnection.connect(this, &TCPPort::OnNewConnection);
296 socket_->SignalAddressReady.connect(this, &TCPPort::OnAddressReady);
297}
298
Yves Gerey665174f2018-06-19 15:03:05 +0200299rtc::AsyncPacketSocket* TCPPort::GetIncoming(const rtc::SocketAddress& addr,
300 bool remove) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000301 rtc::AsyncPacketSocket* socket = NULL;
302 for (std::list<Incoming>::iterator it = incoming_.begin();
303 it != incoming_.end(); ++it) {
304 if (it->addr == addr) {
305 socket = it->socket;
306 if (remove)
307 incoming_.erase(it);
308 break;
309 }
310 }
311 return socket;
312}
313
314void TCPPort::OnReadPacket(rtc::AsyncPacketSocket* socket,
Yves Gerey665174f2018-06-19 15:03:05 +0200315 const char* data,
316 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000317 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +0100318 const int64_t& packet_time_us) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000319 Port::OnReadPacket(data, size, remote_addr, PROTO_TCP);
320}
321
Stefan Holmer55674ff2016-01-14 15:49:16 +0100322void TCPPort::OnSentPacket(rtc::AsyncPacketSocket* socket,
323 const rtc::SentPacket& sent_packet) {
Stefan Holmer55674ff2016-01-14 15:49:16 +0100324 PortInterface::SignalSentPacket(sent_packet);
325}
326
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000327void TCPPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
328 Port::OnReadyToSend();
329}
330
331void TCPPort::OnAddressReady(rtc::AsyncPacketSocket* socket,
332 const rtc::SocketAddress& address) {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700333 AddAddress(address, address, rtc::SocketAddress(), TCP_PROTOCOL_NAME, "",
334 TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP,
zhihuang26d99c22017-02-13 12:47:27 -0800335 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000336}
337
Qingsi Wang22e623a2018-03-13 10:53:57 -0700338// TODO(qingsi): |CONNECTION_WRITE_CONNECT_TIMEOUT| is overriden by
339// |ice_unwritable_timeout| in IceConfig when determining the writability state.
340// Replace this constant with the config parameter assuming the default value if
341// we decide it is also applicable here.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700342TCPConnection::TCPConnection(TCPPort* port,
343 const Candidate& candidate,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000344 rtc::AsyncPacketSocket* socket)
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700345 : Connection(port, 0, candidate),
346 socket_(socket),
347 error_(0),
348 outgoing_(socket == NULL),
349 connection_pending_(false),
350 pretending_to_be_writable_(false),
351 reconnection_timeout_(cricket::CONNECTION_WRITE_CONNECT_TIMEOUT) {
352 if (outgoing_) {
353 CreateOutgoingTcpSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000354 } else {
deadbeef5c3c1042017-08-04 15:01:57 -0700355 // Incoming connections should match one of the network addresses. Same as
356 // what's being checked in OnConnect, but just DCHECKing here.
Jonas Olssond7d762d2018-03-28 09:47:51 +0200357 RTC_LOG(LS_VERBOSE) << ToString() << ": socket ipaddr: "
358 << socket_->GetLocalAddress().ToString()
359 << ", port() Network:" << port->Network()->ToString();
deadbeef5c3c1042017-08-04 15:01:57 -0700360 const std::vector<rtc::InterfaceAddress>& desired_addresses =
361 port_->Network()->GetIPs();
Taylor Brandstetter01cb5f22018-03-07 15:49:32 -0800362 RTC_DCHECK(std::find_if(desired_addresses.begin(), desired_addresses.end(),
363 [this](const rtc::InterfaceAddress& addr) {
364 return socket_->GetLocalAddress().ipaddr() ==
365 addr;
366 }) != desired_addresses.end());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700367 ConnectSocketSignals(socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000368 }
369}
370
Yves Gerey665174f2018-06-19 15:03:05 +0200371TCPConnection::~TCPConnection() {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000372
Yves Gerey665174f2018-06-19 15:03:05 +0200373int TCPConnection::Send(const void* data,
374 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000375 const rtc::PacketOptions& options) {
376 if (!socket_) {
377 error_ = ENOTCONN;
378 return SOCKET_ERROR;
379 }
380
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700381 // Sending after OnClose on active side will trigger a reconnect for a
382 // outgoing connection. Note that the write state is still WRITABLE as we want
383 // to spend a few seconds attempting a reconnect before saying we're
384 // unwritable.
385 if (!connected()) {
386 MaybeReconnect();
387 return SOCKET_ERROR;
388 }
389
390 // Note that this is important to put this after the previous check to give
391 // the connection a chance to reconnect.
392 if (pretending_to_be_writable_ || write_state() != STATE_WRITABLE) {
Steve Anton6c38cc72017-11-29 10:25:58 -0800393 // TODO(?): Should STATE_WRITE_TIMEOUT return a non-blocking error?
skvladc309e0e2016-07-28 17:15:20 -0700394 error_ = ENOTCONN;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000395 return SOCKET_ERROR;
396 }
zhihuang5ecf16c2016-06-01 17:09:15 -0700397 stats_.sent_total_packets++;
Qingsi Wang6e641e62018-04-11 20:14:17 -0700398 rtc::PacketOptions modified_options(options);
399 static_cast<TCPPort*>(port_)->CopyPortInformationToPacketInfo(
400 &modified_options.info_signaled_after_sent);
401 int sent = socket_->Send(data, size, modified_options);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000402 if (sent < 0) {
zhihuang5ecf16c2016-06-01 17:09:15 -0700403 stats_.sent_discarded_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000404 error_ = socket_->GetError();
405 } else {
Tim Psiaki63046262015-09-14 10:38:08 -0700406 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000407 }
408 return sent;
409}
410
411int TCPConnection::GetError() {
412 return error_;
413}
414
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700415void TCPConnection::OnConnectionRequestResponse(ConnectionRequest* req,
416 StunMessage* response) {
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700417 // Process the STUN response before we inform upper layer ready to send.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700418 Connection::OnConnectionRequestResponse(req, response);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700419
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 05:15:36 -0800427 RTC_DCHECK(write_state() == STATE_WRITABLE);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700428}
429
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000430void TCPConnection::OnConnect(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800431 RTC_DCHECK(socket == socket_.get());
deadbeef5c3c1042017-08-04 15:01:57 -0700432 // 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();
447 const std::vector<rtc::InterfaceAddress>& desired_addresses =
448 port_->Network()->GetIPs();
Taylor Brandstetter01cb5f22018-03-07 15:49:32 -0800449 if (std::find_if(desired_addresses.begin(), desired_addresses.end(),
450 [socket_address](const rtc::InterfaceAddress& addr) {
451 return socket_address.ipaddr() == addr;
452 }) != desired_addresses.end()) {
Yves Gerey665174f2018-06-19 15:03:05 +0200453 RTC_LOG(LS_VERBOSE) << ToString() << ": Connection established to "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200454 << socket->GetRemoteAddress().ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000455 } else {
deadbeef5c3c1042017-08-04 15:01:57 -0700456 if (socket->GetLocalAddress().IsLoopbackIP()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100457 RTC_LOG(LS_WARNING) << "Socket is bound to the address:"
458 << socket_address.ipaddr().ToString()
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 localhost.";
deadbeef5c3c1042017-08-04 15:01:57 -0700462 } else if (IPIsAny(port_->Network()->GetBestIP())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100463 RTC_LOG(LS_WARNING)
464 << "Socket is bound to the address:"
465 << socket_address.ipaddr().ToString()
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()
468 << ". Still allowing it since it's the 'any' address"
Jonas Olssond7d762d2018-03-28 09:47:51 +0200469 ", possibly caused by multiple_routes being disabled.";
deadbeef5c3c1042017-08-04 15:01:57 -0700470 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100471 RTC_LOG(LS_WARNING) << "Dropping connection as TCP socket bound to IP "
472 << socket_address.ipaddr().ToString()
Taylor Brandstetter3ba7a572018-03-02 10:58:25 -0800473 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100474 << port_->Network()->ToString();
deadbeef5c3c1042017-08-04 15:01:57 -0700475 OnClose(socket, 0);
476 return;
477 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000478 }
tommi5ce1a2a2016-05-14 03:19:31 -0700479
480 // Connection is established successfully.
481 set_connected(true);
482 connection_pending_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000483}
484
485void TCPConnection::OnClose(rtc::AsyncPacketSocket* socket, int error) {
nisseede5da42017-01-12 05:15:36 -0800486 RTC_DCHECK(socket == socket_.get());
Yves Gerey665174f2018-06-19 15:03:05 +0200487 RTC_LOG(LS_INFO) << ToString() << ": Connection closed with error " << error;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700488
489 // Guard against the condition where IPC socket will call OnClose for every
490 // packet it can't send.
491 if (connected()) {
492 set_connected(false);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700493
494 // Prevent the connection from being destroyed by redundant SignalClose
495 // events.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700496 pretending_to_be_writable_ = true;
497
498 // We don't attempt reconnect right here. This is to avoid a case where the
499 // shutdown is intentional and reconnect is not necessary. We only reconnect
500 // when the connection is used to Send() or Ping().
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700501 port()->thread()->PostDelayed(RTC_FROM_HERE, reconnection_timeout(), this,
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700502 MSG_TCPCONNECTION_DELAYED_ONCLOSE);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700503 } else if (!pretending_to_be_writable_) {
504 // OnClose could be called when the underneath socket times out during the
505 // initial connect() (i.e. |pretending_to_be_writable_| is false) . We have
506 // to manually destroy here as this connection, as never connected, will not
507 // be scheduled for ping to trigger destroy.
508 Destroy();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700509 }
510}
511
512void TCPConnection::OnMessage(rtc::Message* pmsg) {
513 switch (pmsg->message_id) {
514 case MSG_TCPCONNECTION_DELAYED_ONCLOSE:
515 // If this connection can't become connected and writable again in 5
516 // seconds, it's time to tear this down. This is the case for the original
517 // TCP connection on passive side during a reconnect.
518 if (pretending_to_be_writable_) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700519 Destroy();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700520 }
521 break;
522 default:
523 Connection::OnMessage(pmsg);
524 }
525}
526
527void TCPConnection::MaybeReconnect() {
528 // Only reconnect for an outgoing TCPConnection when OnClose was signaled and
529 // no outstanding reconnect is pending.
530 if (connected() || connection_pending_ || !outgoing_) {
531 return;
532 }
533
Jonas Olssond7d762d2018-03-28 09:47:51 +0200534 RTC_LOG(LS_INFO) << ToString()
535 << ": TCP Connection with remote is closed, "
536 "trying to reconnect";
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700537
538 CreateOutgoingTcpSocket();
539 error_ = EPIPE;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000540}
541
Yves Gerey665174f2018-06-19 15:03:05 +0200542void TCPConnection::OnReadPacket(rtc::AsyncPacketSocket* socket,
543 const char* data,
544 size_t size,
545 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +0100546 const int64_t& packet_time_us) {
nisseede5da42017-01-12 05:15:36 -0800547 RTC_DCHECK(socket == socket_.get());
Niels Möllere6933812018-11-05 13:01:41 +0100548 Connection::OnReadPacket(data, size, packet_time_us);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000549}
550
551void TCPConnection::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800552 RTC_DCHECK(socket == socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000553 Connection::OnReadyToSend();
554}
555
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700556void TCPConnection::CreateOutgoingTcpSocket() {
nisseede5da42017-01-12 05:15:36 -0800557 RTC_DCHECK(outgoing_);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700558 // TODO(guoweis): Handle failures here (unlikely since TCP).
559 int opts = (remote_candidate().protocol() == SSLTCP_PROTOCOL_NAME)
hnsl04833622017-01-09 08:35:45 -0800560 ? rtc::PacketSocketFactory::OPT_TLS_FAKE
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700561 : 0;
562 socket_.reset(port()->socket_factory()->CreateClientTcpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -0700563 rtc::SocketAddress(port()->Network()->GetBestIP(), 0),
564 remote_candidate().address(), port()->proxy(), port()->user_agent(),
565 opts));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700566 if (socket_) {
Yves Gerey665174f2018-06-19 15:03:05 +0200567 RTC_LOG(LS_VERBOSE) << ToString() << ": Connecting from "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200568 << socket_->GetLocalAddress().ToSensitiveString()
569 << " to "
570 << remote_candidate().address().ToSensitiveString();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700571 set_connected(false);
572 connection_pending_ = true;
573 ConnectSocketSignals(socket_.get());
574 } else {
Yves Gerey665174f2018-06-19 15:03:05 +0200575 RTC_LOG(LS_WARNING) << ToString() << ": Failed to create connection to "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200576 << remote_candidate().address().ToSensitiveString();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700577 }
578}
579
580void TCPConnection::ConnectSocketSignals(rtc::AsyncPacketSocket* socket) {
581 if (outgoing_) {
582 socket->SignalConnect.connect(this, &TCPConnection::OnConnect);
583 }
584 socket->SignalReadPacket.connect(this, &TCPConnection::OnReadPacket);
585 socket->SignalReadyToSend.connect(this, &TCPConnection::OnReadyToSend);
586 socket->SignalClose.connect(this, &TCPConnection::OnClose);
587}
588
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000589} // namespace cricket