blob: 5c9e0425c80fc3d9ae138288d417ff41c08c7696 [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 *
32 * 7 -------------+
33 * |Connected: N |
34 * Timeout |Writable: N | Timeout
35 * +------------------->|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
58 * 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(),
174 rtc::SocketAddress(),
175 TCP_PROTOCOL_NAME, TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE,
176 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.
181 AddAddress(rtc::SocketAddress(ip(), 0),
182 rtc::SocketAddress(ip(), 0), rtc::SocketAddress(),
183 TCP_PROTOCOL_NAME, TCPTYPE_ACTIVE_STR, LOCAL_PORT_TYPE,
184 ICE_TYPE_PREFERENCE_HOST_TCP, 0, true);
185 }
186}
187
188int TCPPort::SendTo(const void* data, size_t size,
189 const rtc::SocketAddress& addr,
190 const rtc::PacketOptions& options,
191 bool payload) {
192 rtc::AsyncPacketSocket * socket = NULL;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700193 TCPConnection* conn = static_cast<TCPConnection*>(GetConnection(addr));
194
195 // For Connection, this is the code path used by Ping() to establish
196 // WRITABLE. It has to send through the socket directly as TCPConnection::Send
197 // checks writability.
198 if (conn) {
199 if (!conn->connected()) {
200 conn->MaybeReconnect();
201 return SOCKET_ERROR;
202 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000203 socket = conn->socket();
204 } else {
205 socket = GetIncoming(addr);
206 }
207 if (!socket) {
208 LOG_J(LS_ERROR, this) << "Attempted to send to an unknown destination, "
209 << addr.ToSensitiveString();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700210 return SOCKET_ERROR; // TODO(tbd): Set error_
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000211 }
212
213 int sent = socket->Send(data, size, options);
214 if (sent < 0) {
215 error_ = socket->GetError();
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700216 // Error from this code path for a Connection (instead of from a bare
217 // socket) will not trigger reconnecting. In theory, this shouldn't matter
218 // as OnClose should always be called and set connected to false.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000219 LOG_J(LS_ERROR, this) << "TCP send of " << size
220 << " bytes failed with error " << error_;
221 }
222 return sent;
223}
224
225int TCPPort::GetOption(rtc::Socket::Option opt, int* value) {
226 if (socket_) {
227 return socket_->GetOption(opt, value);
228 } else {
229 return SOCKET_ERROR;
230 }
231}
232
233int TCPPort::SetOption(rtc::Socket::Option opt, int value) {
234 if (socket_) {
235 return socket_->SetOption(opt, value);
236 } else {
237 return SOCKET_ERROR;
238 }
239}
240
241int TCPPort::GetError() {
242 return error_;
243}
244
245void TCPPort::OnNewConnection(rtc::AsyncPacketSocket* socket,
246 rtc::AsyncPacketSocket* new_socket) {
247 ASSERT(socket == socket_);
248
249 Incoming incoming;
250 incoming.addr = new_socket->GetRemoteAddress();
251 incoming.socket = new_socket;
252 incoming.socket->SignalReadPacket.connect(this, &TCPPort::OnReadPacket);
253 incoming.socket->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
254
255 LOG_J(LS_VERBOSE, this) << "Accepted connection from "
256 << incoming.addr.ToSensitiveString();
257 incoming_.push_back(incoming);
258}
259
260rtc::AsyncPacketSocket* TCPPort::GetIncoming(
261 const rtc::SocketAddress& addr, bool remove) {
262 rtc::AsyncPacketSocket* socket = NULL;
263 for (std::list<Incoming>::iterator it = incoming_.begin();
264 it != incoming_.end(); ++it) {
265 if (it->addr == addr) {
266 socket = it->socket;
267 if (remove)
268 incoming_.erase(it);
269 break;
270 }
271 }
272 return socket;
273}
274
275void TCPPort::OnReadPacket(rtc::AsyncPacketSocket* socket,
276 const char* data, size_t size,
277 const rtc::SocketAddress& remote_addr,
278 const rtc::PacketTime& packet_time) {
279 Port::OnReadPacket(data, size, remote_addr, PROTO_TCP);
280}
281
282void TCPPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
283 Port::OnReadyToSend();
284}
285
286void TCPPort::OnAddressReady(rtc::AsyncPacketSocket* socket,
287 const rtc::SocketAddress& address) {
288 AddAddress(address, address, rtc::SocketAddress(),
289 TCP_PROTOCOL_NAME, TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE,
290 ICE_TYPE_PREFERENCE_HOST_TCP, 0, true);
291}
292
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700293TCPConnection::TCPConnection(TCPPort* port,
294 const Candidate& candidate,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000295 rtc::AsyncPacketSocket* socket)
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700296 : Connection(port, 0, candidate),
297 socket_(socket),
298 error_(0),
299 outgoing_(socket == NULL),
300 connection_pending_(false),
301 pretending_to_be_writable_(false),
302 reconnection_timeout_(cricket::CONNECTION_WRITE_CONNECT_TIMEOUT) {
303 if (outgoing_) {
304 CreateOutgoingTcpSocket();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000305 } else {
306 // Incoming connections should match the network address.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700307 LOG_J(LS_VERBOSE, this)
308 << "socket ipaddr: " << socket_->GetLocalAddress().ToString()
309 << ",port() ip:" << port->ip().ToString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000310 ASSERT(socket_->GetLocalAddress().ipaddr() == port->ip());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700311 ConnectSocketSignals(socket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000312 }
313}
314
315TCPConnection::~TCPConnection() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000316}
317
318int TCPConnection::Send(const void* data, size_t size,
319 const rtc::PacketOptions& options) {
320 if (!socket_) {
321 error_ = ENOTCONN;
322 return SOCKET_ERROR;
323 }
324
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700325 // Sending after OnClose on active side will trigger a reconnect for a
326 // outgoing connection. Note that the write state is still WRITABLE as we want
327 // to spend a few seconds attempting a reconnect before saying we're
328 // unwritable.
329 if (!connected()) {
330 MaybeReconnect();
331 return SOCKET_ERROR;
332 }
333
334 // Note that this is important to put this after the previous check to give
335 // the connection a chance to reconnect.
336 if (pretending_to_be_writable_ || write_state() != STATE_WRITABLE) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000337 // TODO: Should STATE_WRITE_TIMEOUT return a non-blocking error?
338 error_ = EWOULDBLOCK;
339 return SOCKET_ERROR;
340 }
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000341 sent_packets_total_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000342 int sent = socket_->Send(data, size, options);
343 if (sent < 0) {
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000344 sent_packets_discarded_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000345 error_ = socket_->GetError();
346 } else {
347 send_rate_tracker_.Update(sent);
348 }
349 return sent;
350}
351
352int TCPConnection::GetError() {
353 return error_;
354}
355
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700356void TCPConnection::OnConnectionRequestResponse(ConnectionRequest* req,
357 StunMessage* response) {
358 // Once we receive a binding response, we are really writable, and not just
359 // pretending to be writable.
360 pretending_to_be_writable_ = false;
361 Connection::OnConnectionRequestResponse(req, response);
362 ASSERT(write_state() == STATE_WRITABLE);
363}
364
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000365void TCPConnection::OnConnect(rtc::AsyncPacketSocket* socket) {
366 ASSERT(socket == socket_);
367 // Do not use this connection if the socket bound to a different address than
368 // the one we asked for. This is seen in Chrome, where TCP sockets cannot be
369 // given a binding address, and the platform is expected to pick the
370 // correct local address.
henrike@webrtc.org43e033e2014-11-10 19:40:29 +0000371 const rtc::IPAddress& socket_ip = socket->GetLocalAddress().ipaddr();
372 if (socket_ip == port()->ip()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000373 LOG_J(LS_VERBOSE, this) << "Connection established to "
374 << socket->GetRemoteAddress().ToSensitiveString();
375 set_connected(true);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700376 connection_pending_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000377 } else {
henrike@webrtc.org43e033e2014-11-10 19:40:29 +0000378 LOG_J(LS_WARNING, this) << "Dropping connection as TCP socket bound to IP "
379 << socket_ip.ToSensitiveString()
380 << ", different from the local candidate IP "
381 << port()->ip().ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000382 socket_->Close();
383 }
384}
385
386void TCPConnection::OnClose(rtc::AsyncPacketSocket* socket, int error) {
387 ASSERT(socket == socket_);
henrike@webrtc.org43e033e2014-11-10 19:40:29 +0000388 LOG_J(LS_INFO, this) << "Connection closed with error " << error;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700389
390 // Guard against the condition where IPC socket will call OnClose for every
391 // packet it can't send.
392 if (connected()) {
393 set_connected(false);
394 pretending_to_be_writable_ = true;
395
396 // We don't attempt reconnect right here. This is to avoid a case where the
397 // shutdown is intentional and reconnect is not necessary. We only reconnect
398 // when the connection is used to Send() or Ping().
399 port()->thread()->PostDelayed(reconnection_timeout(), this,
400 MSG_TCPCONNECTION_DELAYED_ONCLOSE);
401 }
402}
403
404void TCPConnection::OnMessage(rtc::Message* pmsg) {
405 switch (pmsg->message_id) {
406 case MSG_TCPCONNECTION_DELAYED_ONCLOSE:
407 // If this connection can't become connected and writable again in 5
408 // seconds, it's time to tear this down. This is the case for the original
409 // TCP connection on passive side during a reconnect.
410 if (pretending_to_be_writable_) {
411 set_write_state(STATE_WRITE_TIMEOUT);
412 }
413 break;
414 default:
415 Connection::OnMessage(pmsg);
416 }
417}
418
419void TCPConnection::MaybeReconnect() {
420 // Only reconnect for an outgoing TCPConnection when OnClose was signaled and
421 // no outstanding reconnect is pending.
422 if (connected() || connection_pending_ || !outgoing_) {
423 return;
424 }
425
426 LOG_J(LS_INFO, this) << "TCP Connection with remote is closed, "
427 << "trying to reconnect";
428
429 CreateOutgoingTcpSocket();
430 error_ = EPIPE;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000431}
432
433void TCPConnection::OnReadPacket(
434 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
435 const rtc::SocketAddress& remote_addr,
436 const rtc::PacketTime& packet_time) {
437 ASSERT(socket == socket_);
438 Connection::OnReadPacket(data, size, packet_time);
439}
440
441void TCPConnection::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
442 ASSERT(socket == socket_);
443 Connection::OnReadyToSend();
444}
445
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700446void TCPConnection::CreateOutgoingTcpSocket() {
447 ASSERT(outgoing_);
448 // TODO(guoweis): Handle failures here (unlikely since TCP).
449 int opts = (remote_candidate().protocol() == SSLTCP_PROTOCOL_NAME)
450 ? rtc::PacketSocketFactory::OPT_SSLTCP
451 : 0;
452 socket_.reset(port()->socket_factory()->CreateClientTcpSocket(
453 rtc::SocketAddress(port()->ip(), 0), remote_candidate().address(),
454 port()->proxy(), port()->user_agent(), opts));
455 if (socket_) {
456 LOG_J(LS_VERBOSE, this)
457 << "Connecting from " << socket_->GetLocalAddress().ToSensitiveString()
458 << " to " << remote_candidate().address().ToSensitiveString();
459 set_connected(false);
460 connection_pending_ = true;
461 ConnectSocketSignals(socket_.get());
462 } else {
463 LOG_J(LS_WARNING, this) << "Failed to create connection to "
464 << remote_candidate().address().ToSensitiveString();
465 }
466}
467
468void TCPConnection::ConnectSocketSignals(rtc::AsyncPacketSocket* socket) {
469 if (outgoing_) {
470 socket->SignalConnect.connect(this, &TCPConnection::OnConnect);
471 }
472 socket->SignalReadPacket.connect(this, &TCPConnection::OnReadPacket);
473 socket->SignalReadyToSend.connect(this, &TCPConnection::OnReadyToSend);
474 socket->SignalClose.connect(this, &TCPConnection::OnClose);
475}
476
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000477} // namespace cricket