blob: 45acfc7eccc76c8aa233932b75de74dc0ce13c8d [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 }
219
220 int sent = socket->Send(data, size, options);
221 if (sent < 0) {
222 error_ = socket->GetError();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700223 // Error from this code path for a Connection (instead of from a bare
224 // socket) will not trigger reconnecting. In theory, this shouldn't matter
225 // as OnClose should always be called and set connected to false.
Jonas Olssond7d762d2018-03-28 09:47:51 +0200226 RTC_LOG(LS_ERROR) << ToString() << ": TCP send of "
227 << size << " bytes failed with error " << error_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000228 }
229 return sent;
230}
231
232int TCPPort::GetOption(rtc::Socket::Option opt, int* value) {
233 if (socket_) {
234 return socket_->GetOption(opt, value);
235 } else {
236 return SOCKET_ERROR;
237 }
238}
239
240int TCPPort::SetOption(rtc::Socket::Option opt, int value) {
241 if (socket_) {
242 return socket_->SetOption(opt, value);
243 } else {
244 return SOCKET_ERROR;
245 }
246}
247
248int TCPPort::GetError() {
249 return error_;
250}
251
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700252bool TCPPort::SupportsProtocol(const std::string& protocol) const {
253 return protocol == TCP_PROTOCOL_NAME || protocol == SSLTCP_PROTOCOL_NAME;
254}
255
256ProtocolType TCPPort::GetProtocol() const {
257 return PROTO_TCP;
258}
259
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000260void TCPPort::OnNewConnection(rtc::AsyncPacketSocket* socket,
261 rtc::AsyncPacketSocket* new_socket) {
nisseede5da42017-01-12 05:15:36 -0800262 RTC_DCHECK(socket == socket_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000263
264 Incoming incoming;
265 incoming.addr = new_socket->GetRemoteAddress();
266 incoming.socket = new_socket;
267 incoming.socket->SignalReadPacket.connect(this, &TCPPort::OnReadPacket);
268 incoming.socket->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
Stefan Holmer55674ff2016-01-14 15:49:16 +0100269 incoming.socket->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000270
Jonas Olssond7d762d2018-03-28 09:47:51 +0200271 RTC_LOG(LS_VERBOSE) << ToString()
272 << ": Accepted connection from "
273 << incoming.addr.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000274 incoming_.push_back(incoming);
275}
276
deadbeef1ee21252017-06-13 15:49:45 -0700277void TCPPort::TryCreateServerSocket() {
278 socket_ = socket_factory()->CreateServerTcpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -0700279 rtc::SocketAddress(Network()->GetBestIP(), 0), min_port(), max_port(),
280 false /* ssl */);
deadbeef1ee21252017-06-13 15:49:45 -0700281 if (!socket_) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200282 RTC_LOG(LS_WARNING)
283 << ToString()
284 << ": TCP server socket creation failed; continuing anyway.";
deadbeef1ee21252017-06-13 15:49:45 -0700285 return;
286 }
287 socket_->SignalNewConnection.connect(this, &TCPPort::OnNewConnection);
288 socket_->SignalAddressReady.connect(this, &TCPPort::OnAddressReady);
289}
290
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000291rtc::AsyncPacketSocket* TCPPort::GetIncoming(
292 const rtc::SocketAddress& addr, bool remove) {
293 rtc::AsyncPacketSocket* socket = NULL;
294 for (std::list<Incoming>::iterator it = incoming_.begin();
295 it != incoming_.end(); ++it) {
296 if (it->addr == addr) {
297 socket = it->socket;
298 if (remove)
299 incoming_.erase(it);
300 break;
301 }
302 }
303 return socket;
304}
305
306void TCPPort::OnReadPacket(rtc::AsyncPacketSocket* socket,
307 const char* data, size_t size,
308 const rtc::SocketAddress& remote_addr,
309 const rtc::PacketTime& packet_time) {
310 Port::OnReadPacket(data, size, remote_addr, PROTO_TCP);
311}
312
Stefan Holmer55674ff2016-01-14 15:49:16 +0100313void TCPPort::OnSentPacket(rtc::AsyncPacketSocket* socket,
314 const rtc::SentPacket& sent_packet) {
Stefan Holmer55674ff2016-01-14 15:49:16 +0100315 PortInterface::SignalSentPacket(sent_packet);
316}
317
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000318void TCPPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
319 Port::OnReadyToSend();
320}
321
322void TCPPort::OnAddressReady(rtc::AsyncPacketSocket* socket,
323 const rtc::SocketAddress& address) {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700324 AddAddress(address, address, rtc::SocketAddress(), TCP_PROTOCOL_NAME, "",
325 TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP,
zhihuang26d99c22017-02-13 12:47:27 -0800326 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000327}
328
Qingsi Wang22e623a2018-03-13 10:53:57 -0700329// TODO(qingsi): |CONNECTION_WRITE_CONNECT_TIMEOUT| is overriden by
330// |ice_unwritable_timeout| in IceConfig when determining the writability state.
331// Replace this constant with the config parameter assuming the default value if
332// we decide it is also applicable here.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700333TCPConnection::TCPConnection(TCPPort* port,
334 const Candidate& candidate,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000335 rtc::AsyncPacketSocket* socket)
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700336 : Connection(port, 0, candidate),
337 socket_(socket),
338 error_(0),
339 outgoing_(socket == NULL),
340 connection_pending_(false),
341 pretending_to_be_writable_(false),
342 reconnection_timeout_(cricket::CONNECTION_WRITE_CONNECT_TIMEOUT) {
343 if (outgoing_) {
344 CreateOutgoingTcpSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000345 } else {
deadbeef5c3c1042017-08-04 15:01:57 -0700346 // Incoming connections should match one of the network addresses. Same as
347 // what's being checked in OnConnect, but just DCHECKing here.
Jonas Olssond7d762d2018-03-28 09:47:51 +0200348 RTC_LOG(LS_VERBOSE) << ToString() << ": socket ipaddr: "
349 << socket_->GetLocalAddress().ToString()
350 << ", port() Network:" << port->Network()->ToString();
deadbeef5c3c1042017-08-04 15:01:57 -0700351 const std::vector<rtc::InterfaceAddress>& desired_addresses =
352 port_->Network()->GetIPs();
Taylor Brandstetter01cb5f22018-03-07 15:49:32 -0800353 RTC_DCHECK(std::find_if(desired_addresses.begin(), desired_addresses.end(),
354 [this](const rtc::InterfaceAddress& addr) {
355 return socket_->GetLocalAddress().ipaddr() ==
356 addr;
357 }) != desired_addresses.end());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700358 ConnectSocketSignals(socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000359 }
360}
361
362TCPConnection::~TCPConnection() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000363}
364
365int TCPConnection::Send(const void* data, size_t size,
366 const rtc::PacketOptions& options) {
367 if (!socket_) {
368 error_ = ENOTCONN;
369 return SOCKET_ERROR;
370 }
371
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700372 // Sending after OnClose on active side will trigger a reconnect for a
373 // outgoing connection. Note that the write state is still WRITABLE as we want
374 // to spend a few seconds attempting a reconnect before saying we're
375 // unwritable.
376 if (!connected()) {
377 MaybeReconnect();
378 return SOCKET_ERROR;
379 }
380
381 // Note that this is important to put this after the previous check to give
382 // the connection a chance to reconnect.
383 if (pretending_to_be_writable_ || write_state() != STATE_WRITABLE) {
Steve Anton6c38cc72017-11-29 10:25:58 -0800384 // TODO(?): Should STATE_WRITE_TIMEOUT return a non-blocking error?
skvladc309e0e2016-07-28 17:15:20 -0700385 error_ = ENOTCONN;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000386 return SOCKET_ERROR;
387 }
zhihuang5ecf16c2016-06-01 17:09:15 -0700388 stats_.sent_total_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000389 int sent = socket_->Send(data, size, options);
390 if (sent < 0) {
zhihuang5ecf16c2016-06-01 17:09:15 -0700391 stats_.sent_discarded_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000392 error_ = socket_->GetError();
393 } else {
Tim Psiaki63046262015-09-14 10:38:08 -0700394 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000395 }
396 return sent;
397}
398
399int TCPConnection::GetError() {
400 return error_;
401}
402
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700403void TCPConnection::OnConnectionRequestResponse(ConnectionRequest* req,
404 StunMessage* response) {
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700405 // Process the STUN response before we inform upper layer ready to send.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700406 Connection::OnConnectionRequestResponse(req, response);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700407
408 // If we're in the state of pretending to be writeable, we should inform the
409 // upper layer it's ready to send again as previous EWOULDLBLOCK from socket
410 // would have stopped the outgoing stream.
411 if (pretending_to_be_writable_) {
412 Connection::OnReadyToSend();
413 }
414 pretending_to_be_writable_ = false;
nisseede5da42017-01-12 05:15:36 -0800415 RTC_DCHECK(write_state() == STATE_WRITABLE);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700416}
417
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000418void TCPConnection::OnConnect(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800419 RTC_DCHECK(socket == socket_.get());
deadbeef5c3c1042017-08-04 15:01:57 -0700420 // Do not use this port if the socket bound to an address not associated with
421 // the desired network interface. This is seen in Chrome, where TCP sockets
422 // cannot be given a binding address, and the platform is expected to pick
423 // the correct local address.
424 //
425 // However, there are two situations in which we allow the bound address to
426 // not be one of the addresses of the requested interface:
427 // 1. The bound address is the loopback address. This happens when a proxy
428 // forces TCP to bind to only the localhost address (see issue 3927).
429 // 2. The bound address is the "any address". This happens when
430 // multiple_routes is disabled (see issue 4780).
431 //
432 // Note that, aside from minor differences in log statements, this logic is
433 // identical to that in TurnPort.
434 const rtc::SocketAddress& socket_address = socket->GetLocalAddress();
435 const std::vector<rtc::InterfaceAddress>& desired_addresses =
436 port_->Network()->GetIPs();
Taylor Brandstetter01cb5f22018-03-07 15:49:32 -0800437 if (std::find_if(desired_addresses.begin(), desired_addresses.end(),
438 [socket_address](const rtc::InterfaceAddress& addr) {
439 return socket_address.ipaddr() == addr;
440 }) != desired_addresses.end()) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200441 RTC_LOG(LS_VERBOSE) << ToString()
442 << ": Connection established to "
443 << socket->GetRemoteAddress().ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000444 } else {
deadbeef5c3c1042017-08-04 15:01:57 -0700445 if (socket->GetLocalAddress().IsLoopbackIP()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100446 RTC_LOG(LS_WARNING) << "Socket is bound to the address:"
447 << socket_address.ipaddr().ToString()
Taylor Brandstetter3ba7a572018-03-02 10:58:25 -0800448 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100449 << port_->Network()->ToString()
450 << ". Still allowing it since it's localhost.";
deadbeef5c3c1042017-08-04 15:01:57 -0700451 } else if (IPIsAny(port_->Network()->GetBestIP())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100452 RTC_LOG(LS_WARNING)
453 << "Socket is bound to the address:"
454 << socket_address.ipaddr().ToString()
Taylor Brandstetter3ba7a572018-03-02 10:58:25 -0800455 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100456 << port_->Network()->ToString()
457 << ". Still allowing it since it's the 'any' address"
Jonas Olssond7d762d2018-03-28 09:47:51 +0200458 ", possibly caused by multiple_routes being disabled.";
deadbeef5c3c1042017-08-04 15:01:57 -0700459 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100460 RTC_LOG(LS_WARNING) << "Dropping connection as TCP socket bound to IP "
461 << socket_address.ipaddr().ToString()
Taylor Brandstetter3ba7a572018-03-02 10:58:25 -0800462 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100463 << port_->Network()->ToString();
deadbeef5c3c1042017-08-04 15:01:57 -0700464 OnClose(socket, 0);
465 return;
466 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000467 }
tommi5ce1a2a2016-05-14 03:19:31 -0700468
469 // Connection is established successfully.
470 set_connected(true);
471 connection_pending_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000472}
473
474void TCPConnection::OnClose(rtc::AsyncPacketSocket* socket, int error) {
nisseede5da42017-01-12 05:15:36 -0800475 RTC_DCHECK(socket == socket_.get());
Jonas Olssond7d762d2018-03-28 09:47:51 +0200476 RTC_LOG(LS_INFO) << ToString()
477 << ": Connection closed with error " << error;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700478
479 // Guard against the condition where IPC socket will call OnClose for every
480 // packet it can't send.
481 if (connected()) {
482 set_connected(false);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700483
484 // Prevent the connection from being destroyed by redundant SignalClose
485 // events.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700486 pretending_to_be_writable_ = true;
487
488 // We don't attempt reconnect right here. This is to avoid a case where the
489 // shutdown is intentional and reconnect is not necessary. We only reconnect
490 // when the connection is used to Send() or Ping().
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700491 port()->thread()->PostDelayed(RTC_FROM_HERE, reconnection_timeout(), this,
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700492 MSG_TCPCONNECTION_DELAYED_ONCLOSE);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700493 } else if (!pretending_to_be_writable_) {
494 // OnClose could be called when the underneath socket times out during the
495 // initial connect() (i.e. |pretending_to_be_writable_| is false) . We have
496 // to manually destroy here as this connection, as never connected, will not
497 // be scheduled for ping to trigger destroy.
498 Destroy();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700499 }
500}
501
502void TCPConnection::OnMessage(rtc::Message* pmsg) {
503 switch (pmsg->message_id) {
504 case MSG_TCPCONNECTION_DELAYED_ONCLOSE:
505 // If this connection can't become connected and writable again in 5
506 // seconds, it's time to tear this down. This is the case for the original
507 // TCP connection on passive side during a reconnect.
508 if (pretending_to_be_writable_) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700509 Destroy();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700510 }
511 break;
512 default:
513 Connection::OnMessage(pmsg);
514 }
515}
516
517void TCPConnection::MaybeReconnect() {
518 // Only reconnect for an outgoing TCPConnection when OnClose was signaled and
519 // no outstanding reconnect is pending.
520 if (connected() || connection_pending_ || !outgoing_) {
521 return;
522 }
523
Jonas Olssond7d762d2018-03-28 09:47:51 +0200524 RTC_LOG(LS_INFO) << ToString()
525 << ": TCP Connection with remote is closed, "
526 "trying to reconnect";
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700527
528 CreateOutgoingTcpSocket();
529 error_ = EPIPE;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000530}
531
532void TCPConnection::OnReadPacket(
533 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
534 const rtc::SocketAddress& remote_addr,
535 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -0800536 RTC_DCHECK(socket == socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000537 Connection::OnReadPacket(data, size, packet_time);
538}
539
540void TCPConnection::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800541 RTC_DCHECK(socket == socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000542 Connection::OnReadyToSend();
543}
544
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700545void TCPConnection::CreateOutgoingTcpSocket() {
nisseede5da42017-01-12 05:15:36 -0800546 RTC_DCHECK(outgoing_);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700547 // TODO(guoweis): Handle failures here (unlikely since TCP).
548 int opts = (remote_candidate().protocol() == SSLTCP_PROTOCOL_NAME)
hnsl04833622017-01-09 08:35:45 -0800549 ? rtc::PacketSocketFactory::OPT_TLS_FAKE
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700550 : 0;
551 socket_.reset(port()->socket_factory()->CreateClientTcpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -0700552 rtc::SocketAddress(port()->Network()->GetBestIP(), 0),
553 remote_candidate().address(), port()->proxy(), port()->user_agent(),
554 opts));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700555 if (socket_) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200556 RTC_LOG(LS_VERBOSE) << ToString()
557 << ": Connecting from "
558 << socket_->GetLocalAddress().ToSensitiveString()
559 << " to "
560 << remote_candidate().address().ToSensitiveString();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700561 set_connected(false);
562 connection_pending_ = true;
563 ConnectSocketSignals(socket_.get());
564 } else {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200565 RTC_LOG(LS_WARNING) << ToString()
566 << ": Failed to create connection to "
567 << remote_candidate().address().ToSensitiveString();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700568 }
569}
570
571void TCPConnection::ConnectSocketSignals(rtc::AsyncPacketSocket* socket) {
572 if (outgoing_) {
573 socket->SignalConnect.connect(this, &TCPConnection::OnConnect);
574 }
575 socket->SignalReadPacket.connect(this, &TCPConnection::OnReadPacket);
576 socket->SignalReadyToSend.connect(this, &TCPConnection::OnReadyToSend);
577 socket->SignalClose.connect(this, &TCPConnection::OnClose);
578}
579
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000580} // namespace cricket