blob: 8fcbfe3cdfdf53053da965c8e1c10d64296ad0b4 [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,
79 uint16 min_port,
80 uint16 max_port,
81 const std::string& username,
82 const std::string& password,
83 bool allow_listen)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000084 : Port(thread, LOCAL_PORT_TYPE, factory, network, ip, min_port, max_port,
85 username, password),
86 incoming_only_(false),
87 allow_listen_(allow_listen),
88 socket_(NULL),
89 error_(0) {
90 // TODO(mallinath) - Set preference value as per RFC 6544.
91 // http://b/issue?id=7141794
92}
93
94bool TCPPort::Init() {
95 if (allow_listen_) {
96 // Treat failure to create or bind a TCP socket as fatal. This
97 // should never happen.
98 socket_ = socket_factory()->CreateServerTcpSocket(
99 rtc::SocketAddress(ip(), 0), min_port(), max_port(),
100 false /* ssl */);
101 if (!socket_) {
102 LOG_J(LS_ERROR, this) << "TCP socket creation failed.";
103 return false;
104 }
105 socket_->SignalNewConnection.connect(this, &TCPPort::OnNewConnection);
106 socket_->SignalAddressReady.connect(this, &TCPPort::OnAddressReady);
107 }
108 return true;
109}
110
111TCPPort::~TCPPort() {
112 delete socket_;
113 std::list<Incoming>::iterator it;
114 for (it = incoming_.begin(); it != incoming_.end(); ++it)
115 delete it->socket;
116 incoming_.clear();
117}
118
119Connection* TCPPort::CreateConnection(const Candidate& address,
120 CandidateOrigin origin) {
121 // We only support TCP protocols
122 if ((address.protocol() != TCP_PROTOCOL_NAME) &&
123 (address.protocol() != SSLTCP_PROTOCOL_NAME)) {
124 return NULL;
125 }
126
127 if (address.tcptype() == TCPTYPE_ACTIVE_STR ||
128 (address.tcptype().empty() && address.address().port() == 0)) {
129 // It's active only candidate, we should not try to create connections
130 // for these candidates.
131 return NULL;
132 }
133
134 // We can't accept TCP connections incoming on other ports
135 if (origin == ORIGIN_OTHER_PORT)
136 return NULL;
137
138 // Check if we are allowed to make outgoing TCP connections
139 if (incoming_only_ && (origin == ORIGIN_MESSAGE))
140 return NULL;
141
142 // We don't know how to act as an ssl server yet
143 if ((address.protocol() == SSLTCP_PROTOCOL_NAME) &&
144 (origin == ORIGIN_THIS_PORT)) {
145 return NULL;
146 }
147
148 if (!IsCompatibleAddress(address.address())) {
149 return NULL;
150 }
151
152 TCPConnection* conn = NULL;
153 if (rtc::AsyncPacketSocket* socket =
154 GetIncoming(address.address(), true)) {
155 socket->SignalReadPacket.disconnect(this);
156 conn = new TCPConnection(this, address, socket);
157 } else {
158 conn = new TCPConnection(this, address);
159 }
160 AddConnection(conn);
161 return conn;
162}
163
164void TCPPort::PrepareAddress() {
165 if (socket_) {
166 // If socket isn't bound yet the address will be added in
167 // OnAddressReady(). Socket may be in the CLOSED state if Listen()
168 // failed, we still want to add the socket address.
169 LOG(LS_VERBOSE) << "Preparing TCP address, current state: "
170 << socket_->GetState();
171 if (socket_->GetState() == rtc::AsyncPacketSocket::STATE_BOUND ||
172 socket_->GetState() == rtc::AsyncPacketSocket::STATE_CLOSED)
173 AddAddress(socket_->GetLocalAddress(), socket_->GetLocalAddress(),
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700174 rtc::SocketAddress(), TCP_PROTOCOL_NAME, "",
175 TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000176 ICE_TYPE_PREFERENCE_HOST_TCP, 0, true);
177 } else {
178 LOG_J(LS_INFO, this) << "Not listening due to firewall restrictions.";
179 // Note: We still add the address, since otherwise the remote side won't
180 // recognize our incoming TCP connections.
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700181 AddAddress(rtc::SocketAddress(ip(), 0), rtc::SocketAddress(ip(), 0),
182 rtc::SocketAddress(), TCP_PROTOCOL_NAME, "", TCPTYPE_ACTIVE_STR,
183 LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP, 0, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000184 }
185}
186
187int TCPPort::SendTo(const void* data, size_t size,
188 const rtc::SocketAddress& addr,
189 const rtc::PacketOptions& options,
190 bool payload) {
191 rtc::AsyncPacketSocket * socket = NULL;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700192 TCPConnection* conn = static_cast<TCPConnection*>(GetConnection(addr));
193
194 // For Connection, this is the code path used by Ping() to establish
195 // WRITABLE. It has to send through the socket directly as TCPConnection::Send
196 // checks writability.
197 if (conn) {
198 if (!conn->connected()) {
199 conn->MaybeReconnect();
200 return SOCKET_ERROR;
201 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000202 socket = conn->socket();
203 } else {
204 socket = GetIncoming(addr);
205 }
206 if (!socket) {
207 LOG_J(LS_ERROR, this) << "Attempted to send to an unknown destination, "
208 << addr.ToSensitiveString();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700209 return SOCKET_ERROR; // TODO(tbd): Set error_
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000210 }
211
212 int sent = socket->Send(data, size, options);
213 if (sent < 0) {
214 error_ = socket->GetError();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700215 // Error from this code path for a Connection (instead of from a bare
216 // socket) will not trigger reconnecting. In theory, this shouldn't matter
217 // as OnClose should always be called and set connected to false.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000218 LOG_J(LS_ERROR, this) << "TCP send of " << size
219 << " bytes failed with error " << error_;
220 }
221 return sent;
222}
223
224int TCPPort::GetOption(rtc::Socket::Option opt, int* value) {
225 if (socket_) {
226 return socket_->GetOption(opt, value);
227 } else {
228 return SOCKET_ERROR;
229 }
230}
231
232int TCPPort::SetOption(rtc::Socket::Option opt, int value) {
233 if (socket_) {
234 return socket_->SetOption(opt, value);
235 } else {
236 return SOCKET_ERROR;
237 }
238}
239
240int TCPPort::GetError() {
241 return error_;
242}
243
244void TCPPort::OnNewConnection(rtc::AsyncPacketSocket* socket,
245 rtc::AsyncPacketSocket* new_socket) {
246 ASSERT(socket == socket_);
247
248 Incoming incoming;
249 incoming.addr = new_socket->GetRemoteAddress();
250 incoming.socket = new_socket;
251 incoming.socket->SignalReadPacket.connect(this, &TCPPort::OnReadPacket);
252 incoming.socket->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
253
254 LOG_J(LS_VERBOSE, this) << "Accepted connection from "
255 << incoming.addr.ToSensitiveString();
256 incoming_.push_back(incoming);
257}
258
259rtc::AsyncPacketSocket* TCPPort::GetIncoming(
260 const rtc::SocketAddress& addr, bool remove) {
261 rtc::AsyncPacketSocket* socket = NULL;
262 for (std::list<Incoming>::iterator it = incoming_.begin();
263 it != incoming_.end(); ++it) {
264 if (it->addr == addr) {
265 socket = it->socket;
266 if (remove)
267 incoming_.erase(it);
268 break;
269 }
270 }
271 return socket;
272}
273
274void TCPPort::OnReadPacket(rtc::AsyncPacketSocket* socket,
275 const char* data, size_t size,
276 const rtc::SocketAddress& remote_addr,
277 const rtc::PacketTime& packet_time) {
278 Port::OnReadPacket(data, size, remote_addr, PROTO_TCP);
279}
280
281void TCPPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
282 Port::OnReadyToSend();
283}
284
285void TCPPort::OnAddressReady(rtc::AsyncPacketSocket* socket,
286 const rtc::SocketAddress& address) {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700287 AddAddress(address, address, rtc::SocketAddress(), TCP_PROTOCOL_NAME, "",
288 TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE, ICE_TYPE_PREFERENCE_HOST_TCP,
289 0, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000290}
291
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700292TCPConnection::TCPConnection(TCPPort* port,
293 const Candidate& candidate,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000294 rtc::AsyncPacketSocket* socket)
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700295 : Connection(port, 0, candidate),
296 socket_(socket),
297 error_(0),
298 outgoing_(socket == NULL),
299 connection_pending_(false),
300 pretending_to_be_writable_(false),
301 reconnection_timeout_(cricket::CONNECTION_WRITE_CONNECT_TIMEOUT) {
302 if (outgoing_) {
303 CreateOutgoingTcpSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000304 } else {
305 // Incoming connections should match the network address.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700306 LOG_J(LS_VERBOSE, this)
307 << "socket ipaddr: " << socket_->GetLocalAddress().ToString()
308 << ",port() ip:" << port->ip().ToString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000309 ASSERT(socket_->GetLocalAddress().ipaddr() == port->ip());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700310 ConnectSocketSignals(socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000311 }
312}
313
314TCPConnection::~TCPConnection() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000315}
316
317int TCPConnection::Send(const void* data, size_t size,
318 const rtc::PacketOptions& options) {
319 if (!socket_) {
320 error_ = ENOTCONN;
321 return SOCKET_ERROR;
322 }
323
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700324 // Sending after OnClose on active side will trigger a reconnect for a
325 // outgoing connection. Note that the write state is still WRITABLE as we want
326 // to spend a few seconds attempting a reconnect before saying we're
327 // unwritable.
328 if (!connected()) {
329 MaybeReconnect();
330 return SOCKET_ERROR;
331 }
332
333 // Note that this is important to put this after the previous check to give
334 // the connection a chance to reconnect.
335 if (pretending_to_be_writable_ || write_state() != STATE_WRITABLE) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000336 // TODO: Should STATE_WRITE_TIMEOUT return a non-blocking error?
337 error_ = EWOULDBLOCK;
338 return SOCKET_ERROR;
339 }
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000340 sent_packets_total_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000341 int sent = socket_->Send(data, size, options);
342 if (sent < 0) {
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000343 sent_packets_discarded_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000344 error_ = socket_->GetError();
345 } else {
Tim Psiaki63046262015-09-14 10:38:08 -0700346 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000347 }
348 return sent;
349}
350
351int TCPConnection::GetError() {
352 return error_;
353}
354
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700355void TCPConnection::OnConnectionRequestResponse(ConnectionRequest* req,
356 StunMessage* response) {
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700357 // Process the STUN response before we inform upper layer ready to send.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700358 Connection::OnConnectionRequestResponse(req, response);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700359
360 // If we're in the state of pretending to be writeable, we should inform the
361 // upper layer it's ready to send again as previous EWOULDLBLOCK from socket
362 // would have stopped the outgoing stream.
363 if (pretending_to_be_writable_) {
364 Connection::OnReadyToSend();
365 }
366 pretending_to_be_writable_ = false;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700367 ASSERT(write_state() == STATE_WRITABLE);
368}
369
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000370void TCPConnection::OnConnect(rtc::AsyncPacketSocket* socket) {
371 ASSERT(socket == socket_);
372 // Do not use this connection if the socket bound to a different address than
373 // the one we asked for. This is seen in Chrome, where TCP sockets cannot be
374 // given a binding address, and the platform is expected to pick the
375 // correct local address.
henrike@webrtc.org43e033e2014-11-10 19:40:29 +0000376 const rtc::IPAddress& socket_ip = socket->GetLocalAddress().ipaddr();
377 if (socket_ip == port()->ip()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000378 LOG_J(LS_VERBOSE, this) << "Connection established to "
379 << socket->GetRemoteAddress().ToSensitiveString();
380 set_connected(true);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700381 connection_pending_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000382 } else {
henrike@webrtc.org43e033e2014-11-10 19:40:29 +0000383 LOG_J(LS_WARNING, this) << "Dropping connection as TCP socket bound to IP "
384 << socket_ip.ToSensitiveString()
385 << ", different from the local candidate IP "
386 << port()->ip().ToSensitiveString();
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700387 OnClose(socket, 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000388 }
389}
390
391void TCPConnection::OnClose(rtc::AsyncPacketSocket* socket, int error) {
392 ASSERT(socket == socket_);
henrike@webrtc.org43e033e2014-11-10 19:40:29 +0000393 LOG_J(LS_INFO, this) << "Connection closed with error " << error;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700394
395 // Guard against the condition where IPC socket will call OnClose for every
396 // packet it can't send.
397 if (connected()) {
398 set_connected(false);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700399
400 // Prevent the connection from being destroyed by redundant SignalClose
401 // events.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700402 pretending_to_be_writable_ = true;
403
404 // We don't attempt reconnect right here. This is to avoid a case where the
405 // shutdown is intentional and reconnect is not necessary. We only reconnect
406 // when the connection is used to Send() or Ping().
407 port()->thread()->PostDelayed(reconnection_timeout(), this,
408 MSG_TCPCONNECTION_DELAYED_ONCLOSE);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700409 } else if (!pretending_to_be_writable_) {
410 // OnClose could be called when the underneath socket times out during the
411 // initial connect() (i.e. |pretending_to_be_writable_| is false) . We have
412 // to manually destroy here as this connection, as never connected, will not
413 // be scheduled for ping to trigger destroy.
414 Destroy();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700415 }
416}
417
418void TCPConnection::OnMessage(rtc::Message* pmsg) {
419 switch (pmsg->message_id) {
420 case MSG_TCPCONNECTION_DELAYED_ONCLOSE:
421 // If this connection can't become connected and writable again in 5
422 // seconds, it's time to tear this down. This is the case for the original
423 // TCP connection on passive side during a reconnect.
424 if (pretending_to_be_writable_) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700425 Destroy();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700426 }
427 break;
428 default:
429 Connection::OnMessage(pmsg);
430 }
431}
432
433void TCPConnection::MaybeReconnect() {
434 // Only reconnect for an outgoing TCPConnection when OnClose was signaled and
435 // no outstanding reconnect is pending.
436 if (connected() || connection_pending_ || !outgoing_) {
437 return;
438 }
439
440 LOG_J(LS_INFO, this) << "TCP Connection with remote is closed, "
441 << "trying to reconnect";
442
443 CreateOutgoingTcpSocket();
444 error_ = EPIPE;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000445}
446
447void TCPConnection::OnReadPacket(
448 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
449 const rtc::SocketAddress& remote_addr,
450 const rtc::PacketTime& packet_time) {
451 ASSERT(socket == socket_);
452 Connection::OnReadPacket(data, size, packet_time);
453}
454
455void TCPConnection::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
456 ASSERT(socket == socket_);
457 Connection::OnReadyToSend();
458}
459
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700460void TCPConnection::CreateOutgoingTcpSocket() {
461 ASSERT(outgoing_);
462 // TODO(guoweis): Handle failures here (unlikely since TCP).
463 int opts = (remote_candidate().protocol() == SSLTCP_PROTOCOL_NAME)
464 ? rtc::PacketSocketFactory::OPT_SSLTCP
465 : 0;
466 socket_.reset(port()->socket_factory()->CreateClientTcpSocket(
467 rtc::SocketAddress(port()->ip(), 0), remote_candidate().address(),
468 port()->proxy(), port()->user_agent(), opts));
469 if (socket_) {
470 LOG_J(LS_VERBOSE, this)
471 << "Connecting from " << socket_->GetLocalAddress().ToSensitiveString()
472 << " to " << remote_candidate().address().ToSensitiveString();
473 set_connected(false);
474 connection_pending_ = true;
475 ConnectSocketSignals(socket_.get());
476 } else {
477 LOG_J(LS_WARNING, this) << "Failed to create connection to "
478 << remote_candidate().address().ToSensitiveString();
479 }
480}
481
482void TCPConnection::ConnectSocketSignals(rtc::AsyncPacketSocket* socket) {
483 if (outgoing_) {
484 socket->SignalConnect.connect(this, &TCPConnection::OnConnect);
485 }
486 socket->SignalReadPacket.connect(this, &TCPConnection::OnReadPacket);
487 socket->SignalReadyToSend.connect(this, &TCPConnection::OnReadyToSend);
488 socket->SignalClose.connect(this, &TCPConnection::OnClose);
489}
490
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000491} // namespace cricket