blob: 70179528065befa7cded756af09f6cd05b31ba86 [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020067#include "p2p/base/tcpport.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000068
Steve Anton6c38cc72017-11-29 10:25:58 -080069#include <vector>
70
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020071#include "rtc_base/checks.h"
72#include "rtc_base/logging.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000073
74namespace cricket {
75
76TCPPort::TCPPort(rtc::Thread* thread,
77 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +000078 rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +020079 uint16_t min_port,
80 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +000081 const std::string& username,
82 const std::string& password,
83 bool allow_listen)
Peter Boström0c4e06b2015-10-07 12:23:21 +020084 : Port(thread,
85 LOCAL_PORT_TYPE,
86 factory,
87 network,
Peter Boström0c4e06b2015-10-07 12:23:21 +020088 min_port,
89 max_port,
90 username,
91 password),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000092 incoming_only_(false),
93 allow_listen_(allow_listen),
94 socket_(NULL),
95 error_(0) {
96 // TODO(mallinath) - Set preference value as per RFC 6544.
97 // http://b/issue?id=7141794
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000098 if (allow_listen_) {
deadbeef1ee21252017-06-13 15:49:45 -070099 TryCreateServerSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000100 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000101}
102
103TCPPort::~TCPPort() {
104 delete socket_;
105 std::list<Incoming>::iterator it;
106 for (it = incoming_.begin(); it != incoming_.end(); ++it)
107 delete it->socket;
108 incoming_.clear();
109}
110
111Connection* TCPPort::CreateConnection(const Candidate& address,
112 CandidateOrigin origin) {
Honghai Zhangf9945b22015-12-15 12:20:13 -0800113 if (!SupportsProtocol(address.protocol())) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000114 return NULL;
115 }
116
117 if (address.tcptype() == TCPTYPE_ACTIVE_STR ||
118 (address.tcptype().empty() && address.address().port() == 0)) {
119 // It's active only candidate, we should not try to create connections
120 // for these candidates.
121 return NULL;
122 }
123
124 // We can't accept TCP connections incoming on other ports
125 if (origin == ORIGIN_OTHER_PORT)
126 return NULL;
127
128 // Check if we are allowed to make outgoing TCP connections
129 if (incoming_only_ && (origin == ORIGIN_MESSAGE))
130 return NULL;
131
132 // We don't know how to act as an ssl server yet
133 if ((address.protocol() == SSLTCP_PROTOCOL_NAME) &&
134 (origin == ORIGIN_THIS_PORT)) {
135 return NULL;
136 }
137
138 if (!IsCompatibleAddress(address.address())) {
139 return NULL;
140 }
141
142 TCPConnection* conn = NULL;
143 if (rtc::AsyncPacketSocket* socket =
144 GetIncoming(address.address(), true)) {
deadbeef06878292017-04-21 14:22:23 -0700145 // Incoming connection; we already created a socket and connected signals,
146 // so we need to hand off the "read packet" responsibility to
147 // TCPConnection.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000148 socket->SignalReadPacket.disconnect(this);
149 conn = new TCPConnection(this, address, socket);
150 } else {
deadbeef06878292017-04-21 14:22:23 -0700151 // Outgoing connection, which will create a new socket for which we still
152 // need to connect SignalReadyToSend and SignalSentPacket.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000153 conn = new TCPConnection(this, address);
deadbeef06878292017-04-21 14:22:23 -0700154 if (conn->socket()) {
155 conn->socket()->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
156 conn->socket()->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
157 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000158 }
honghaiz36f50e82016-06-01 15:57:03 -0700159 AddOrReplaceConnection(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000160 return conn;
161}
162
163void TCPPort::PrepareAddress() {
164 if (socket_) {
165 // If socket isn't bound yet the address will be added in
166 // OnAddressReady(). Socket may be in the CLOSED state if Listen()
167 // failed, we still want to add the socket address.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100168 RTC_LOG(LS_VERBOSE) << "Preparing TCP address, current state: "
169 << socket_->GetState();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000170 if (socket_->GetState() == rtc::AsyncPacketSocket::STATE_BOUND ||
171 socket_->GetState() == rtc::AsyncPacketSocket::STATE_CLOSED)
172 AddAddress(socket_->GetLocalAddress(), socket_->GetLocalAddress(),
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700173 rtc::SocketAddress(), TCP_PROTOCOL_NAME, "",
174 TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE,
zhihuang26d99c22017-02-13 12:47:27 -0800175 ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000176 } else {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200177 RTC_LOG(LS_INFO) << ToString()
178 << ": Not listening due to firewall restrictions.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000179 // Note: We still add the address, since otherwise the remote side won't
Guo-wei Shieh310b0932015-11-17 19:15:50 -0800180 // recognize our incoming TCP connections. According to
181 // https://tools.ietf.org/html/rfc6544#section-4.5, for active candidate,
deadbeef5c3c1042017-08-04 15:01:57 -0700182 // the port must be set to the discard port, i.e. 9. We can't be 100% sure
183 // which IP address will actually be used, so GetBestIP is as good as we
184 // can do.
185 // TODO(deadbeef): We could do something like create a dummy socket just to
186 // see what IP we get. But that may be overkill.
187 AddAddress(rtc::SocketAddress(Network()->GetBestIP(), DISCARD_PORT),
188 rtc::SocketAddress(Network()->GetBestIP(), 0),
189 rtc::SocketAddress(), TCP_PROTOCOL_NAME, "", TCPTYPE_ACTIVE_STR,
190 LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000191 }
192}
193
194int TCPPort::SendTo(const void* data, size_t size,
195 const rtc::SocketAddress& addr,
196 const rtc::PacketOptions& options,
197 bool payload) {
198 rtc::AsyncPacketSocket * socket = NULL;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700199 TCPConnection* conn = static_cast<TCPConnection*>(GetConnection(addr));
200
201 // For Connection, this is the code path used by Ping() to establish
202 // WRITABLE. It has to send through the socket directly as TCPConnection::Send
203 // checks writability.
204 if (conn) {
205 if (!conn->connected()) {
206 conn->MaybeReconnect();
207 return SOCKET_ERROR;
208 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000209 socket = conn->socket();
210 } else {
211 socket = GetIncoming(addr);
212 }
213 if (!socket) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200214 RTC_LOG(LS_ERROR) << ToString()
215 << ": Attempted to send to an unknown destination: "
216 << addr.ToSensitiveString();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700217 return SOCKET_ERROR; // TODO(tbd): Set error_
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000218 }
Qingsi Wang6e641e62018-04-11 20:14:17 -0700219 rtc::PacketOptions modified_options(options);
220 CopyPortInformationToPacketInfo(&modified_options.info_signaled_after_sent);
221 int sent = socket->Send(data, size, modified_options);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000222 if (sent < 0) {
223 error_ = socket->GetError();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700224 // Error from this code path for a Connection (instead of from a bare
225 // socket) will not trigger reconnecting. In theory, this shouldn't matter
226 // as OnClose should always be called and set connected to false.
Jonas Olssond7d762d2018-03-28 09:47:51 +0200227 RTC_LOG(LS_ERROR) << ToString() << ": TCP send of "
228 << size << " bytes failed with error " << error_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000229 }
230 return sent;
231}
232
233int TCPPort::GetOption(rtc::Socket::Option opt, int* value) {
234 if (socket_) {
235 return socket_->GetOption(opt, value);
236 } else {
237 return SOCKET_ERROR;
238 }
239}
240
241int TCPPort::SetOption(rtc::Socket::Option opt, int value) {
242 if (socket_) {
243 return socket_->SetOption(opt, value);
244 } else {
245 return SOCKET_ERROR;
246 }
247}
248
249int TCPPort::GetError() {
250 return error_;
251}
252
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700253bool TCPPort::SupportsProtocol(const std::string& protocol) const {
254 return protocol == TCP_PROTOCOL_NAME || protocol == SSLTCP_PROTOCOL_NAME;
255}
256
257ProtocolType TCPPort::GetProtocol() const {
258 return PROTO_TCP;
259}
260
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000261void TCPPort::OnNewConnection(rtc::AsyncPacketSocket* socket,
262 rtc::AsyncPacketSocket* new_socket) {
nisseede5da42017-01-12 05:15:36 -0800263 RTC_DCHECK(socket == socket_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000264
265 Incoming incoming;
266 incoming.addr = new_socket->GetRemoteAddress();
267 incoming.socket = new_socket;
268 incoming.socket->SignalReadPacket.connect(this, &TCPPort::OnReadPacket);
269 incoming.socket->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
Stefan Holmer55674ff2016-01-14 15:49:16 +0100270 incoming.socket->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000271
Jonas Olssond7d762d2018-03-28 09:47:51 +0200272 RTC_LOG(LS_VERBOSE) << ToString()
273 << ": Accepted connection from "
274 << incoming.addr.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000275 incoming_.push_back(incoming);
276}
277
deadbeef1ee21252017-06-13 15:49:45 -0700278void TCPPort::TryCreateServerSocket() {
279 socket_ = socket_factory()->CreateServerTcpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -0700280 rtc::SocketAddress(Network()->GetBestIP(), 0), min_port(), max_port(),
281 false /* ssl */);
deadbeef1ee21252017-06-13 15:49:45 -0700282 if (!socket_) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200283 RTC_LOG(LS_WARNING)
284 << ToString()
285 << ": TCP server socket creation failed; continuing anyway.";
deadbeef1ee21252017-06-13 15:49:45 -0700286 return;
287 }
288 socket_->SignalNewConnection.connect(this, &TCPPort::OnNewConnection);
289 socket_->SignalAddressReady.connect(this, &TCPPort::OnAddressReady);
290}
291
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000292rtc::AsyncPacketSocket* TCPPort::GetIncoming(
293 const rtc::SocketAddress& addr, bool remove) {
294 rtc::AsyncPacketSocket* socket = NULL;
295 for (std::list<Incoming>::iterator it = incoming_.begin();
296 it != incoming_.end(); ++it) {
297 if (it->addr == addr) {
298 socket = it->socket;
299 if (remove)
300 incoming_.erase(it);
301 break;
302 }
303 }
304 return socket;
305}
306
307void TCPPort::OnReadPacket(rtc::AsyncPacketSocket* socket,
308 const char* data, size_t size,
309 const rtc::SocketAddress& remote_addr,
310 const rtc::PacketTime& packet_time) {
311 Port::OnReadPacket(data, size, remote_addr, PROTO_TCP);
312}
313
Stefan Holmer55674ff2016-01-14 15:49:16 +0100314void TCPPort::OnSentPacket(rtc::AsyncPacketSocket* socket,
315 const rtc::SentPacket& sent_packet) {
Stefan Holmer55674ff2016-01-14 15:49:16 +0100316 PortInterface::SignalSentPacket(sent_packet);
317}
318
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000319void TCPPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
320 Port::OnReadyToSend();
321}
322
323void TCPPort::OnAddressReady(rtc::AsyncPacketSocket* socket,
324 const rtc::SocketAddress& address) {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700325 AddAddress(address, address, rtc::SocketAddress(), TCP_PROTOCOL_NAME, "",
326 TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP,
zhihuang26d99c22017-02-13 12:47:27 -0800327 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000328}
329
Qingsi Wang22e623a2018-03-13 10:53:57 -0700330// TODO(qingsi): |CONNECTION_WRITE_CONNECT_TIMEOUT| is overriden by
331// |ice_unwritable_timeout| in IceConfig when determining the writability state.
332// Replace this constant with the config parameter assuming the default value if
333// we decide it is also applicable here.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700334TCPConnection::TCPConnection(TCPPort* port,
335 const Candidate& candidate,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000336 rtc::AsyncPacketSocket* socket)
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700337 : Connection(port, 0, candidate),
338 socket_(socket),
339 error_(0),
340 outgoing_(socket == NULL),
341 connection_pending_(false),
342 pretending_to_be_writable_(false),
343 reconnection_timeout_(cricket::CONNECTION_WRITE_CONNECT_TIMEOUT) {
344 if (outgoing_) {
345 CreateOutgoingTcpSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000346 } else {
deadbeef5c3c1042017-08-04 15:01:57 -0700347 // Incoming connections should match one of the network addresses. Same as
348 // what's being checked in OnConnect, but just DCHECKing here.
Jonas Olssond7d762d2018-03-28 09:47:51 +0200349 RTC_LOG(LS_VERBOSE) << ToString() << ": socket ipaddr: "
350 << socket_->GetLocalAddress().ToString()
351 << ", port() Network:" << port->Network()->ToString();
deadbeef5c3c1042017-08-04 15:01:57 -0700352 const std::vector<rtc::InterfaceAddress>& desired_addresses =
353 port_->Network()->GetIPs();
Taylor Brandstetter01cb5f22018-03-07 15:49:32 -0800354 RTC_DCHECK(std::find_if(desired_addresses.begin(), desired_addresses.end(),
355 [this](const rtc::InterfaceAddress& addr) {
356 return socket_->GetLocalAddress().ipaddr() ==
357 addr;
358 }) != desired_addresses.end());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700359 ConnectSocketSignals(socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000360 }
361}
362
363TCPConnection::~TCPConnection() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000364}
365
366int TCPConnection::Send(const void* data, size_t size,
367 const rtc::PacketOptions& options) {
368 if (!socket_) {
369 error_ = ENOTCONN;
370 return SOCKET_ERROR;
371 }
372
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700373 // Sending after OnClose on active side will trigger a reconnect for a
374 // outgoing connection. Note that the write state is still WRITABLE as we want
375 // to spend a few seconds attempting a reconnect before saying we're
376 // unwritable.
377 if (!connected()) {
378 MaybeReconnect();
379 return SOCKET_ERROR;
380 }
381
382 // Note that this is important to put this after the previous check to give
383 // the connection a chance to reconnect.
384 if (pretending_to_be_writable_ || write_state() != STATE_WRITABLE) {
Steve Anton6c38cc72017-11-29 10:25:58 -0800385 // TODO(?): Should STATE_WRITE_TIMEOUT return a non-blocking error?
skvladc309e0e2016-07-28 17:15:20 -0700386 error_ = ENOTCONN;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000387 return SOCKET_ERROR;
388 }
zhihuang5ecf16c2016-06-01 17:09:15 -0700389 stats_.sent_total_packets++;
Qingsi Wang6e641e62018-04-11 20:14:17 -0700390 rtc::PacketOptions modified_options(options);
391 static_cast<TCPPort*>(port_)->CopyPortInformationToPacketInfo(
392 &modified_options.info_signaled_after_sent);
393 int sent = socket_->Send(data, size, modified_options);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000394 if (sent < 0) {
zhihuang5ecf16c2016-06-01 17:09:15 -0700395 stats_.sent_discarded_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000396 error_ = socket_->GetError();
397 } else {
Tim Psiaki63046262015-09-14 10:38:08 -0700398 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000399 }
400 return sent;
401}
402
403int TCPConnection::GetError() {
404 return error_;
405}
406
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700407void TCPConnection::OnConnectionRequestResponse(ConnectionRequest* req,
408 StunMessage* response) {
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700409 // Process the STUN response before we inform upper layer ready to send.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700410 Connection::OnConnectionRequestResponse(req, response);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700411
412 // If we're in the state of pretending to be writeable, we should inform the
413 // upper layer it's ready to send again as previous EWOULDLBLOCK from socket
414 // would have stopped the outgoing stream.
415 if (pretending_to_be_writable_) {
416 Connection::OnReadyToSend();
417 }
418 pretending_to_be_writable_ = false;
nisseede5da42017-01-12 05:15:36 -0800419 RTC_DCHECK(write_state() == STATE_WRITABLE);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700420}
421
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000422void TCPConnection::OnConnect(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800423 RTC_DCHECK(socket == socket_.get());
deadbeef5c3c1042017-08-04 15:01:57 -0700424 // Do not use this port if the socket bound to an address not associated with
425 // the desired network interface. This is seen in Chrome, where TCP sockets
426 // cannot be given a binding address, and the platform is expected to pick
427 // the correct local address.
428 //
429 // However, there are two situations in which we allow the bound address to
430 // not be one of the addresses of the requested interface:
431 // 1. The bound address is the loopback address. This happens when a proxy
432 // forces TCP to bind to only the localhost address (see issue 3927).
433 // 2. The bound address is the "any address". This happens when
434 // multiple_routes is disabled (see issue 4780).
435 //
436 // Note that, aside from minor differences in log statements, this logic is
437 // identical to that in TurnPort.
438 const rtc::SocketAddress& socket_address = socket->GetLocalAddress();
439 const std::vector<rtc::InterfaceAddress>& desired_addresses =
440 port_->Network()->GetIPs();
Taylor Brandstetter01cb5f22018-03-07 15:49:32 -0800441 if (std::find_if(desired_addresses.begin(), desired_addresses.end(),
442 [socket_address](const rtc::InterfaceAddress& addr) {
443 return socket_address.ipaddr() == addr;
444 }) != desired_addresses.end()) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200445 RTC_LOG(LS_VERBOSE) << ToString()
446 << ": Connection established to "
447 << 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:"
451 << socket_address.ipaddr().ToString()
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:"
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 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 "
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();
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());
Jonas Olssond7d762d2018-03-28 09:47:51 +0200480 RTC_LOG(LS_INFO) << ToString()
481 << ": Connection closed with error " << error;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700482
483 // Guard against the condition where IPC socket will call OnClose for every
484 // packet it can't send.
485 if (connected()) {
486 set_connected(false);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700487
488 // Prevent the connection from being destroyed by redundant SignalClose
489 // events.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700490 pretending_to_be_writable_ = true;
491
492 // We don't attempt reconnect right here. This is to avoid a case where the
493 // shutdown is intentional and reconnect is not necessary. We only reconnect
494 // when the connection is used to Send() or Ping().
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700495 port()->thread()->PostDelayed(RTC_FROM_HERE, reconnection_timeout(), this,
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700496 MSG_TCPCONNECTION_DELAYED_ONCLOSE);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700497 } else if (!pretending_to_be_writable_) {
498 // OnClose could be called when the underneath socket times out during the
499 // initial connect() (i.e. |pretending_to_be_writable_| is false) . We have
500 // to manually destroy here as this connection, as never connected, will not
501 // be scheduled for ping to trigger destroy.
502 Destroy();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700503 }
504}
505
506void TCPConnection::OnMessage(rtc::Message* pmsg) {
507 switch (pmsg->message_id) {
508 case MSG_TCPCONNECTION_DELAYED_ONCLOSE:
509 // If this connection can't become connected and writable again in 5
510 // seconds, it's time to tear this down. This is the case for the original
511 // TCP connection on passive side during a reconnect.
512 if (pretending_to_be_writable_) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700513 Destroy();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700514 }
515 break;
516 default:
517 Connection::OnMessage(pmsg);
518 }
519}
520
521void TCPConnection::MaybeReconnect() {
522 // Only reconnect for an outgoing TCPConnection when OnClose was signaled and
523 // no outstanding reconnect is pending.
524 if (connected() || connection_pending_ || !outgoing_) {
525 return;
526 }
527
Jonas Olssond7d762d2018-03-28 09:47:51 +0200528 RTC_LOG(LS_INFO) << ToString()
529 << ": TCP Connection with remote is closed, "
530 "trying to reconnect";
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700531
532 CreateOutgoingTcpSocket();
533 error_ = EPIPE;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000534}
535
536void TCPConnection::OnReadPacket(
537 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
538 const rtc::SocketAddress& remote_addr,
539 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -0800540 RTC_DCHECK(socket == socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000541 Connection::OnReadPacket(data, size, packet_time);
542}
543
544void TCPConnection::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800545 RTC_DCHECK(socket == socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000546 Connection::OnReadyToSend();
547}
548
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700549void TCPConnection::CreateOutgoingTcpSocket() {
nisseede5da42017-01-12 05:15:36 -0800550 RTC_DCHECK(outgoing_);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700551 // TODO(guoweis): Handle failures here (unlikely since TCP).
552 int opts = (remote_candidate().protocol() == SSLTCP_PROTOCOL_NAME)
hnsl04833622017-01-09 08:35:45 -0800553 ? rtc::PacketSocketFactory::OPT_TLS_FAKE
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700554 : 0;
555 socket_.reset(port()->socket_factory()->CreateClientTcpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -0700556 rtc::SocketAddress(port()->Network()->GetBestIP(), 0),
557 remote_candidate().address(), port()->proxy(), port()->user_agent(),
558 opts));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700559 if (socket_) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200560 RTC_LOG(LS_VERBOSE) << ToString()
561 << ": Connecting from "
562 << socket_->GetLocalAddress().ToSensitiveString()
563 << " to "
564 << remote_candidate().address().ToSensitiveString();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700565 set_connected(false);
566 connection_pending_ = true;
567 ConnectSocketSignals(socket_.get());
568 } else {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200569 RTC_LOG(LS_WARNING) << ToString()
570 << ": Failed to create connection to "
571 << remote_candidate().address().ToSensitiveString();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700572 }
573}
574
575void TCPConnection::ConnectSocketSignals(rtc::AsyncPacketSocket* socket) {
576 if (outgoing_) {
577 socket->SignalConnect.connect(this, &TCPConnection::OnConnect);
578 }
579 socket->SignalReadPacket.connect(this, &TCPConnection::OnReadPacket);
580 socket->SignalReadyToSend.connect(this, &TCPConnection::OnReadyToSend);
581 socket->SignalClose.connect(this, &TCPConnection::OnClose);
582}
583
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000584} // namespace cricket