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