blob: cbb25b91927f9fd5268521db5207dc2bd4c2ab3f [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
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000067#include "webrtc/p2p/base/tcpport.h"
68
69#include "webrtc/p2p/base/common.h"
Edward Lemurc20978e2017-07-06 19:44:34 +020070#include "webrtc/rtc_base/checks.h"
71#include "webrtc/rtc_base/logging.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000072
73namespace cricket {
74
75TCPPort::TCPPort(rtc::Thread* thread,
76 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +000077 rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +020078 uint16_t min_port,
79 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +000080 const std::string& username,
81 const std::string& password,
82 bool allow_listen)
Peter Boström0c4e06b2015-10-07 12:23:21 +020083 : Port(thread,
84 LOCAL_PORT_TYPE,
85 factory,
86 network,
Peter Boström0c4e06b2015-10-07 12:23:21 +020087 min_port,
88 max_port,
89 username,
90 password),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000091 incoming_only_(false),
92 allow_listen_(allow_listen),
93 socket_(NULL),
94 error_(0) {
95 // TODO(mallinath) - Set preference value as per RFC 6544.
96 // http://b/issue?id=7141794
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000097 if (allow_listen_) {
deadbeef1ee21252017-06-13 15:49:45 -070098 TryCreateServerSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000099 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000100}
101
102TCPPort::~TCPPort() {
103 delete socket_;
104 std::list<Incoming>::iterator it;
105 for (it = incoming_.begin(); it != incoming_.end(); ++it)
106 delete it->socket;
107 incoming_.clear();
108}
109
110Connection* TCPPort::CreateConnection(const Candidate& address,
111 CandidateOrigin origin) {
Honghai Zhangf9945b22015-12-15 12:20:13 -0800112 if (!SupportsProtocol(address.protocol())) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000113 return NULL;
114 }
115
116 if (address.tcptype() == TCPTYPE_ACTIVE_STR ||
117 (address.tcptype().empty() && address.address().port() == 0)) {
118 // It's active only candidate, we should not try to create connections
119 // for these candidates.
120 return NULL;
121 }
122
123 // We can't accept TCP connections incoming on other ports
124 if (origin == ORIGIN_OTHER_PORT)
125 return NULL;
126
127 // Check if we are allowed to make outgoing TCP connections
128 if (incoming_only_ && (origin == ORIGIN_MESSAGE))
129 return NULL;
130
131 // We don't know how to act as an ssl server yet
132 if ((address.protocol() == SSLTCP_PROTOCOL_NAME) &&
133 (origin == ORIGIN_THIS_PORT)) {
134 return NULL;
135 }
136
137 if (!IsCompatibleAddress(address.address())) {
138 return NULL;
139 }
140
141 TCPConnection* conn = NULL;
142 if (rtc::AsyncPacketSocket* socket =
143 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.
167 LOG(LS_VERBOSE) << "Preparing TCP address, current state: "
168 << socket_->GetState();
169 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 {
176 LOG_J(LS_INFO, this) << "Not listening due to firewall restrictions.";
177 // Note: We still add the address, since otherwise the remote side won't
Guo-wei Shieh310b0932015-11-17 19:15:50 -0800178 // recognize our incoming TCP connections. According to
179 // https://tools.ietf.org/html/rfc6544#section-4.5, for active candidate,
deadbeef5c3c1042017-08-04 15:01:57 -0700180 // the port must be set to the discard port, i.e. 9. We can't be 100% sure
181 // which IP address will actually be used, so GetBestIP is as good as we
182 // can do.
183 // TODO(deadbeef): We could do something like create a dummy socket just to
184 // see what IP we get. But that may be overkill.
185 AddAddress(rtc::SocketAddress(Network()->GetBestIP(), DISCARD_PORT),
186 rtc::SocketAddress(Network()->GetBestIP(), 0),
187 rtc::SocketAddress(), TCP_PROTOCOL_NAME, "", TCPTYPE_ACTIVE_STR,
188 LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP, 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000189 }
190}
191
192int TCPPort::SendTo(const void* data, size_t size,
193 const rtc::SocketAddress& addr,
194 const rtc::PacketOptions& options,
195 bool payload) {
196 rtc::AsyncPacketSocket * socket = NULL;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700197 TCPConnection* conn = static_cast<TCPConnection*>(GetConnection(addr));
198
199 // For Connection, this is the code path used by Ping() to establish
200 // WRITABLE. It has to send through the socket directly as TCPConnection::Send
201 // checks writability.
202 if (conn) {
203 if (!conn->connected()) {
204 conn->MaybeReconnect();
205 return SOCKET_ERROR;
206 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000207 socket = conn->socket();
208 } else {
209 socket = GetIncoming(addr);
210 }
211 if (!socket) {
212 LOG_J(LS_ERROR, this) << "Attempted to send to an unknown destination, "
213 << addr.ToSensitiveString();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700214 return SOCKET_ERROR; // TODO(tbd): Set error_
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000215 }
216
217 int sent = socket->Send(data, size, options);
218 if (sent < 0) {
219 error_ = socket->GetError();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700220 // Error from this code path for a Connection (instead of from a bare
221 // socket) will not trigger reconnecting. In theory, this shouldn't matter
222 // as OnClose should always be called and set connected to false.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000223 LOG_J(LS_ERROR, this) << "TCP send of " << size
224 << " bytes failed with error " << error_;
225 }
226 return sent;
227}
228
229int TCPPort::GetOption(rtc::Socket::Option opt, int* value) {
230 if (socket_) {
231 return socket_->GetOption(opt, value);
232 } else {
233 return SOCKET_ERROR;
234 }
235}
236
237int TCPPort::SetOption(rtc::Socket::Option opt, int value) {
238 if (socket_) {
239 return socket_->SetOption(opt, value);
240 } else {
241 return SOCKET_ERROR;
242 }
243}
244
245int TCPPort::GetError() {
246 return error_;
247}
248
249void TCPPort::OnNewConnection(rtc::AsyncPacketSocket* socket,
250 rtc::AsyncPacketSocket* new_socket) {
nisseede5da42017-01-12 05:15:36 -0800251 RTC_DCHECK(socket == socket_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000252
253 Incoming incoming;
254 incoming.addr = new_socket->GetRemoteAddress();
255 incoming.socket = new_socket;
256 incoming.socket->SignalReadPacket.connect(this, &TCPPort::OnReadPacket);
257 incoming.socket->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
Stefan Holmer55674ff2016-01-14 15:49:16 +0100258 incoming.socket->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000259
260 LOG_J(LS_VERBOSE, this) << "Accepted connection from "
261 << incoming.addr.ToSensitiveString();
262 incoming_.push_back(incoming);
263}
264
deadbeef1ee21252017-06-13 15:49:45 -0700265void TCPPort::TryCreateServerSocket() {
266 socket_ = socket_factory()->CreateServerTcpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -0700267 rtc::SocketAddress(Network()->GetBestIP(), 0), min_port(), max_port(),
268 false /* ssl */);
deadbeef1ee21252017-06-13 15:49:45 -0700269 if (!socket_) {
270 LOG_J(LS_WARNING, this)
271 << "TCP server socket creation failed; continuing anyway.";
272 return;
273 }
274 socket_->SignalNewConnection.connect(this, &TCPPort::OnNewConnection);
275 socket_->SignalAddressReady.connect(this, &TCPPort::OnAddressReady);
276}
277
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000278rtc::AsyncPacketSocket* TCPPort::GetIncoming(
279 const rtc::SocketAddress& addr, bool remove) {
280 rtc::AsyncPacketSocket* socket = NULL;
281 for (std::list<Incoming>::iterator it = incoming_.begin();
282 it != incoming_.end(); ++it) {
283 if (it->addr == addr) {
284 socket = it->socket;
285 if (remove)
286 incoming_.erase(it);
287 break;
288 }
289 }
290 return socket;
291}
292
293void TCPPort::OnReadPacket(rtc::AsyncPacketSocket* socket,
294 const char* data, size_t size,
295 const rtc::SocketAddress& remote_addr,
296 const rtc::PacketTime& packet_time) {
297 Port::OnReadPacket(data, size, remote_addr, PROTO_TCP);
298}
299
Stefan Holmer55674ff2016-01-14 15:49:16 +0100300void TCPPort::OnSentPacket(rtc::AsyncPacketSocket* socket,
301 const rtc::SentPacket& sent_packet) {
Stefan Holmer55674ff2016-01-14 15:49:16 +0100302 PortInterface::SignalSentPacket(sent_packet);
303}
304
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000305void TCPPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
306 Port::OnReadyToSend();
307}
308
309void TCPPort::OnAddressReady(rtc::AsyncPacketSocket* socket,
310 const rtc::SocketAddress& address) {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700311 AddAddress(address, address, rtc::SocketAddress(), TCP_PROTOCOL_NAME, "",
312 TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP,
zhihuang26d99c22017-02-13 12:47:27 -0800313 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000314}
315
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700316TCPConnection::TCPConnection(TCPPort* port,
317 const Candidate& candidate,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000318 rtc::AsyncPacketSocket* socket)
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700319 : Connection(port, 0, candidate),
320 socket_(socket),
321 error_(0),
322 outgoing_(socket == NULL),
323 connection_pending_(false),
324 pretending_to_be_writable_(false),
325 reconnection_timeout_(cricket::CONNECTION_WRITE_CONNECT_TIMEOUT) {
326 if (outgoing_) {
327 CreateOutgoingTcpSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000328 } else {
deadbeef5c3c1042017-08-04 15:01:57 -0700329 // Incoming connections should match one of the network addresses. Same as
330 // what's being checked in OnConnect, but just DCHECKing here.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700331 LOG_J(LS_VERBOSE, this)
332 << "socket ipaddr: " << socket_->GetLocalAddress().ToString()
deadbeef5c3c1042017-08-04 15:01:57 -0700333 << ", port() Network:" << port->Network()->ToString();
334 const std::vector<rtc::InterfaceAddress>& desired_addresses =
335 port_->Network()->GetIPs();
336 RTC_DCHECK(std::find(desired_addresses.begin(), desired_addresses.end(),
337 socket_->GetLocalAddress().ipaddr()) !=
338 desired_addresses.end());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700339 ConnectSocketSignals(socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000340 }
341}
342
343TCPConnection::~TCPConnection() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000344}
345
346int TCPConnection::Send(const void* data, size_t size,
347 const rtc::PacketOptions& options) {
348 if (!socket_) {
349 error_ = ENOTCONN;
350 return SOCKET_ERROR;
351 }
352
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700353 // Sending after OnClose on active side will trigger a reconnect for a
354 // outgoing connection. Note that the write state is still WRITABLE as we want
355 // to spend a few seconds attempting a reconnect before saying we're
356 // unwritable.
357 if (!connected()) {
358 MaybeReconnect();
359 return SOCKET_ERROR;
360 }
361
362 // Note that this is important to put this after the previous check to give
363 // the connection a chance to reconnect.
364 if (pretending_to_be_writable_ || write_state() != STATE_WRITABLE) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000365 // TODO: Should STATE_WRITE_TIMEOUT return a non-blocking error?
skvladc309e0e2016-07-28 17:15:20 -0700366 error_ = ENOTCONN;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000367 return SOCKET_ERROR;
368 }
zhihuang5ecf16c2016-06-01 17:09:15 -0700369 stats_.sent_total_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000370 int sent = socket_->Send(data, size, options);
371 if (sent < 0) {
zhihuang5ecf16c2016-06-01 17:09:15 -0700372 stats_.sent_discarded_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000373 error_ = socket_->GetError();
374 } else {
Tim Psiaki63046262015-09-14 10:38:08 -0700375 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000376 }
377 return sent;
378}
379
380int TCPConnection::GetError() {
381 return error_;
382}
383
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700384void TCPConnection::OnConnectionRequestResponse(ConnectionRequest* req,
385 StunMessage* response) {
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700386 // Process the STUN response before we inform upper layer ready to send.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700387 Connection::OnConnectionRequestResponse(req, response);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700388
389 // If we're in the state of pretending to be writeable, we should inform the
390 // upper layer it's ready to send again as previous EWOULDLBLOCK from socket
391 // would have stopped the outgoing stream.
392 if (pretending_to_be_writable_) {
393 Connection::OnReadyToSend();
394 }
395 pretending_to_be_writable_ = false;
nisseede5da42017-01-12 05:15:36 -0800396 RTC_DCHECK(write_state() == STATE_WRITABLE);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700397}
398
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000399void TCPConnection::OnConnect(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800400 RTC_DCHECK(socket == socket_.get());
deadbeef5c3c1042017-08-04 15:01:57 -0700401 // Do not use this port if the socket bound to an address not associated with
402 // the desired network interface. This is seen in Chrome, where TCP sockets
403 // cannot be given a binding address, and the platform is expected to pick
404 // the correct local address.
405 //
406 // However, there are two situations in which we allow the bound address to
407 // not be one of the addresses of the requested interface:
408 // 1. The bound address is the loopback address. This happens when a proxy
409 // forces TCP to bind to only the localhost address (see issue 3927).
410 // 2. The bound address is the "any address". This happens when
411 // multiple_routes is disabled (see issue 4780).
412 //
413 // Note that, aside from minor differences in log statements, this logic is
414 // identical to that in TurnPort.
415 const rtc::SocketAddress& socket_address = socket->GetLocalAddress();
416 const std::vector<rtc::InterfaceAddress>& desired_addresses =
417 port_->Network()->GetIPs();
418 if (std::find(desired_addresses.begin(), desired_addresses.end(),
419 socket_address.ipaddr()) != desired_addresses.end()) {
tommi5ce1a2a2016-05-14 03:19:31 -0700420 LOG_J(LS_VERBOSE, this) << "Connection established to "
421 << socket->GetRemoteAddress().ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000422 } else {
deadbeef5c3c1042017-08-04 15:01:57 -0700423 if (socket->GetLocalAddress().IsLoopbackIP()) {
424 LOG(LS_WARNING) << "Socket is bound to the address:"
425 << socket_address.ipaddr().ToString()
426 << ", rather then an address associated with network:"
427 << port_->Network()->ToString()
428 << ". Still allowing it since it's localhost.";
429 } else if (IPIsAny(port_->Network()->GetBestIP())) {
430 LOG(LS_WARNING) << "Socket is bound to the address:"
431 << socket_address.ipaddr().ToString()
432 << ", rather then an address associated with network:"
433 << port_->Network()->ToString()
434 << ". Still allowing it since it's the 'any' address"
435 << ", possibly caused by multiple_routes being disabled.";
436 } else {
437 LOG(LS_WARNING) << "Dropping connection as TCP socket bound to IP "
438 << socket_address.ipaddr().ToString()
439 << ", rather then an address associated with network:"
440 << port_->Network()->ToString();
441 OnClose(socket, 0);
442 return;
443 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000444 }
tommi5ce1a2a2016-05-14 03:19:31 -0700445
446 // Connection is established successfully.
447 set_connected(true);
448 connection_pending_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000449}
450
451void TCPConnection::OnClose(rtc::AsyncPacketSocket* socket, int error) {
nisseede5da42017-01-12 05:15:36 -0800452 RTC_DCHECK(socket == socket_.get());
henrike@webrtc.org43e033e2014-11-10 19:40:29 +0000453 LOG_J(LS_INFO, this) << "Connection closed with error " << error;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700454
455 // Guard against the condition where IPC socket will call OnClose for every
456 // packet it can't send.
457 if (connected()) {
458 set_connected(false);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700459
460 // Prevent the connection from being destroyed by redundant SignalClose
461 // events.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700462 pretending_to_be_writable_ = true;
463
464 // We don't attempt reconnect right here. This is to avoid a case where the
465 // shutdown is intentional and reconnect is not necessary. We only reconnect
466 // when the connection is used to Send() or Ping().
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700467 port()->thread()->PostDelayed(RTC_FROM_HERE, reconnection_timeout(), this,
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700468 MSG_TCPCONNECTION_DELAYED_ONCLOSE);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700469 } else if (!pretending_to_be_writable_) {
470 // OnClose could be called when the underneath socket times out during the
471 // initial connect() (i.e. |pretending_to_be_writable_| is false) . We have
472 // to manually destroy here as this connection, as never connected, will not
473 // be scheduled for ping to trigger destroy.
474 Destroy();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700475 }
476}
477
478void TCPConnection::OnMessage(rtc::Message* pmsg) {
479 switch (pmsg->message_id) {
480 case MSG_TCPCONNECTION_DELAYED_ONCLOSE:
481 // If this connection can't become connected and writable again in 5
482 // seconds, it's time to tear this down. This is the case for the original
483 // TCP connection on passive side during a reconnect.
484 if (pretending_to_be_writable_) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700485 Destroy();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700486 }
487 break;
488 default:
489 Connection::OnMessage(pmsg);
490 }
491}
492
493void TCPConnection::MaybeReconnect() {
494 // Only reconnect for an outgoing TCPConnection when OnClose was signaled and
495 // no outstanding reconnect is pending.
496 if (connected() || connection_pending_ || !outgoing_) {
497 return;
498 }
499
500 LOG_J(LS_INFO, this) << "TCP Connection with remote is closed, "
501 << "trying to reconnect";
502
503 CreateOutgoingTcpSocket();
504 error_ = EPIPE;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000505}
506
507void TCPConnection::OnReadPacket(
508 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
509 const rtc::SocketAddress& remote_addr,
510 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -0800511 RTC_DCHECK(socket == socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000512 Connection::OnReadPacket(data, size, packet_time);
513}
514
515void TCPConnection::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800516 RTC_DCHECK(socket == socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000517 Connection::OnReadyToSend();
518}
519
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700520void TCPConnection::CreateOutgoingTcpSocket() {
nisseede5da42017-01-12 05:15:36 -0800521 RTC_DCHECK(outgoing_);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700522 // TODO(guoweis): Handle failures here (unlikely since TCP).
523 int opts = (remote_candidate().protocol() == SSLTCP_PROTOCOL_NAME)
hnsl04833622017-01-09 08:35:45 -0800524 ? rtc::PacketSocketFactory::OPT_TLS_FAKE
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700525 : 0;
526 socket_.reset(port()->socket_factory()->CreateClientTcpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -0700527 rtc::SocketAddress(port()->Network()->GetBestIP(), 0),
528 remote_candidate().address(), port()->proxy(), port()->user_agent(),
529 opts));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700530 if (socket_) {
531 LOG_J(LS_VERBOSE, this)
532 << "Connecting from " << socket_->GetLocalAddress().ToSensitiveString()
533 << " to " << remote_candidate().address().ToSensitiveString();
534 set_connected(false);
535 connection_pending_ = true;
536 ConnectSocketSignals(socket_.get());
537 } else {
538 LOG_J(LS_WARNING, this) << "Failed to create connection to "
539 << remote_candidate().address().ToSensitiveString();
540 }
541}
542
543void TCPConnection::ConnectSocketSignals(rtc::AsyncPacketSocket* socket) {
544 if (outgoing_) {
545 socket->SignalConnect.connect(this, &TCPConnection::OnConnect);
546 }
547 socket->SignalReadPacket.connect(this, &TCPConnection::OnReadPacket);
548 socket->SignalReadyToSend.connect(this, &TCPConnection::OnReadyToSend);
549 socket->SignalClose.connect(this, &TCPConnection::OnClose);
550}
551
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000552} // namespace cricket