blob: 721acc2007035eb688d9a7aa072fb43475ea8477 [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"
70#include "webrtc/base/common.h"
71#include "webrtc/base/logging.h"
72
73namespace cricket {
74
75TCPPort::TCPPort(rtc::Thread* thread,
76 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +000077 rtc::Network* network,
78 const rtc::IPAddress& ip,
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,
88 ip,
89 min_port,
90 max_port,
91 username,
92 password),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000093 incoming_only_(false),
94 allow_listen_(allow_listen),
95 socket_(NULL),
96 error_(0) {
97 // TODO(mallinath) - Set preference value as per RFC 6544.
98 // http://b/issue?id=7141794
99}
100
101bool TCPPort::Init() {
102 if (allow_listen_) {
103 // Treat failure to create or bind a TCP socket as fatal. This
104 // should never happen.
105 socket_ = socket_factory()->CreateServerTcpSocket(
106 rtc::SocketAddress(ip(), 0), min_port(), max_port(),
107 false /* ssl */);
108 if (!socket_) {
109 LOG_J(LS_ERROR, this) << "TCP socket creation failed.";
110 return false;
111 }
112 socket_->SignalNewConnection.connect(this, &TCPPort::OnNewConnection);
113 socket_->SignalAddressReady.connect(this, &TCPPort::OnAddressReady);
114 }
115 return true;
116}
117
118TCPPort::~TCPPort() {
119 delete socket_;
120 std::list<Incoming>::iterator it;
121 for (it = incoming_.begin(); it != incoming_.end(); ++it)
122 delete it->socket;
123 incoming_.clear();
124}
125
126Connection* TCPPort::CreateConnection(const Candidate& address,
127 CandidateOrigin origin) {
128 // We only support TCP protocols
129 if ((address.protocol() != TCP_PROTOCOL_NAME) &&
130 (address.protocol() != SSLTCP_PROTOCOL_NAME)) {
131 return NULL;
132 }
133
134 if (address.tcptype() == TCPTYPE_ACTIVE_STR ||
135 (address.tcptype().empty() && address.address().port() == 0)) {
136 // It's active only candidate, we should not try to create connections
137 // for these candidates.
138 return NULL;
139 }
140
141 // We can't accept TCP connections incoming on other ports
142 if (origin == ORIGIN_OTHER_PORT)
143 return NULL;
144
145 // Check if we are allowed to make outgoing TCP connections
146 if (incoming_only_ && (origin == ORIGIN_MESSAGE))
147 return NULL;
148
149 // We don't know how to act as an ssl server yet
150 if ((address.protocol() == SSLTCP_PROTOCOL_NAME) &&
151 (origin == ORIGIN_THIS_PORT)) {
152 return NULL;
153 }
154
155 if (!IsCompatibleAddress(address.address())) {
156 return NULL;
157 }
158
159 TCPConnection* conn = NULL;
160 if (rtc::AsyncPacketSocket* socket =
161 GetIncoming(address.address(), true)) {
162 socket->SignalReadPacket.disconnect(this);
163 conn = new TCPConnection(this, address, socket);
164 } else {
165 conn = new TCPConnection(this, address);
166 }
167 AddConnection(conn);
168 return conn;
169}
170
171void TCPPort::PrepareAddress() {
172 if (socket_) {
173 // If socket isn't bound yet the address will be added in
174 // OnAddressReady(). Socket may be in the CLOSED state if Listen()
175 // failed, we still want to add the socket address.
176 LOG(LS_VERBOSE) << "Preparing TCP address, current state: "
177 << socket_->GetState();
178 if (socket_->GetState() == rtc::AsyncPacketSocket::STATE_BOUND ||
179 socket_->GetState() == rtc::AsyncPacketSocket::STATE_CLOSED)
180 AddAddress(socket_->GetLocalAddress(), socket_->GetLocalAddress(),
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700181 rtc::SocketAddress(), TCP_PROTOCOL_NAME, "",
182 TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000183 ICE_TYPE_PREFERENCE_HOST_TCP, 0, true);
184 } else {
185 LOG_J(LS_INFO, this) << "Not listening due to firewall restrictions.";
186 // Note: We still add the address, since otherwise the remote side won't
Guo-wei Shieh310b0932015-11-17 19:15:50 -0800187 // recognize our incoming TCP connections. According to
188 // https://tools.ietf.org/html/rfc6544#section-4.5, for active candidate,
189 // the port must be set to the discard port, i.e. 9.
190 AddAddress(rtc::SocketAddress(ip(), DISCARD_PORT),
191 rtc::SocketAddress(ip(), 0), rtc::SocketAddress(),
192 TCP_PROTOCOL_NAME, "", TCPTYPE_ACTIVE_STR, LOCAL_PORT_TYPE,
193 ICE_TYPE_PREFERENCE_HOST_TCP, 0, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000194 }
195}
196
197int TCPPort::SendTo(const void* data, size_t size,
198 const rtc::SocketAddress& addr,
199 const rtc::PacketOptions& options,
200 bool payload) {
201 rtc::AsyncPacketSocket * socket = NULL;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700202 TCPConnection* conn = static_cast<TCPConnection*>(GetConnection(addr));
203
204 // For Connection, this is the code path used by Ping() to establish
205 // WRITABLE. It has to send through the socket directly as TCPConnection::Send
206 // checks writability.
207 if (conn) {
208 if (!conn->connected()) {
209 conn->MaybeReconnect();
210 return SOCKET_ERROR;
211 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000212 socket = conn->socket();
213 } else {
214 socket = GetIncoming(addr);
215 }
216 if (!socket) {
217 LOG_J(LS_ERROR, this) << "Attempted to send to an unknown destination, "
218 << addr.ToSensitiveString();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700219 return SOCKET_ERROR; // TODO(tbd): Set error_
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000220 }
221
222 int sent = socket->Send(data, size, options);
223 if (sent < 0) {
224 error_ = socket->GetError();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700225 // Error from this code path for a Connection (instead of from a bare
226 // socket) will not trigger reconnecting. In theory, this shouldn't matter
227 // as OnClose should always be called and set connected to false.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000228 LOG_J(LS_ERROR, this) << "TCP send of " << size
229 << " bytes failed with error " << error_;
230 }
231 return sent;
232}
233
234int TCPPort::GetOption(rtc::Socket::Option opt, int* value) {
235 if (socket_) {
236 return socket_->GetOption(opt, value);
237 } else {
238 return SOCKET_ERROR;
239 }
240}
241
242int TCPPort::SetOption(rtc::Socket::Option opt, int value) {
243 if (socket_) {
244 return socket_->SetOption(opt, value);
245 } else {
246 return SOCKET_ERROR;
247 }
248}
249
250int TCPPort::GetError() {
251 return error_;
252}
253
254void TCPPort::OnNewConnection(rtc::AsyncPacketSocket* socket,
255 rtc::AsyncPacketSocket* new_socket) {
256 ASSERT(socket == socket_);
257
258 Incoming incoming;
259 incoming.addr = new_socket->GetRemoteAddress();
260 incoming.socket = new_socket;
261 incoming.socket->SignalReadPacket.connect(this, &TCPPort::OnReadPacket);
262 incoming.socket->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
263
264 LOG_J(LS_VERBOSE, this) << "Accepted connection from "
265 << incoming.addr.ToSensitiveString();
266 incoming_.push_back(incoming);
267}
268
269rtc::AsyncPacketSocket* TCPPort::GetIncoming(
270 const rtc::SocketAddress& addr, bool remove) {
271 rtc::AsyncPacketSocket* socket = NULL;
272 for (std::list<Incoming>::iterator it = incoming_.begin();
273 it != incoming_.end(); ++it) {
274 if (it->addr == addr) {
275 socket = it->socket;
276 if (remove)
277 incoming_.erase(it);
278 break;
279 }
280 }
281 return socket;
282}
283
284void TCPPort::OnReadPacket(rtc::AsyncPacketSocket* socket,
285 const char* data, size_t size,
286 const rtc::SocketAddress& remote_addr,
287 const rtc::PacketTime& packet_time) {
288 Port::OnReadPacket(data, size, remote_addr, PROTO_TCP);
289}
290
291void TCPPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
292 Port::OnReadyToSend();
293}
294
295void TCPPort::OnAddressReady(rtc::AsyncPacketSocket* socket,
296 const rtc::SocketAddress& address) {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700297 AddAddress(address, address, rtc::SocketAddress(), TCP_PROTOCOL_NAME, "",
298 TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP,
299 0, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000300}
301
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700302TCPConnection::TCPConnection(TCPPort* port,
303 const Candidate& candidate,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000304 rtc::AsyncPacketSocket* socket)
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700305 : Connection(port, 0, candidate),
306 socket_(socket),
307 error_(0),
308 outgoing_(socket == NULL),
309 connection_pending_(false),
310 pretending_to_be_writable_(false),
311 reconnection_timeout_(cricket::CONNECTION_WRITE_CONNECT_TIMEOUT) {
312 if (outgoing_) {
313 CreateOutgoingTcpSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000314 } else {
315 // Incoming connections should match the network address.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700316 LOG_J(LS_VERBOSE, this)
317 << "socket ipaddr: " << socket_->GetLocalAddress().ToString()
318 << ",port() ip:" << port->ip().ToString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000319 ASSERT(socket_->GetLocalAddress().ipaddr() == port->ip());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700320 ConnectSocketSignals(socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000321 }
322}
323
324TCPConnection::~TCPConnection() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000325}
326
327int TCPConnection::Send(const void* data, size_t size,
328 const rtc::PacketOptions& options) {
329 if (!socket_) {
330 error_ = ENOTCONN;
331 return SOCKET_ERROR;
332 }
333
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700334 // Sending after OnClose on active side will trigger a reconnect for a
335 // outgoing connection. Note that the write state is still WRITABLE as we want
336 // to spend a few seconds attempting a reconnect before saying we're
337 // unwritable.
338 if (!connected()) {
339 MaybeReconnect();
340 return SOCKET_ERROR;
341 }
342
343 // Note that this is important to put this after the previous check to give
344 // the connection a chance to reconnect.
345 if (pretending_to_be_writable_ || write_state() != STATE_WRITABLE) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000346 // TODO: Should STATE_WRITE_TIMEOUT return a non-blocking error?
347 error_ = EWOULDBLOCK;
348 return SOCKET_ERROR;
349 }
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000350 sent_packets_total_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000351 int sent = socket_->Send(data, size, options);
352 if (sent < 0) {
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000353 sent_packets_discarded_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000354 error_ = socket_->GetError();
355 } else {
Tim Psiaki63046262015-09-14 10:38:08 -0700356 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000357 }
358 return sent;
359}
360
361int TCPConnection::GetError() {
362 return error_;
363}
364
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700365void TCPConnection::OnConnectionRequestResponse(ConnectionRequest* req,
366 StunMessage* response) {
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700367 // Process the STUN response before we inform upper layer ready to send.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700368 Connection::OnConnectionRequestResponse(req, response);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700369
370 // If we're in the state of pretending to be writeable, we should inform the
371 // upper layer it's ready to send again as previous EWOULDLBLOCK from socket
372 // would have stopped the outgoing stream.
373 if (pretending_to_be_writable_) {
374 Connection::OnReadyToSend();
375 }
376 pretending_to_be_writable_ = false;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700377 ASSERT(write_state() == STATE_WRITABLE);
378}
379
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000380void TCPConnection::OnConnect(rtc::AsyncPacketSocket* socket) {
381 ASSERT(socket == socket_);
382 // Do not use this connection if the socket bound to a different address than
383 // the one we asked for. This is seen in Chrome, where TCP sockets cannot be
384 // given a binding address, and the platform is expected to pick the
385 // correct local address.
henrike@webrtc.org43e033e2014-11-10 19:40:29 +0000386 const rtc::IPAddress& socket_ip = socket->GetLocalAddress().ipaddr();
Guo-wei Shieh53eee432015-09-23 14:09:09 -0700387 if (socket_ip == port()->ip() || IPIsAny(port()->ip())) {
388 if (socket_ip == port()->ip()) {
389 LOG_J(LS_VERBOSE, this) << "Connection established to "
390 << socket->GetRemoteAddress().ToSensitiveString();
391 } else {
392 LOG(LS_WARNING) << "Socket is bound to a different address:"
393 << socket->GetLocalAddress().ipaddr().ToString()
394 << ", rather then the local port:"
395 << port()->ip().ToString()
396 << ". Still allowing it since it's any address"
397 << ", possibly caused by multi-routes being disabled.";
398 }
Guo-wei Shieh2e4b6202015-09-23 13:57:07 -0700399 set_connected(true);
400 connection_pending_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000401 } else {
henrike@webrtc.org43e033e2014-11-10 19:40:29 +0000402 LOG_J(LS_WARNING, this) << "Dropping connection as TCP socket bound to IP "
403 << socket_ip.ToSensitiveString()
404 << ", different from the local candidate IP "
405 << port()->ip().ToSensitiveString();
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700406 OnClose(socket, 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000407 }
408}
409
410void TCPConnection::OnClose(rtc::AsyncPacketSocket* socket, int error) {
411 ASSERT(socket == socket_);
henrike@webrtc.org43e033e2014-11-10 19:40:29 +0000412 LOG_J(LS_INFO, this) << "Connection closed with error " << error;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700413
414 // Guard against the condition where IPC socket will call OnClose for every
415 // packet it can't send.
416 if (connected()) {
417 set_connected(false);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700418
419 // Prevent the connection from being destroyed by redundant SignalClose
420 // events.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700421 pretending_to_be_writable_ = true;
422
423 // We don't attempt reconnect right here. This is to avoid a case where the
424 // shutdown is intentional and reconnect is not necessary. We only reconnect
425 // when the connection is used to Send() or Ping().
426 port()->thread()->PostDelayed(reconnection_timeout(), this,
427 MSG_TCPCONNECTION_DELAYED_ONCLOSE);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700428 } else if (!pretending_to_be_writable_) {
429 // OnClose could be called when the underneath socket times out during the
430 // initial connect() (i.e. |pretending_to_be_writable_| is false) . We have
431 // to manually destroy here as this connection, as never connected, will not
432 // be scheduled for ping to trigger destroy.
433 Destroy();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700434 }
435}
436
437void TCPConnection::OnMessage(rtc::Message* pmsg) {
438 switch (pmsg->message_id) {
439 case MSG_TCPCONNECTION_DELAYED_ONCLOSE:
440 // If this connection can't become connected and writable again in 5
441 // seconds, it's time to tear this down. This is the case for the original
442 // TCP connection on passive side during a reconnect.
443 if (pretending_to_be_writable_) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700444 Destroy();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700445 }
446 break;
447 default:
448 Connection::OnMessage(pmsg);
449 }
450}
451
452void TCPConnection::MaybeReconnect() {
453 // Only reconnect for an outgoing TCPConnection when OnClose was signaled and
454 // no outstanding reconnect is pending.
455 if (connected() || connection_pending_ || !outgoing_) {
456 return;
457 }
458
459 LOG_J(LS_INFO, this) << "TCP Connection with remote is closed, "
460 << "trying to reconnect";
461
462 CreateOutgoingTcpSocket();
463 error_ = EPIPE;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000464}
465
466void TCPConnection::OnReadPacket(
467 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
468 const rtc::SocketAddress& remote_addr,
469 const rtc::PacketTime& packet_time) {
470 ASSERT(socket == socket_);
471 Connection::OnReadPacket(data, size, packet_time);
472}
473
474void TCPConnection::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
475 ASSERT(socket == socket_);
476 Connection::OnReadyToSend();
477}
478
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700479void TCPConnection::CreateOutgoingTcpSocket() {
480 ASSERT(outgoing_);
481 // TODO(guoweis): Handle failures here (unlikely since TCP).
482 int opts = (remote_candidate().protocol() == SSLTCP_PROTOCOL_NAME)
483 ? rtc::PacketSocketFactory::OPT_SSLTCP
484 : 0;
485 socket_.reset(port()->socket_factory()->CreateClientTcpSocket(
486 rtc::SocketAddress(port()->ip(), 0), remote_candidate().address(),
487 port()->proxy(), port()->user_agent(), opts));
488 if (socket_) {
489 LOG_J(LS_VERBOSE, this)
490 << "Connecting from " << socket_->GetLocalAddress().ToSensitiveString()
491 << " to " << remote_candidate().address().ToSensitiveString();
492 set_connected(false);
493 connection_pending_ = true;
494 ConnectSocketSignals(socket_.get());
495 } else {
496 LOG_J(LS_WARNING, this) << "Failed to create connection to "
497 << remote_candidate().address().ToSensitiveString();
498 }
499}
500
501void TCPConnection::ConnectSocketSignals(rtc::AsyncPacketSocket* socket) {
502 if (outgoing_) {
503 socket->SignalConnect.connect(this, &TCPConnection::OnConnect);
504 }
505 socket->SignalReadPacket.connect(this, &TCPConnection::OnReadPacket);
506 socket->SignalReadyToSend.connect(this, &TCPConnection::OnReadyToSend);
507 socket->SignalClose.connect(this, &TCPConnection::OnClose);
508}
509
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000510} // namespace cricket