blob: e018ea755d62d7b546aaec29c7c4c24279b65f72 [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;
Yves Gerey665174f2018-06-19 15:03:05 +0200143 if (rtc::AsyncPacketSocket* socket = GetIncoming(address.address(), true)) {
deadbeef06878292017-04-21 14:22:23 -0700144 // Incoming connection; we already created a socket and connected signals,
145 // so we need to hand off the "read packet" responsibility to
146 // TCPConnection.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000147 socket->SignalReadPacket.disconnect(this);
148 conn = new TCPConnection(this, address, socket);
149 } else {
deadbeef06878292017-04-21 14:22:23 -0700150 // Outgoing connection, which will create a new socket for which we still
151 // need to connect SignalReadyToSend and SignalSentPacket.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000152 conn = new TCPConnection(this, address);
deadbeef06878292017-04-21 14:22:23 -0700153 if (conn->socket()) {
154 conn->socket()->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
155 conn->socket()->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
156 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000157 }
honghaiz36f50e82016-06-01 15:57:03 -0700158 AddOrReplaceConnection(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000159 return conn;
160}
161
162void TCPPort::PrepareAddress() {
163 if (socket_) {
164 // If socket isn't bound yet the address will be added in
165 // OnAddressReady(). Socket may be in the CLOSED state if Listen()
166 // failed, we still want to add the socket address.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100167 RTC_LOG(LS_VERBOSE) << "Preparing TCP address, current state: "
168 << socket_->GetState();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000169 if (socket_->GetState() == rtc::AsyncPacketSocket::STATE_BOUND ||
170 socket_->GetState() == rtc::AsyncPacketSocket::STATE_CLOSED)
171 AddAddress(socket_->GetLocalAddress(), socket_->GetLocalAddress(),
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700172 rtc::SocketAddress(), TCP_PROTOCOL_NAME, "",
173 TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE,
zhihuang26d99c22017-02-13 12:47:27 -0800174 ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000175 } else {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200176 RTC_LOG(LS_INFO) << ToString()
177 << ": Not listening due to firewall restrictions.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000178 // Note: We still add the address, since otherwise the remote side won't
Guo-wei Shieh310b0932015-11-17 19:15:50 -0800179 // recognize our incoming TCP connections. According to
180 // https://tools.ietf.org/html/rfc6544#section-4.5, for active candidate,
deadbeef5c3c1042017-08-04 15:01:57 -0700181 // the port must be set to the discard port, i.e. 9. We can't be 100% sure
182 // which IP address will actually be used, so GetBestIP is as good as we
183 // can do.
184 // TODO(deadbeef): We could do something like create a dummy socket just to
185 // see what IP we get. But that may be overkill.
186 AddAddress(rtc::SocketAddress(Network()->GetBestIP(), DISCARD_PORT),
187 rtc::SocketAddress(Network()->GetBestIP(), 0),
188 rtc::SocketAddress(), TCP_PROTOCOL_NAME, "", TCPTYPE_ACTIVE_STR,
189 LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000190 }
191}
192
Yves Gerey665174f2018-06-19 15:03:05 +0200193int TCPPort::SendTo(const void* data,
194 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000195 const rtc::SocketAddress& addr,
196 const rtc::PacketOptions& options,
197 bool payload) {
Yves Gerey665174f2018-06-19 15:03:05 +0200198 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.
Yves Gerey665174f2018-06-19 15:03:05 +0200227 RTC_LOG(LS_ERROR) << ToString() << ": TCP send of " << size
228 << " 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
Yves Gerey665174f2018-06-19 15:03:05 +0200272 RTC_LOG(LS_VERBOSE) << ToString() << ": Accepted connection from "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200273 << 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
Yves Gerey665174f2018-06-19 15:03:05 +0200291rtc::AsyncPacketSocket* TCPPort::GetIncoming(const rtc::SocketAddress& addr,
292 bool remove) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000293 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,
Yves Gerey665174f2018-06-19 15:03:05 +0200307 const char* data,
308 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000309 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +0100310 const int64_t& packet_time_us) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000311 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
Yves Gerey665174f2018-06-19 15:03:05 +0200363TCPConnection::~TCPConnection() {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000364
Yves Gerey665174f2018-06-19 15:03:05 +0200365int TCPConnection::Send(const void* data,
366 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000367 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()) {
Yves Gerey665174f2018-06-19 15:03:05 +0200445 RTC_LOG(LS_VERBOSE) << ToString() << ": Connection established to "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200446 << socket->GetRemoteAddress().ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000447 } else {
deadbeef5c3c1042017-08-04 15:01:57 -0700448 if (socket->GetLocalAddress().IsLoopbackIP()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100449 RTC_LOG(LS_WARNING) << "Socket is bound to the address:"
450 << socket_address.ipaddr().ToString()
Taylor Brandstetter3ba7a572018-03-02 10:58:25 -0800451 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100452 << port_->Network()->ToString()
453 << ". Still allowing it since it's localhost.";
deadbeef5c3c1042017-08-04 15:01:57 -0700454 } else if (IPIsAny(port_->Network()->GetBestIP())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100455 RTC_LOG(LS_WARNING)
456 << "Socket is bound to the address:"
457 << socket_address.ipaddr().ToString()
Taylor Brandstetter3ba7a572018-03-02 10:58:25 -0800458 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100459 << port_->Network()->ToString()
460 << ". Still allowing it since it's the 'any' address"
Jonas Olssond7d762d2018-03-28 09:47:51 +0200461 ", possibly caused by multiple_routes being disabled.";
deadbeef5c3c1042017-08-04 15:01:57 -0700462 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100463 RTC_LOG(LS_WARNING) << "Dropping connection as TCP socket bound to IP "
464 << socket_address.ipaddr().ToString()
Taylor Brandstetter3ba7a572018-03-02 10:58:25 -0800465 << ", rather than an address associated with network:"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100466 << port_->Network()->ToString();
deadbeef5c3c1042017-08-04 15:01:57 -0700467 OnClose(socket, 0);
468 return;
469 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000470 }
tommi5ce1a2a2016-05-14 03:19:31 -0700471
472 // Connection is established successfully.
473 set_connected(true);
474 connection_pending_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000475}
476
477void TCPConnection::OnClose(rtc::AsyncPacketSocket* socket, int error) {
nisseede5da42017-01-12 05:15:36 -0800478 RTC_DCHECK(socket == socket_.get());
Yves Gerey665174f2018-06-19 15:03:05 +0200479 RTC_LOG(LS_INFO) << ToString() << ": Connection closed with error " << error;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700480
481 // Guard against the condition where IPC socket will call OnClose for every
482 // packet it can't send.
483 if (connected()) {
484 set_connected(false);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700485
486 // Prevent the connection from being destroyed by redundant SignalClose
487 // events.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700488 pretending_to_be_writable_ = true;
489
490 // We don't attempt reconnect right here. This is to avoid a case where the
491 // shutdown is intentional and reconnect is not necessary. We only reconnect
492 // when the connection is used to Send() or Ping().
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700493 port()->thread()->PostDelayed(RTC_FROM_HERE, reconnection_timeout(), this,
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700494 MSG_TCPCONNECTION_DELAYED_ONCLOSE);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700495 } else if (!pretending_to_be_writable_) {
496 // OnClose could be called when the underneath socket times out during the
497 // initial connect() (i.e. |pretending_to_be_writable_| is false) . We have
498 // to manually destroy here as this connection, as never connected, will not
499 // be scheduled for ping to trigger destroy.
500 Destroy();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700501 }
502}
503
504void TCPConnection::OnMessage(rtc::Message* pmsg) {
505 switch (pmsg->message_id) {
506 case MSG_TCPCONNECTION_DELAYED_ONCLOSE:
507 // If this connection can't become connected and writable again in 5
508 // seconds, it's time to tear this down. This is the case for the original
509 // TCP connection on passive side during a reconnect.
510 if (pretending_to_be_writable_) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700511 Destroy();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700512 }
513 break;
514 default:
515 Connection::OnMessage(pmsg);
516 }
517}
518
519void TCPConnection::MaybeReconnect() {
520 // Only reconnect for an outgoing TCPConnection when OnClose was signaled and
521 // no outstanding reconnect is pending.
522 if (connected() || connection_pending_ || !outgoing_) {
523 return;
524 }
525
Jonas Olssond7d762d2018-03-28 09:47:51 +0200526 RTC_LOG(LS_INFO) << ToString()
527 << ": TCP Connection with remote is closed, "
528 "trying to reconnect";
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700529
530 CreateOutgoingTcpSocket();
531 error_ = EPIPE;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000532}
533
Yves Gerey665174f2018-06-19 15:03:05 +0200534void TCPConnection::OnReadPacket(rtc::AsyncPacketSocket* socket,
535 const char* data,
536 size_t size,
537 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +0100538 const int64_t& packet_time_us) {
nisseede5da42017-01-12 05:15:36 -0800539 RTC_DCHECK(socket == socket_.get());
Niels Möllere6933812018-11-05 13:01:41 +0100540 Connection::OnReadPacket(data, size, packet_time_us);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000541}
542
543void TCPConnection::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800544 RTC_DCHECK(socket == socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000545 Connection::OnReadyToSend();
546}
547
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700548void TCPConnection::CreateOutgoingTcpSocket() {
nisseede5da42017-01-12 05:15:36 -0800549 RTC_DCHECK(outgoing_);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700550 // TODO(guoweis): Handle failures here (unlikely since TCP).
551 int opts = (remote_candidate().protocol() == SSLTCP_PROTOCOL_NAME)
hnsl04833622017-01-09 08:35:45 -0800552 ? rtc::PacketSocketFactory::OPT_TLS_FAKE
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700553 : 0;
554 socket_.reset(port()->socket_factory()->CreateClientTcpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -0700555 rtc::SocketAddress(port()->Network()->GetBestIP(), 0),
556 remote_candidate().address(), port()->proxy(), port()->user_agent(),
557 opts));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700558 if (socket_) {
Yves Gerey665174f2018-06-19 15:03:05 +0200559 RTC_LOG(LS_VERBOSE) << ToString() << ": Connecting from "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200560 << socket_->GetLocalAddress().ToSensitiveString()
561 << " to "
562 << remote_candidate().address().ToSensitiveString();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700563 set_connected(false);
564 connection_pending_ = true;
565 ConnectSocketSignals(socket_.get());
566 } else {
Yves Gerey665174f2018-06-19 15:03:05 +0200567 RTC_LOG(LS_WARNING) << ToString() << ": Failed to create connection to "
Jonas Olssond7d762d2018-03-28 09:47:51 +0200568 << remote_candidate().address().ToSensitiveString();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700569 }
570}
571
572void TCPConnection::ConnectSocketSignals(rtc::AsyncPacketSocket* socket) {
573 if (outgoing_) {
574 socket->SignalConnect.connect(this, &TCPConnection::OnConnect);
575 }
576 socket->SignalReadPacket.connect(this, &TCPConnection::OnReadPacket);
577 socket->SignalReadyToSend.connect(this, &TCPConnection::OnReadyToSend);
578 socket->SignalClose.connect(this, &TCPConnection::OnClose);
579}
580
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000581} // namespace cricket