1/*
2 * libjingle
3 * Copyright 2004--2005, Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 *  1. Redistributions of source code must retain the above copyright notice,
9 *     this list of conditions and the following disclaimer.
10 *  2. Redistributions in binary form must reproduce the above copyright notice,
11 *     this list of conditions and the following disclaimer in the documentation
12 *     and/or other materials provided with the distribution.
13 *  3. The name of the author may not be used to endorse or promote products
14 *     derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include "talk/p2p/base/tcpport.h"
29
30#include "talk/p2p/base/common.h"
31#include "webrtc/base/common.h"
32#include "webrtc/base/logging.h"
33
34namespace cricket {
35
36TCPPort::TCPPort(rtc::Thread* thread,
37                 rtc::PacketSocketFactory* factory,
38                 rtc::Network* network, const rtc::IPAddress& ip,
39                 int min_port, int max_port, const std::string& username,
40                 const std::string& password, bool allow_listen)
41    : Port(thread, LOCAL_PORT_TYPE, factory, network, ip, min_port, max_port,
42           username, password),
43      incoming_only_(false),
44      allow_listen_(allow_listen),
45      socket_(NULL),
46      error_(0) {
47  // TODO(mallinath) - Set preference value as per RFC 6544.
48  // http://b/issue?id=7141794
49}
50
51bool TCPPort::Init() {
52  if (allow_listen_) {
53    // Treat failure to create or bind a TCP socket as fatal.  This
54    // should never happen.
55    socket_ = socket_factory()->CreateServerTcpSocket(
56        rtc::SocketAddress(ip(), 0), min_port(), max_port(),
57        false /* ssl */);
58    if (!socket_) {
59      LOG_J(LS_ERROR, this) << "TCP socket creation failed.";
60      return false;
61    }
62    socket_->SignalNewConnection.connect(this, &TCPPort::OnNewConnection);
63    socket_->SignalAddressReady.connect(this, &TCPPort::OnAddressReady);
64  }
65  return true;
66}
67
68TCPPort::~TCPPort() {
69  delete socket_;
70  std::list<Incoming>::iterator it;
71  for (it = incoming_.begin(); it != incoming_.end(); ++it)
72    delete it->socket;
73  incoming_.clear();
74}
75
76Connection* TCPPort::CreateConnection(const Candidate& address,
77                                      CandidateOrigin origin) {
78  // We only support TCP protocols
79  if ((address.protocol() != TCP_PROTOCOL_NAME) &&
80      (address.protocol() != SSLTCP_PROTOCOL_NAME)) {
81    return NULL;
82  }
83
84  if (address.tcptype() == TCPTYPE_ACTIVE_STR ||
85      (address.tcptype().empty() && address.address().port() == 0)) {
86    // It's active only candidate, we should not try to create connections
87    // for these candidates.
88    return NULL;
89  }
90
91  // We can't accept TCP connections incoming on other ports
92  if (origin == ORIGIN_OTHER_PORT)
93    return NULL;
94
95  // Check if we are allowed to make outgoing TCP connections
96  if (incoming_only_ && (origin == ORIGIN_MESSAGE))
97    return NULL;
98
99  // We don't know how to act as an ssl server yet
100  if ((address.protocol() == SSLTCP_PROTOCOL_NAME) &&
101      (origin == ORIGIN_THIS_PORT)) {
102    return NULL;
103  }
104
105  if (!IsCompatibleAddress(address.address())) {
106    return NULL;
107  }
108
109  TCPConnection* conn = NULL;
110  if (rtc::AsyncPacketSocket* socket =
111      GetIncoming(address.address(), true)) {
112    socket->SignalReadPacket.disconnect(this);
113    conn = new TCPConnection(this, address, socket);
114  } else {
115    conn = new TCPConnection(this, address);
116  }
117  AddConnection(conn);
118  return conn;
119}
120
121void TCPPort::PrepareAddress() {
122  if (socket_) {
123    // If socket isn't bound yet the address will be added in
124    // OnAddressReady(). Socket may be in the CLOSED state if Listen()
125    // failed, we still want to add the socket address.
126    LOG(LS_VERBOSE) << "Preparing TCP address, current state: "
127                    << socket_->GetState();
128    if (socket_->GetState() == rtc::AsyncPacketSocket::STATE_BOUND ||
129        socket_->GetState() == rtc::AsyncPacketSocket::STATE_CLOSED)
130      AddAddress(socket_->GetLocalAddress(), socket_->GetLocalAddress(),
131                 rtc::SocketAddress(),
132                 TCP_PROTOCOL_NAME, TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE,
133                 ICE_TYPE_PREFERENCE_HOST_TCP, 0, true);
134  } else {
135    LOG_J(LS_INFO, this) << "Not listening due to firewall restrictions.";
136    // Note: We still add the address, since otherwise the remote side won't
137    // recognize our incoming TCP connections.
138    AddAddress(rtc::SocketAddress(ip(), 0),
139               rtc::SocketAddress(ip(), 0), rtc::SocketAddress(),
140               TCP_PROTOCOL_NAME, TCPTYPE_ACTIVE_STR, LOCAL_PORT_TYPE,
141               ICE_TYPE_PREFERENCE_HOST_TCP, 0, true);
142  }
143}
144
145int TCPPort::SendTo(const void* data, size_t size,
146                    const rtc::SocketAddress& addr,
147                    const rtc::PacketOptions& options,
148                    bool payload) {
149  rtc::AsyncPacketSocket * socket = NULL;
150  if (TCPConnection * conn = static_cast<TCPConnection*>(GetConnection(addr))) {
151    socket = conn->socket();
152  } else {
153    socket = GetIncoming(addr);
154  }
155  if (!socket) {
156    LOG_J(LS_ERROR, this) << "Attempted to send to an unknown destination, "
157                          << addr.ToSensitiveString();
158    return -1;  // TODO: Set error_
159  }
160
161  int sent = socket->Send(data, size, options);
162  if (sent < 0) {
163    error_ = socket->GetError();
164    LOG_J(LS_ERROR, this) << "TCP send of " << size
165                          << " bytes failed with error " << error_;
166  }
167  return sent;
168}
169
170int TCPPort::GetOption(rtc::Socket::Option opt, int* value) {
171  if (socket_) {
172    return socket_->GetOption(opt, value);
173  } else {
174    return SOCKET_ERROR;
175  }
176}
177
178int TCPPort::SetOption(rtc::Socket::Option opt, int value) {
179  if (socket_) {
180    return socket_->SetOption(opt, value);
181  } else {
182    return SOCKET_ERROR;
183  }
184}
185
186int TCPPort::GetError() {
187  return error_;
188}
189
190void TCPPort::OnNewConnection(rtc::AsyncPacketSocket* socket,
191                              rtc::AsyncPacketSocket* new_socket) {
192  ASSERT(socket == socket_);
193
194  Incoming incoming;
195  incoming.addr = new_socket->GetRemoteAddress();
196  incoming.socket = new_socket;
197  incoming.socket->SignalReadPacket.connect(this, &TCPPort::OnReadPacket);
198  incoming.socket->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
199
200  LOG_J(LS_VERBOSE, this) << "Accepted connection from "
201                          << incoming.addr.ToSensitiveString();
202  incoming_.push_back(incoming);
203}
204
205rtc::AsyncPacketSocket* TCPPort::GetIncoming(
206    const rtc::SocketAddress& addr, bool remove) {
207  rtc::AsyncPacketSocket* socket = NULL;
208  for (std::list<Incoming>::iterator it = incoming_.begin();
209       it != incoming_.end(); ++it) {
210    if (it->addr == addr) {
211      socket = it->socket;
212      if (remove)
213        incoming_.erase(it);
214      break;
215    }
216  }
217  return socket;
218}
219
220void TCPPort::OnReadPacket(rtc::AsyncPacketSocket* socket,
221                           const char* data, size_t size,
222                           const rtc::SocketAddress& remote_addr,
223                           const rtc::PacketTime& packet_time) {
224  Port::OnReadPacket(data, size, remote_addr, PROTO_TCP);
225}
226
227void TCPPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
228  Port::OnReadyToSend();
229}
230
231void TCPPort::OnAddressReady(rtc::AsyncPacketSocket* socket,
232                             const rtc::SocketAddress& address) {
233  AddAddress(address, address, rtc::SocketAddress(),
234             TCP_PROTOCOL_NAME, TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE,
235             ICE_TYPE_PREFERENCE_HOST_TCP, 0, true);
236}
237
238TCPConnection::TCPConnection(TCPPort* port, const Candidate& candidate,
239                             rtc::AsyncPacketSocket* socket)
240    : Connection(port, 0, candidate), socket_(socket), error_(0) {
241  bool outgoing = (socket_ == NULL);
242  if (outgoing) {
243    // TODO: Handle failures here (unlikely since TCP).
244    int opts = (candidate.protocol() == SSLTCP_PROTOCOL_NAME) ?
245        rtc::PacketSocketFactory::OPT_SSLTCP : 0;
246    socket_ = port->socket_factory()->CreateClientTcpSocket(
247        rtc::SocketAddress(port->ip(), 0),
248        candidate.address(), port->proxy(), port->user_agent(), opts);
249    if (socket_) {
250      LOG_J(LS_VERBOSE, this) << "Connecting from "
251                              << socket_->GetLocalAddress().ToSensitiveString()
252                              << " to "
253                              << candidate.address().ToSensitiveString();
254      set_connected(false);
255      socket_->SignalConnect.connect(this, &TCPConnection::OnConnect);
256    } else {
257      LOG_J(LS_WARNING, this) << "Failed to create connection to "
258                              << candidate.address().ToSensitiveString();
259    }
260  } else {
261    // Incoming connections should match the network address.
262    ASSERT(socket_->GetLocalAddress().ipaddr() == port->ip());
263  }
264
265  if (socket_) {
266    socket_->SignalReadPacket.connect(this, &TCPConnection::OnReadPacket);
267    socket_->SignalReadyToSend.connect(this, &TCPConnection::OnReadyToSend);
268    socket_->SignalClose.connect(this, &TCPConnection::OnClose);
269  }
270}
271
272TCPConnection::~TCPConnection() {
273  delete socket_;
274}
275
276int TCPConnection::Send(const void* data, size_t size,
277                        const rtc::PacketOptions& options) {
278  if (!socket_) {
279    error_ = ENOTCONN;
280    return SOCKET_ERROR;
281  }
282
283  if (write_state() != STATE_WRITABLE) {
284    // TODO: Should STATE_WRITE_TIMEOUT return a non-blocking error?
285    error_ = EWOULDBLOCK;
286    return SOCKET_ERROR;
287  }
288  int sent = socket_->Send(data, size, options);
289  if (sent < 0) {
290    error_ = socket_->GetError();
291  } else {
292    send_rate_tracker_.Update(sent);
293  }
294  return sent;
295}
296
297int TCPConnection::GetError() {
298  return error_;
299}
300
301void TCPConnection::OnConnect(rtc::AsyncPacketSocket* socket) {
302  ASSERT(socket == socket_);
303  // Do not use this connection if the socket bound to a different address than
304  // the one we asked for. This is seen in Chrome, where TCP sockets cannot be
305  // given a binding address, and the platform is expected to pick the
306  // correct local address.
307  if (socket->GetLocalAddress().ipaddr() == port()->ip()) {
308    LOG_J(LS_VERBOSE, this) << "Connection established to "
309                            << socket->GetRemoteAddress().ToSensitiveString();
310    set_connected(true);
311  } else {
312    LOG_J(LS_WARNING, this) << "Dropping connection as TCP socket bound to a "
313                            << "different address from the local candidate.";
314    socket_->Close();
315  }
316}
317
318void TCPConnection::OnClose(rtc::AsyncPacketSocket* socket, int error) {
319  ASSERT(socket == socket_);
320  LOG_J(LS_VERBOSE, this) << "Connection closed with error " << error;
321  set_connected(false);
322  set_write_state(STATE_WRITE_TIMEOUT);
323}
324
325void TCPConnection::OnReadPacket(
326  rtc::AsyncPacketSocket* socket, const char* data, size_t size,
327  const rtc::SocketAddress& remote_addr,
328  const rtc::PacketTime& packet_time) {
329  ASSERT(socket == socket_);
330  Connection::OnReadPacket(data, size, packet_time);
331}
332
333void TCPConnection::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
334  ASSERT(socket == socket_);
335  Connection::OnReadyToSend();
336}
337
338}  // namespace cricket
339