blob: 85d2d8a8cb2cfebee4de50d3e47bb8d55ae9f0f7 [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020069#include "p2p/base/common.h"
70#include "rtc_base/checks.h"
71#include "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.
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 {
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
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700249bool TCPPort::SupportsProtocol(const std::string& protocol) const {
250 return protocol == TCP_PROTOCOL_NAME || protocol == SSLTCP_PROTOCOL_NAME;
251}
252
253ProtocolType TCPPort::GetProtocol() const {
254 return PROTO_TCP;
255}
256
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000257void TCPPort::OnNewConnection(rtc::AsyncPacketSocket* socket,
258 rtc::AsyncPacketSocket* new_socket) {
nisseede5da42017-01-12 05:15:36 -0800259 RTC_DCHECK(socket == socket_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000260
261 Incoming incoming;
262 incoming.addr = new_socket->GetRemoteAddress();
263 incoming.socket = new_socket;
264 incoming.socket->SignalReadPacket.connect(this, &TCPPort::OnReadPacket);
265 incoming.socket->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
Stefan Holmer55674ff2016-01-14 15:49:16 +0100266 incoming.socket->SignalSentPacket.connect(this, &TCPPort::OnSentPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000267
268 LOG_J(LS_VERBOSE, this) << "Accepted connection from "
269 << incoming.addr.ToSensitiveString();
270 incoming_.push_back(incoming);
271}
272
deadbeef1ee21252017-06-13 15:49:45 -0700273void TCPPort::TryCreateServerSocket() {
274 socket_ = socket_factory()->CreateServerTcpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -0700275 rtc::SocketAddress(Network()->GetBestIP(), 0), min_port(), max_port(),
276 false /* ssl */);
deadbeef1ee21252017-06-13 15:49:45 -0700277 if (!socket_) {
278 LOG_J(LS_WARNING, this)
279 << "TCP server socket creation failed; continuing anyway.";
280 return;
281 }
282 socket_->SignalNewConnection.connect(this, &TCPPort::OnNewConnection);
283 socket_->SignalAddressReady.connect(this, &TCPPort::OnAddressReady);
284}
285
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000286rtc::AsyncPacketSocket* TCPPort::GetIncoming(
287 const rtc::SocketAddress& addr, bool remove) {
288 rtc::AsyncPacketSocket* socket = NULL;
289 for (std::list<Incoming>::iterator it = incoming_.begin();
290 it != incoming_.end(); ++it) {
291 if (it->addr == addr) {
292 socket = it->socket;
293 if (remove)
294 incoming_.erase(it);
295 break;
296 }
297 }
298 return socket;
299}
300
301void TCPPort::OnReadPacket(rtc::AsyncPacketSocket* socket,
302 const char* data, size_t size,
303 const rtc::SocketAddress& remote_addr,
304 const rtc::PacketTime& packet_time) {
305 Port::OnReadPacket(data, size, remote_addr, PROTO_TCP);
306}
307
Stefan Holmer55674ff2016-01-14 15:49:16 +0100308void TCPPort::OnSentPacket(rtc::AsyncPacketSocket* socket,
309 const rtc::SentPacket& sent_packet) {
Stefan Holmer55674ff2016-01-14 15:49:16 +0100310 PortInterface::SignalSentPacket(sent_packet);
311}
312
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000313void TCPPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
314 Port::OnReadyToSend();
315}
316
317void TCPPort::OnAddressReady(rtc::AsyncPacketSocket* socket,
318 const rtc::SocketAddress& address) {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700319 AddAddress(address, address, rtc::SocketAddress(), TCP_PROTOCOL_NAME, "",
320 TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP,
zhihuang26d99c22017-02-13 12:47:27 -0800321 0, "", true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000322}
323
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700324TCPConnection::TCPConnection(TCPPort* port,
325 const Candidate& candidate,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000326 rtc::AsyncPacketSocket* socket)
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700327 : Connection(port, 0, candidate),
328 socket_(socket),
329 error_(0),
330 outgoing_(socket == NULL),
331 connection_pending_(false),
332 pretending_to_be_writable_(false),
333 reconnection_timeout_(cricket::CONNECTION_WRITE_CONNECT_TIMEOUT) {
334 if (outgoing_) {
335 CreateOutgoingTcpSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000336 } else {
deadbeef5c3c1042017-08-04 15:01:57 -0700337 // Incoming connections should match one of the network addresses. Same as
338 // what's being checked in OnConnect, but just DCHECKing here.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700339 LOG_J(LS_VERBOSE, this)
340 << "socket ipaddr: " << socket_->GetLocalAddress().ToString()
deadbeef5c3c1042017-08-04 15:01:57 -0700341 << ", port() Network:" << port->Network()->ToString();
342 const std::vector<rtc::InterfaceAddress>& desired_addresses =
343 port_->Network()->GetIPs();
344 RTC_DCHECK(std::find(desired_addresses.begin(), desired_addresses.end(),
345 socket_->GetLocalAddress().ipaddr()) !=
346 desired_addresses.end());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700347 ConnectSocketSignals(socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000348 }
349}
350
351TCPConnection::~TCPConnection() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000352}
353
354int TCPConnection::Send(const void* data, size_t size,
355 const rtc::PacketOptions& options) {
356 if (!socket_) {
357 error_ = ENOTCONN;
358 return SOCKET_ERROR;
359 }
360
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700361 // Sending after OnClose on active side will trigger a reconnect for a
362 // outgoing connection. Note that the write state is still WRITABLE as we want
363 // to spend a few seconds attempting a reconnect before saying we're
364 // unwritable.
365 if (!connected()) {
366 MaybeReconnect();
367 return SOCKET_ERROR;
368 }
369
370 // Note that this is important to put this after the previous check to give
371 // the connection a chance to reconnect.
372 if (pretending_to_be_writable_ || write_state() != STATE_WRITABLE) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000373 // TODO: Should STATE_WRITE_TIMEOUT return a non-blocking error?
skvladc309e0e2016-07-28 17:15:20 -0700374 error_ = ENOTCONN;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000375 return SOCKET_ERROR;
376 }
zhihuang5ecf16c2016-06-01 17:09:15 -0700377 stats_.sent_total_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000378 int sent = socket_->Send(data, size, options);
379 if (sent < 0) {
zhihuang5ecf16c2016-06-01 17:09:15 -0700380 stats_.sent_discarded_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000381 error_ = socket_->GetError();
382 } else {
Tim Psiaki63046262015-09-14 10:38:08 -0700383 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000384 }
385 return sent;
386}
387
388int TCPConnection::GetError() {
389 return error_;
390}
391
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700392void TCPConnection::OnConnectionRequestResponse(ConnectionRequest* req,
393 StunMessage* response) {
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700394 // Process the STUN response before we inform upper layer ready to send.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700395 Connection::OnConnectionRequestResponse(req, response);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700396
397 // If we're in the state of pretending to be writeable, we should inform the
398 // upper layer it's ready to send again as previous EWOULDLBLOCK from socket
399 // would have stopped the outgoing stream.
400 if (pretending_to_be_writable_) {
401 Connection::OnReadyToSend();
402 }
403 pretending_to_be_writable_ = false;
nisseede5da42017-01-12 05:15:36 -0800404 RTC_DCHECK(write_state() == STATE_WRITABLE);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700405}
406
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000407void TCPConnection::OnConnect(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800408 RTC_DCHECK(socket == socket_.get());
deadbeef5c3c1042017-08-04 15:01:57 -0700409 // Do not use this port if the socket bound to an address not associated with
410 // the desired network interface. This is seen in Chrome, where TCP sockets
411 // cannot be given a binding address, and the platform is expected to pick
412 // the correct local address.
413 //
414 // However, there are two situations in which we allow the bound address to
415 // not be one of the addresses of the requested interface:
416 // 1. The bound address is the loopback address. This happens when a proxy
417 // forces TCP to bind to only the localhost address (see issue 3927).
418 // 2. The bound address is the "any address". This happens when
419 // multiple_routes is disabled (see issue 4780).
420 //
421 // Note that, aside from minor differences in log statements, this logic is
422 // identical to that in TurnPort.
423 const rtc::SocketAddress& socket_address = socket->GetLocalAddress();
424 const std::vector<rtc::InterfaceAddress>& desired_addresses =
425 port_->Network()->GetIPs();
426 if (std::find(desired_addresses.begin(), desired_addresses.end(),
427 socket_address.ipaddr()) != desired_addresses.end()) {
tommi5ce1a2a2016-05-14 03:19:31 -0700428 LOG_J(LS_VERBOSE, this) << "Connection established to "
429 << socket->GetRemoteAddress().ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000430 } else {
deadbeef5c3c1042017-08-04 15:01:57 -0700431 if (socket->GetLocalAddress().IsLoopbackIP()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100432 RTC_LOG(LS_WARNING) << "Socket is bound to the address:"
433 << socket_address.ipaddr().ToString()
434 << ", rather then an address associated with network:"
435 << port_->Network()->ToString()
436 << ". Still allowing it since it's localhost.";
deadbeef5c3c1042017-08-04 15:01:57 -0700437 } else if (IPIsAny(port_->Network()->GetBestIP())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100438 RTC_LOG(LS_WARNING)
439 << "Socket is bound to the address:"
440 << socket_address.ipaddr().ToString()
441 << ", rather then an address associated with network:"
442 << port_->Network()->ToString()
443 << ". Still allowing it since it's the 'any' address"
444 << ", possibly caused by multiple_routes being disabled.";
deadbeef5c3c1042017-08-04 15:01:57 -0700445 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100446 RTC_LOG(LS_WARNING) << "Dropping connection as TCP socket bound to IP "
447 << socket_address.ipaddr().ToString()
448 << ", rather then an address associated with network:"
449 << port_->Network()->ToString();
deadbeef5c3c1042017-08-04 15:01:57 -0700450 OnClose(socket, 0);
451 return;
452 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000453 }
tommi5ce1a2a2016-05-14 03:19:31 -0700454
455 // Connection is established successfully.
456 set_connected(true);
457 connection_pending_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000458}
459
460void TCPConnection::OnClose(rtc::AsyncPacketSocket* socket, int error) {
nisseede5da42017-01-12 05:15:36 -0800461 RTC_DCHECK(socket == socket_.get());
henrike@webrtc.org43e033e2014-11-10 19:40:29 +0000462 LOG_J(LS_INFO, this) << "Connection closed with error " << error;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700463
464 // Guard against the condition where IPC socket will call OnClose for every
465 // packet it can't send.
466 if (connected()) {
467 set_connected(false);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700468
469 // Prevent the connection from being destroyed by redundant SignalClose
470 // events.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700471 pretending_to_be_writable_ = true;
472
473 // We don't attempt reconnect right here. This is to avoid a case where the
474 // shutdown is intentional and reconnect is not necessary. We only reconnect
475 // when the connection is used to Send() or Ping().
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700476 port()->thread()->PostDelayed(RTC_FROM_HERE, reconnection_timeout(), this,
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700477 MSG_TCPCONNECTION_DELAYED_ONCLOSE);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700478 } else if (!pretending_to_be_writable_) {
479 // OnClose could be called when the underneath socket times out during the
480 // initial connect() (i.e. |pretending_to_be_writable_| is false) . We have
481 // to manually destroy here as this connection, as never connected, will not
482 // be scheduled for ping to trigger destroy.
483 Destroy();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700484 }
485}
486
487void TCPConnection::OnMessage(rtc::Message* pmsg) {
488 switch (pmsg->message_id) {
489 case MSG_TCPCONNECTION_DELAYED_ONCLOSE:
490 // If this connection can't become connected and writable again in 5
491 // seconds, it's time to tear this down. This is the case for the original
492 // TCP connection on passive side during a reconnect.
493 if (pretending_to_be_writable_) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700494 Destroy();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700495 }
496 break;
497 default:
498 Connection::OnMessage(pmsg);
499 }
500}
501
502void TCPConnection::MaybeReconnect() {
503 // Only reconnect for an outgoing TCPConnection when OnClose was signaled and
504 // no outstanding reconnect is pending.
505 if (connected() || connection_pending_ || !outgoing_) {
506 return;
507 }
508
509 LOG_J(LS_INFO, this) << "TCP Connection with remote is closed, "
510 << "trying to reconnect";
511
512 CreateOutgoingTcpSocket();
513 error_ = EPIPE;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000514}
515
516void TCPConnection::OnReadPacket(
517 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
518 const rtc::SocketAddress& remote_addr,
519 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -0800520 RTC_DCHECK(socket == socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000521 Connection::OnReadPacket(data, size, packet_time);
522}
523
524void TCPConnection::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800525 RTC_DCHECK(socket == socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000526 Connection::OnReadyToSend();
527}
528
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700529void TCPConnection::CreateOutgoingTcpSocket() {
nisseede5da42017-01-12 05:15:36 -0800530 RTC_DCHECK(outgoing_);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700531 // TODO(guoweis): Handle failures here (unlikely since TCP).
532 int opts = (remote_candidate().protocol() == SSLTCP_PROTOCOL_NAME)
hnsl04833622017-01-09 08:35:45 -0800533 ? rtc::PacketSocketFactory::OPT_TLS_FAKE
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700534 : 0;
535 socket_.reset(port()->socket_factory()->CreateClientTcpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -0700536 rtc::SocketAddress(port()->Network()->GetBestIP(), 0),
537 remote_candidate().address(), port()->proxy(), port()->user_agent(),
538 opts));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700539 if (socket_) {
540 LOG_J(LS_VERBOSE, this)
541 << "Connecting from " << socket_->GetLocalAddress().ToSensitiveString()
542 << " to " << remote_candidate().address().ToSensitiveString();
543 set_connected(false);
544 connection_pending_ = true;
545 ConnectSocketSignals(socket_.get());
546 } else {
547 LOG_J(LS_WARNING, this) << "Failed to create connection to "
548 << remote_candidate().address().ToSensitiveString();
549 }
550}
551
552void TCPConnection::ConnectSocketSignals(rtc::AsyncPacketSocket* socket) {
553 if (outgoing_) {
554 socket->SignalConnect.connect(this, &TCPConnection::OnConnect);
555 }
556 socket->SignalReadPacket.connect(this, &TCPConnection::OnReadPacket);
557 socket->SignalReadyToSend.connect(this, &TCPConnection::OnReadyToSend);
558 socket->SignalClose.connect(this, &TCPConnection::OnClose);
559}
560
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000561} // namespace cricket