blob: 89265d7b1189d645d83b06ac11d83fed361f163a [file] [log] [blame]
henrike@webrtc.org1a02faa2014-10-28 22:20:111/*
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
11#include "webrtc/p2p/base/tcpport.h"
12
13#include "webrtc/p2p/base/common.h"
14#include "webrtc/base/common.h"
15#include "webrtc/base/logging.h"
16
17namespace cricket {
18
19TCPPort::TCPPort(rtc::Thread* thread,
20 rtc::PacketSocketFactory* factory,
pkasting@chromium.org8645a5a2014-11-06 20:19:2221 rtc::Network* network,
22 const rtc::IPAddress& ip,
23 uint16 min_port,
24 uint16 max_port,
25 const std::string& username,
26 const std::string& password,
27 bool allow_listen)
henrike@webrtc.org1a02faa2014-10-28 22:20:1128 : Port(thread, LOCAL_PORT_TYPE, factory, network, ip, min_port, max_port,
29 username, password),
30 incoming_only_(false),
31 allow_listen_(allow_listen),
32 socket_(NULL),
33 error_(0) {
34 // TODO(mallinath) - Set preference value as per RFC 6544.
35 // http://b/issue?id=7141794
36}
37
38bool TCPPort::Init() {
39 if (allow_listen_) {
40 // Treat failure to create or bind a TCP socket as fatal. This
41 // should never happen.
42 socket_ = socket_factory()->CreateServerTcpSocket(
43 rtc::SocketAddress(ip(), 0), min_port(), max_port(),
44 false /* ssl */);
45 if (!socket_) {
46 LOG_J(LS_ERROR, this) << "TCP socket creation failed.";
47 return false;
48 }
49 socket_->SignalNewConnection.connect(this, &TCPPort::OnNewConnection);
50 socket_->SignalAddressReady.connect(this, &TCPPort::OnAddressReady);
51 }
52 return true;
53}
54
55TCPPort::~TCPPort() {
56 delete socket_;
57 std::list<Incoming>::iterator it;
58 for (it = incoming_.begin(); it != incoming_.end(); ++it)
59 delete it->socket;
60 incoming_.clear();
61}
62
63Connection* TCPPort::CreateConnection(const Candidate& address,
64 CandidateOrigin origin) {
65 // We only support TCP protocols
66 if ((address.protocol() != TCP_PROTOCOL_NAME) &&
67 (address.protocol() != SSLTCP_PROTOCOL_NAME)) {
68 return NULL;
69 }
70
71 if (address.tcptype() == TCPTYPE_ACTIVE_STR ||
72 (address.tcptype().empty() && address.address().port() == 0)) {
73 // It's active only candidate, we should not try to create connections
74 // for these candidates.
75 return NULL;
76 }
77
78 // We can't accept TCP connections incoming on other ports
79 if (origin == ORIGIN_OTHER_PORT)
80 return NULL;
81
82 // Check if we are allowed to make outgoing TCP connections
83 if (incoming_only_ && (origin == ORIGIN_MESSAGE))
84 return NULL;
85
86 // We don't know how to act as an ssl server yet
87 if ((address.protocol() == SSLTCP_PROTOCOL_NAME) &&
88 (origin == ORIGIN_THIS_PORT)) {
89 return NULL;
90 }
91
92 if (!IsCompatibleAddress(address.address())) {
93 return NULL;
94 }
95
96 TCPConnection* conn = NULL;
97 if (rtc::AsyncPacketSocket* socket =
98 GetIncoming(address.address(), true)) {
99 socket->SignalReadPacket.disconnect(this);
100 conn = new TCPConnection(this, address, socket);
101 } else {
102 conn = new TCPConnection(this, address);
103 }
104 AddConnection(conn);
105 return conn;
106}
107
108void TCPPort::PrepareAddress() {
109 if (socket_) {
110 // If socket isn't bound yet the address will be added in
111 // OnAddressReady(). Socket may be in the CLOSED state if Listen()
112 // failed, we still want to add the socket address.
113 LOG(LS_VERBOSE) << "Preparing TCP address, current state: "
114 << socket_->GetState();
115 if (socket_->GetState() == rtc::AsyncPacketSocket::STATE_BOUND ||
116 socket_->GetState() == rtc::AsyncPacketSocket::STATE_CLOSED)
117 AddAddress(socket_->GetLocalAddress(), socket_->GetLocalAddress(),
118 rtc::SocketAddress(),
119 TCP_PROTOCOL_NAME, TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE,
120 ICE_TYPE_PREFERENCE_HOST_TCP, 0, true);
121 } else {
122 LOG_J(LS_INFO, this) << "Not listening due to firewall restrictions.";
123 // Note: We still add the address, since otherwise the remote side won't
124 // recognize our incoming TCP connections.
125 AddAddress(rtc::SocketAddress(ip(), 0),
126 rtc::SocketAddress(ip(), 0), rtc::SocketAddress(),
127 TCP_PROTOCOL_NAME, TCPTYPE_ACTIVE_STR, LOCAL_PORT_TYPE,
128 ICE_TYPE_PREFERENCE_HOST_TCP, 0, true);
129 }
130}
131
132int TCPPort::SendTo(const void* data, size_t size,
133 const rtc::SocketAddress& addr,
134 const rtc::PacketOptions& options,
135 bool payload) {
136 rtc::AsyncPacketSocket * socket = NULL;
137 if (TCPConnection * conn = static_cast<TCPConnection*>(GetConnection(addr))) {
138 socket = conn->socket();
139 } else {
140 socket = GetIncoming(addr);
141 }
142 if (!socket) {
143 LOG_J(LS_ERROR, this) << "Attempted to send to an unknown destination, "
144 << addr.ToSensitiveString();
145 return -1; // TODO: Set error_
146 }
147
148 int sent = socket->Send(data, size, options);
149 if (sent < 0) {
150 error_ = socket->GetError();
151 LOG_J(LS_ERROR, this) << "TCP send of " << size
152 << " bytes failed with error " << error_;
153 }
154 return sent;
155}
156
157int TCPPort::GetOption(rtc::Socket::Option opt, int* value) {
158 if (socket_) {
159 return socket_->GetOption(opt, value);
160 } else {
161 return SOCKET_ERROR;
162 }
163}
164
165int TCPPort::SetOption(rtc::Socket::Option opt, int value) {
166 if (socket_) {
167 return socket_->SetOption(opt, value);
168 } else {
169 return SOCKET_ERROR;
170 }
171}
172
173int TCPPort::GetError() {
174 return error_;
175}
176
177void TCPPort::OnNewConnection(rtc::AsyncPacketSocket* socket,
178 rtc::AsyncPacketSocket* new_socket) {
179 ASSERT(socket == socket_);
180
181 Incoming incoming;
182 incoming.addr = new_socket->GetRemoteAddress();
183 incoming.socket = new_socket;
184 incoming.socket->SignalReadPacket.connect(this, &TCPPort::OnReadPacket);
185 incoming.socket->SignalReadyToSend.connect(this, &TCPPort::OnReadyToSend);
186
187 LOG_J(LS_VERBOSE, this) << "Accepted connection from "
188 << incoming.addr.ToSensitiveString();
189 incoming_.push_back(incoming);
190}
191
192rtc::AsyncPacketSocket* TCPPort::GetIncoming(
193 const rtc::SocketAddress& addr, bool remove) {
194 rtc::AsyncPacketSocket* socket = NULL;
195 for (std::list<Incoming>::iterator it = incoming_.begin();
196 it != incoming_.end(); ++it) {
197 if (it->addr == addr) {
198 socket = it->socket;
199 if (remove)
200 incoming_.erase(it);
201 break;
202 }
203 }
204 return socket;
205}
206
207void TCPPort::OnReadPacket(rtc::AsyncPacketSocket* socket,
208 const char* data, size_t size,
209 const rtc::SocketAddress& remote_addr,
210 const rtc::PacketTime& packet_time) {
211 Port::OnReadPacket(data, size, remote_addr, PROTO_TCP);
212}
213
214void TCPPort::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
215 Port::OnReadyToSend();
216}
217
218void TCPPort::OnAddressReady(rtc::AsyncPacketSocket* socket,
219 const rtc::SocketAddress& address) {
220 AddAddress(address, address, rtc::SocketAddress(),
221 TCP_PROTOCOL_NAME, TCPTYPE_PASSIVE_STR, LOCAL_PORT_TYPE,
222 ICE_TYPE_PREFERENCE_HOST_TCP, 0, true);
223}
224
225TCPConnection::TCPConnection(TCPPort* port, const Candidate& candidate,
226 rtc::AsyncPacketSocket* socket)
227 : Connection(port, 0, candidate), socket_(socket), error_(0) {
228 bool outgoing = (socket_ == NULL);
229 if (outgoing) {
230 // TODO: Handle failures here (unlikely since TCP).
231 int opts = (candidate.protocol() == SSLTCP_PROTOCOL_NAME) ?
232 rtc::PacketSocketFactory::OPT_SSLTCP : 0;
233 socket_ = port->socket_factory()->CreateClientTcpSocket(
234 rtc::SocketAddress(port->ip(), 0),
235 candidate.address(), port->proxy(), port->user_agent(), opts);
236 if (socket_) {
237 LOG_J(LS_VERBOSE, this) << "Connecting from "
238 << socket_->GetLocalAddress().ToSensitiveString()
239 << " to "
240 << candidate.address().ToSensitiveString();
241 set_connected(false);
242 socket_->SignalConnect.connect(this, &TCPConnection::OnConnect);
243 } else {
244 LOG_J(LS_WARNING, this) << "Failed to create connection to "
245 << candidate.address().ToSensitiveString();
246 }
247 } else {
248 // Incoming connections should match the network address.
249 ASSERT(socket_->GetLocalAddress().ipaddr() == port->ip());
250 }
251
252 if (socket_) {
253 socket_->SignalReadPacket.connect(this, &TCPConnection::OnReadPacket);
254 socket_->SignalReadyToSend.connect(this, &TCPConnection::OnReadyToSend);
255 socket_->SignalClose.connect(this, &TCPConnection::OnClose);
256 }
257}
258
259TCPConnection::~TCPConnection() {
260 delete socket_;
261}
262
263int TCPConnection::Send(const void* data, size_t size,
264 const rtc::PacketOptions& options) {
265 if (!socket_) {
266 error_ = ENOTCONN;
267 return SOCKET_ERROR;
268 }
269
270 if (write_state() != STATE_WRITABLE) {
271 // TODO: Should STATE_WRITE_TIMEOUT return a non-blocking error?
272 error_ = EWOULDBLOCK;
273 return SOCKET_ERROR;
274 }
guoweis@webrtc.org33bbae62014-11-17 19:42:14275 sent_packets_total_++;
henrike@webrtc.org1a02faa2014-10-28 22:20:11276 int sent = socket_->Send(data, size, options);
277 if (sent < 0) {
guoweis@webrtc.org33bbae62014-11-17 19:42:14278 sent_packets_discarded_++;
henrike@webrtc.org1a02faa2014-10-28 22:20:11279 error_ = socket_->GetError();
280 } else {
281 send_rate_tracker_.Update(sent);
282 }
283 return sent;
284}
285
286int TCPConnection::GetError() {
287 return error_;
288}
289
290void TCPConnection::OnConnect(rtc::AsyncPacketSocket* socket) {
291 ASSERT(socket == socket_);
292 // Do not use this connection if the socket bound to a different address than
293 // the one we asked for. This is seen in Chrome, where TCP sockets cannot be
294 // given a binding address, and the platform is expected to pick the
295 // correct local address.
henrike@webrtc.org22d1e462014-11-10 19:40:29296 const rtc::IPAddress& socket_ip = socket->GetLocalAddress().ipaddr();
297 if (socket_ip == port()->ip()) {
henrike@webrtc.org1a02faa2014-10-28 22:20:11298 LOG_J(LS_VERBOSE, this) << "Connection established to "
299 << socket->GetRemoteAddress().ToSensitiveString();
300 set_connected(true);
301 } else {
henrike@webrtc.org22d1e462014-11-10 19:40:29302 LOG_J(LS_WARNING, this) << "Dropping connection as TCP socket bound to IP "
303 << socket_ip.ToSensitiveString()
304 << ", different from the local candidate IP "
305 << port()->ip().ToSensitiveString();
henrike@webrtc.org1a02faa2014-10-28 22:20:11306 socket_->Close();
307 }
308}
309
310void TCPConnection::OnClose(rtc::AsyncPacketSocket* socket, int error) {
311 ASSERT(socket == socket_);
henrike@webrtc.org22d1e462014-11-10 19:40:29312 LOG_J(LS_INFO, this) << "Connection closed with error " << error;
henrike@webrtc.org1a02faa2014-10-28 22:20:11313 set_connected(false);
314 set_write_state(STATE_WRITE_TIMEOUT);
315}
316
317void TCPConnection::OnReadPacket(
318 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
319 const rtc::SocketAddress& remote_addr,
320 const rtc::PacketTime& packet_time) {
321 ASSERT(socket == socket_);
322 Connection::OnReadPacket(data, size, packet_time);
323}
324
325void TCPConnection::OnReadyToSend(rtc::AsyncPacketSocket* socket) {
326 ASSERT(socket == socket_);
327 Connection::OnReadyToSend();
328}
329
330} // namespace cricket