blob: 385022c11aa98fd7be768c672617c5a900d5b5de [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/port.h"
12
13#include <algorithm>
14#include <vector>
15
16#include "webrtc/p2p/base/common.h"
17#include "webrtc/p2p/base/portallocator.h"
18#include "webrtc/base/base64.h"
nissec80e7412017-01-11 05:56:46 -080019#include "webrtc/base/checks.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000020#include "webrtc/base/crc32.h"
21#include "webrtc/base/helpers.h"
22#include "webrtc/base/logging.h"
23#include "webrtc/base/messagedigest.h"
honghaize3c6c822016-02-17 13:00:28 -080024#include "webrtc/base/network.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000025#include "webrtc/base/stringencode.h"
26#include "webrtc/base/stringutils.h"
27
28namespace {
29
30// Determines whether we have seen at least the given maximum number of
31// pings fail to have a response.
32inline bool TooManyFailures(
Peter Thatcher1cf6f812015-05-15 10:40:45 -070033 const std::vector<cricket::Connection::SentPing>& pings_since_last_response,
Peter Boström0c4e06b2015-10-07 12:23:21 +020034 uint32_t maximum_failures,
honghaiz34b11eb2016-03-16 08:55:44 -070035 int rtt_estimate,
36 int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000037 // If we haven't sent that many pings, then we can't have failed that many.
38 if (pings_since_last_response.size() < maximum_failures)
39 return false;
40
41 // Check if the window in which we would expect a response to the ping has
42 // already elapsed.
honghaiz34b11eb2016-03-16 08:55:44 -070043 int64_t expected_response_time =
Peter Thatcher1cf6f812015-05-15 10:40:45 -070044 pings_since_last_response[maximum_failures - 1].sent_time + rtt_estimate;
45 return now > expected_response_time;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000046}
47
48// Determines whether we have gone too long without seeing any response.
49inline bool TooLongWithoutResponse(
Peter Thatcher1cf6f812015-05-15 10:40:45 -070050 const std::vector<cricket::Connection::SentPing>& pings_since_last_response,
honghaiz34b11eb2016-03-16 08:55:44 -070051 int64_t maximum_time,
52 int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000053 if (pings_since_last_response.size() == 0)
54 return false;
55
Peter Thatcher1cf6f812015-05-15 10:40:45 -070056 auto first = pings_since_last_response[0];
57 return now > (first.sent_time + maximum_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000058}
59
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000060// We will restrict RTT estimates (when used for determining state) to be
61// within a reasonable range.
honghaiz34b11eb2016-03-16 08:55:44 -070062const int MINIMUM_RTT = 100; // 0.1 seconds
skvlad51072462017-02-02 11:50:14 -080063const int MAXIMUM_RTT = 60000; // 60 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000064
65// When we don't have any RTT data, we have to pick something reasonable. We
66// use a large value just in case the connection is really slow.
skvlad51072462017-02-02 11:50:14 -080067const int DEFAULT_RTT = 3000; // 3 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000068
69// Computes our estimate of the RTT given the current estimate.
honghaiz34b11eb2016-03-16 08:55:44 -070070inline int ConservativeRTTEstimate(int rtt) {
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000071 return std::max(MINIMUM_RTT, std::min(MAXIMUM_RTT, 2 * rtt));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000072}
73
74// Weighting of the old rtt value to new data.
75const int RTT_RATIO = 3; // 3 : 1
76
pthatcher94a2f212017-02-08 14:42:22 -080077// The delay before we begin checking if this port is useless. We set
78// it to a little higher than a total STUN timeout.
79const int kPortTimeoutDelay = cricket::STUN_TOTAL_TIMEOUT + 5000;
Honghai Zhang351d77b2016-05-20 15:08:29 -070080} // namespace
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000081
82namespace cricket {
83
84// TODO(ronghuawu): Use "host", "srflx", "prflx" and "relay". But this requires
85// the signaling part be updated correspondingly as well.
86const char LOCAL_PORT_TYPE[] = "local";
87const char STUN_PORT_TYPE[] = "stun";
88const char PRFLX_PORT_TYPE[] = "prflx";
89const char RELAY_PORT_TYPE[] = "relay";
90
91const char UDP_PROTOCOL_NAME[] = "udp";
92const char TCP_PROTOCOL_NAME[] = "tcp";
93const char SSLTCP_PROTOCOL_NAME[] = "ssltcp";
hnsl277b2502016-12-13 05:17:23 -080094const char TLS_PROTOCOL_NAME[] = "tls";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000095
hnsl277b2502016-12-13 05:17:23 -080096static const char* const PROTO_NAMES[] = {UDP_PROTOCOL_NAME, TCP_PROTOCOL_NAME,
97 SSLTCP_PROTOCOL_NAME,
98 TLS_PROTOCOL_NAME};
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000099
100const char* ProtoToString(ProtocolType proto) {
101 return PROTO_NAMES[proto];
102}
103
104bool StringToProto(const char* value, ProtocolType* proto) {
105 for (size_t i = 0; i <= PROTO_LAST; ++i) {
106 if (_stricmp(PROTO_NAMES[i], value) == 0) {
107 *proto = static_cast<ProtocolType>(i);
108 return true;
109 }
110 }
111 return false;
112}
113
114// RFC 6544, TCP candidate encoding rules.
115const int DISCARD_PORT = 9;
116const char TCPTYPE_ACTIVE_STR[] = "active";
117const char TCPTYPE_PASSIVE_STR[] = "passive";
118const char TCPTYPE_SIMOPEN_STR[] = "so";
119
120// Foundation: An arbitrary string that is the same for two candidates
121// that have the same type, base IP address, protocol (UDP, TCP,
122// etc.), and STUN or TURN server. If any of these are different,
123// then the foundation will be different. Two candidate pairs with
124// the same foundation pairs are likely to have similar network
125// characteristics. Foundations are used in the frozen algorithm.
Honghai Zhang80f1db92016-01-27 11:54:45 -0800126static std::string ComputeFoundation(const std::string& type,
127 const std::string& protocol,
128 const std::string& relay_protocol,
129 const rtc::SocketAddress& base_address) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000130 std::ostringstream ost;
Honghai Zhang80f1db92016-01-27 11:54:45 -0800131 ost << type << base_address.ipaddr().ToString() << protocol << relay_protocol;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200132 return rtc::ToString<uint32_t>(rtc::ComputeCrc32(ost.str()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000133}
134
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000135Port::Port(rtc::Thread* thread,
Honghai Zhangd00c0572016-06-28 09:44:47 -0700136 const std::string& type,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000137 rtc::PacketSocketFactory* factory,
138 rtc::Network* network,
139 const rtc::IPAddress& ip,
140 const std::string& username_fragment,
141 const std::string& password)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000142 : thread_(thread),
143 factory_(factory),
Honghai Zhangd00c0572016-06-28 09:44:47 -0700144 type_(type),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000145 send_retransmit_count_attribute_(false),
146 network_(network),
147 ip_(ip),
148 min_port_(0),
149 max_port_(0),
150 component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
151 generation_(0),
152 ice_username_fragment_(username_fragment),
153 password_(password),
154 timeout_delay_(kPortTimeoutDelay),
155 enable_port_packets_(false),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000156 ice_role_(ICEROLE_UNKNOWN),
157 tiebreaker_(0),
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700158 shared_socket_(true) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000159 Construct();
160}
161
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000162Port::Port(rtc::Thread* thread,
163 const std::string& type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000164 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000165 rtc::Network* network,
166 const rtc::IPAddress& ip,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200167 uint16_t min_port,
168 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000169 const std::string& username_fragment,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000170 const std::string& password)
171 : thread_(thread),
172 factory_(factory),
173 type_(type),
174 send_retransmit_count_attribute_(false),
175 network_(network),
176 ip_(ip),
177 min_port_(min_port),
178 max_port_(max_port),
179 component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
180 generation_(0),
181 ice_username_fragment_(username_fragment),
182 password_(password),
183 timeout_delay_(kPortTimeoutDelay),
184 enable_port_packets_(false),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000185 ice_role_(ICEROLE_UNKNOWN),
186 tiebreaker_(0),
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700187 shared_socket_(false) {
nisseede5da42017-01-12 05:15:36 -0800188 RTC_DCHECK(factory_ != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000189 Construct();
190}
191
192void Port::Construct() {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700193 // TODO(pthatcher): Remove this old behavior once we're sure no one
194 // relies on it. If the username_fragment and password are empty,
195 // we should just create one.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000196 if (ice_username_fragment_.empty()) {
nisseede5da42017-01-12 05:15:36 -0800197 RTC_DCHECK(password_.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000198 ice_username_fragment_ = rtc::CreateRandomString(ICE_UFRAG_LENGTH);
199 password_ = rtc::CreateRandomString(ICE_PWD_LENGTH);
200 }
Honghai Zhang351d77b2016-05-20 15:08:29 -0700201 network_->SignalTypeChanged.connect(this, &Port::OnNetworkTypeChanged);
202 network_cost_ = network_->GetCost();
honghaize1a0c942016-02-16 14:54:56 -0800203
Honghai Zhanga74363c2016-07-28 18:06:15 -0700204 thread_->PostDelayed(RTC_FROM_HERE, timeout_delay_, this,
205 MSG_DESTROY_IF_DEAD);
Honghai Zhang351d77b2016-05-20 15:08:29 -0700206 LOG_J(LS_INFO, this) << "Port created with network cost " << network_cost_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000207}
208
209Port::~Port() {
210 // Delete all of the remaining connections. We copy the list up front
211 // because each deletion will cause it to be modified.
212
213 std::vector<Connection*> list;
214
215 AddressMap::iterator iter = connections_.begin();
216 while (iter != connections_.end()) {
217 list.push_back(iter->second);
218 ++iter;
219 }
220
Peter Boström0c4e06b2015-10-07 12:23:21 +0200221 for (uint32_t i = 0; i < list.size(); i++)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000222 delete list[i];
223}
224
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700225void Port::SetIceParameters(int component,
226 const std::string& username_fragment,
227 const std::string& password) {
228 component_ = component;
229 ice_username_fragment_ = username_fragment;
230 password_ = password;
231 for (Candidate& c : candidates_) {
232 c.set_component(component);
233 c.set_username(username_fragment);
234 c.set_password(password);
235 }
236}
237
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000238Connection* Port::GetConnection(const rtc::SocketAddress& remote_addr) {
239 AddressMap::const_iterator iter = connections_.find(remote_addr);
240 if (iter != connections_.end())
241 return iter->second;
242 else
243 return NULL;
244}
245
246void Port::AddAddress(const rtc::SocketAddress& address,
247 const rtc::SocketAddress& base_address,
248 const rtc::SocketAddress& related_address,
249 const std::string& protocol,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700250 const std::string& relay_protocol,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000251 const std::string& tcptype,
252 const std::string& type,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200253 uint32_t type_preference,
254 uint32_t relay_preference,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000255 bool final) {
256 if (protocol == TCP_PROTOCOL_NAME && type == LOCAL_PORT_TYPE) {
nisseede5da42017-01-12 05:15:36 -0800257 RTC_DCHECK(!tcptype.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000258 }
259
honghaiza0c44ea2016-03-23 16:07:48 -0700260 std::string foundation =
261 ComputeFoundation(type, protocol, relay_protocol, base_address);
262 Candidate c(component_, protocol, address, 0U, username_fragment(), password_,
263 type, generation_, foundation, network_->id(), network_cost_);
264 c.set_priority(
265 c.GetPriority(type_preference, network_->preference(), relay_preference));
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700266 c.set_relay_protocol(relay_protocol);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000267 c.set_tcptype(tcptype);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000268 c.set_network_name(network_->name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +0000269 c.set_network_type(network_->type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000270 c.set_related_address(related_address);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000271 candidates_.push_back(c);
272 SignalCandidateReady(this, c);
273
274 if (final) {
275 SignalPortComplete(this);
276 }
277}
278
honghaiz36f50e82016-06-01 15:57:03 -0700279void Port::AddOrReplaceConnection(Connection* conn) {
280 auto ret = connections_.insert(
281 std::make_pair(conn->remote_candidate().address(), conn));
282 // If there is a different connection on the same remote address, replace
283 // it with the new one and destroy the old one.
284 if (ret.second == false && ret.first->second != conn) {
285 LOG_J(LS_WARNING, this)
286 << "A new connection was created on an existing remote address. "
287 << "New remote candidate: " << conn->remote_candidate().ToString();
288 ret.first->second->SignalDestroyed.disconnect(this);
289 ret.first->second->Destroy();
290 ret.first->second = conn;
291 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000292 conn->SignalDestroyed.connect(this, &Port::OnConnectionDestroyed);
293 SignalConnectionCreated(this, conn);
294}
295
296void Port::OnReadPacket(
297 const char* data, size_t size, const rtc::SocketAddress& addr,
298 ProtocolType proto) {
299 // If the user has enabled port packets, just hand this over.
300 if (enable_port_packets_) {
301 SignalReadPacket(this, data, size, addr);
302 return;
303 }
304
305 // If this is an authenticated STUN request, then signal unknown address and
306 // send back a proper binding response.
kwiberg3ec46792016-04-27 07:22:53 -0700307 std::unique_ptr<IceMessage> msg;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000308 std::string remote_username;
kwiberg6baec032016-03-15 11:09:39 -0700309 if (!GetStunMessage(data, size, addr, &msg, &remote_username)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000310 LOG_J(LS_ERROR, this) << "Received non-STUN packet from unknown address ("
311 << addr.ToSensitiveString() << ")";
312 } else if (!msg) {
313 // STUN message handled already
314 } else if (msg->type() == STUN_BINDING_REQUEST) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700315 LOG(LS_INFO) << "Received STUN ping "
316 << " id=" << rtc::hex_encode(msg->transaction_id())
317 << " from unknown address " << addr.ToSensitiveString();
318
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000319 // Check for role conflicts.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700320 if (!MaybeIceRoleConflict(addr, msg.get(), remote_username)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000321 LOG(LS_INFO) << "Received conflicting role from the peer.";
322 return;
323 }
324
325 SignalUnknownAddress(this, addr, proto, msg.get(), remote_username, false);
326 } else {
327 // NOTE(tschmelcher): STUN_BINDING_RESPONSE is benign. It occurs if we
328 // pruned a connection for this port while it had STUN requests in flight,
329 // because we then get back responses for them, which this code correctly
330 // does not handle.
331 if (msg->type() != STUN_BINDING_RESPONSE) {
332 LOG_J(LS_ERROR, this) << "Received unexpected STUN message type ("
333 << msg->type() << ") from unknown address ("
334 << addr.ToSensitiveString() << ")";
335 }
336 }
337}
338
339void Port::OnReadyToSend() {
340 AddressMap::iterator iter = connections_.begin();
341 for (; iter != connections_.end(); ++iter) {
342 iter->second->OnReadyToSend();
343 }
344}
345
346size_t Port::AddPrflxCandidate(const Candidate& local) {
347 candidates_.push_back(local);
348 return (candidates_.size() - 1);
349}
350
kwiberg6baec032016-03-15 11:09:39 -0700351bool Port::GetStunMessage(const char* data,
352 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000353 const rtc::SocketAddress& addr,
kwiberg3ec46792016-04-27 07:22:53 -0700354 std::unique_ptr<IceMessage>* out_msg,
kwiberg6baec032016-03-15 11:09:39 -0700355 std::string* out_username) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000356 // NOTE: This could clearly be optimized to avoid allocating any memory.
357 // However, at the data rates we'll be looking at on the client side,
358 // this probably isn't worth worrying about.
nisseede5da42017-01-12 05:15:36 -0800359 RTC_DCHECK(out_msg != NULL);
360 RTC_DCHECK(out_username != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000361 out_username->clear();
362
363 // Don't bother parsing the packet if we can tell it's not STUN.
364 // In ICE mode, all STUN packets will have a valid fingerprint.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700365 if (!StunMessage::ValidateFingerprint(data, size)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000366 return false;
367 }
368
369 // Parse the request message. If the packet is not a complete and correct
370 // STUN message, then ignore it.
kwiberg3ec46792016-04-27 07:22:53 -0700371 std::unique_ptr<IceMessage> stun_msg(new IceMessage());
jbauchf1f87202016-03-30 06:43:37 -0700372 rtc::ByteBufferReader buf(data, size);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000373 if (!stun_msg->Read(&buf) || (buf.Length() > 0)) {
374 return false;
375 }
376
377 if (stun_msg->type() == STUN_BINDING_REQUEST) {
378 // Check for the presence of USERNAME and MESSAGE-INTEGRITY (if ICE) first.
379 // If not present, fail with a 400 Bad Request.
380 if (!stun_msg->GetByteString(STUN_ATTR_USERNAME) ||
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700381 !stun_msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000382 LOG_J(LS_ERROR, this) << "Received STUN request without username/M-I "
383 << "from " << addr.ToSensitiveString();
384 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_BAD_REQUEST,
385 STUN_ERROR_REASON_BAD_REQUEST);
386 return true;
387 }
388
389 // If the username is bad or unknown, fail with a 401 Unauthorized.
390 std::string local_ufrag;
391 std::string remote_ufrag;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700392 if (!ParseStunUsername(stun_msg.get(), &local_ufrag, &remote_ufrag) ||
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000393 local_ufrag != username_fragment()) {
394 LOG_J(LS_ERROR, this) << "Received STUN request with bad local username "
395 << local_ufrag << " from "
396 << addr.ToSensitiveString();
397 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
398 STUN_ERROR_REASON_UNAUTHORIZED);
399 return true;
400 }
401
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000402 // If ICE, and the MESSAGE-INTEGRITY is bad, fail with a 401 Unauthorized
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700403 if (!stun_msg->ValidateMessageIntegrity(data, size, password_)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000404 LOG_J(LS_ERROR, this) << "Received STUN request with bad M-I "
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +0000405 << "from " << addr.ToSensitiveString()
406 << ", password_=" << password_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000407 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
408 STUN_ERROR_REASON_UNAUTHORIZED);
409 return true;
410 }
411 out_username->assign(remote_ufrag);
412 } else if ((stun_msg->type() == STUN_BINDING_RESPONSE) ||
413 (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE)) {
414 if (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE) {
415 if (const StunErrorCodeAttribute* error_code = stun_msg->GetErrorCode()) {
416 LOG_J(LS_ERROR, this) << "Received STUN binding error:"
417 << " class=" << error_code->eclass()
418 << " number=" << error_code->number()
419 << " reason='" << error_code->reason() << "'"
420 << " from " << addr.ToSensitiveString();
421 // Return message to allow error-specific processing
422 } else {
423 LOG_J(LS_ERROR, this) << "Received STUN binding error without a error "
424 << "code from " << addr.ToSensitiveString();
425 return true;
426 }
427 }
428 // NOTE: Username should not be used in verifying response messages.
429 out_username->clear();
430 } else if (stun_msg->type() == STUN_BINDING_INDICATION) {
431 LOG_J(LS_VERBOSE, this) << "Received STUN binding indication:"
432 << " from " << addr.ToSensitiveString();
433 out_username->clear();
434 // No stun attributes will be verified, if it's stun indication message.
435 // Returning from end of the this method.
436 } else {
437 LOG_J(LS_ERROR, this) << "Received STUN packet with invalid type ("
438 << stun_msg->type() << ") from "
439 << addr.ToSensitiveString();
440 return true;
441 }
442
443 // Return the STUN message found.
kwiberg6baec032016-03-15 11:09:39 -0700444 *out_msg = std::move(stun_msg);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000445 return true;
446}
447
448bool Port::IsCompatibleAddress(const rtc::SocketAddress& addr) {
449 int family = ip().family();
450 // We use single-stack sockets, so families must match.
451 if (addr.family() != family) {
452 return false;
453 }
454 // Link-local IPv6 ports can only connect to other link-local IPv6 ports.
Peter Thatcherb8b01432015-07-07 16:45:53 -0700455 if (family == AF_INET6 &&
456 (IPIsLinkLocal(ip()) != IPIsLinkLocal(addr.ipaddr()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000457 return false;
458 }
459 return true;
460}
461
462bool Port::ParseStunUsername(const StunMessage* stun_msg,
463 std::string* local_ufrag,
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700464 std::string* remote_ufrag) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000465 // The packet must include a username that either begins or ends with our
466 // fragment. It should begin with our fragment if it is a request and it
467 // should end with our fragment if it is a response.
468 local_ufrag->clear();
469 remote_ufrag->clear();
470 const StunByteStringAttribute* username_attr =
471 stun_msg->GetByteString(STUN_ATTR_USERNAME);
472 if (username_attr == NULL)
473 return false;
474
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700475 // RFRAG:LFRAG
476 const std::string username = username_attr->GetString();
477 size_t colon_pos = username.find(":");
478 if (colon_pos == std::string::npos) {
479 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000480 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000481
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700482 *local_ufrag = username.substr(0, colon_pos);
483 *remote_ufrag = username.substr(colon_pos + 1, username.size());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000484 return true;
485}
486
487bool Port::MaybeIceRoleConflict(
488 const rtc::SocketAddress& addr, IceMessage* stun_msg,
489 const std::string& remote_ufrag) {
490 // Validate ICE_CONTROLLING or ICE_CONTROLLED attributes.
491 bool ret = true;
492 IceRole remote_ice_role = ICEROLE_UNKNOWN;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200493 uint64_t remote_tiebreaker = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000494 const StunUInt64Attribute* stun_attr =
495 stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
496 if (stun_attr) {
497 remote_ice_role = ICEROLE_CONTROLLING;
498 remote_tiebreaker = stun_attr->value();
499 }
500
501 // If |remote_ufrag| is same as port local username fragment and
502 // tie breaker value received in the ping message matches port
503 // tiebreaker value this must be a loopback call.
504 // We will treat this as valid scenario.
505 if (remote_ice_role == ICEROLE_CONTROLLING &&
506 username_fragment() == remote_ufrag &&
507 remote_tiebreaker == IceTiebreaker()) {
508 return true;
509 }
510
511 stun_attr = stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
512 if (stun_attr) {
513 remote_ice_role = ICEROLE_CONTROLLED;
514 remote_tiebreaker = stun_attr->value();
515 }
516
517 switch (ice_role_) {
518 case ICEROLE_CONTROLLING:
519 if (ICEROLE_CONTROLLING == remote_ice_role) {
520 if (remote_tiebreaker >= tiebreaker_) {
521 SignalRoleConflict(this);
522 } else {
523 // Send Role Conflict (487) error response.
524 SendBindingErrorResponse(stun_msg, addr,
525 STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
526 ret = false;
527 }
528 }
529 break;
530 case ICEROLE_CONTROLLED:
531 if (ICEROLE_CONTROLLED == remote_ice_role) {
532 if (remote_tiebreaker < tiebreaker_) {
533 SignalRoleConflict(this);
534 } else {
535 // Send Role Conflict (487) error response.
536 SendBindingErrorResponse(stun_msg, addr,
537 STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
538 ret = false;
539 }
540 }
541 break;
542 default:
nissec80e7412017-01-11 05:56:46 -0800543 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000544 }
545 return ret;
546}
547
548void Port::CreateStunUsername(const std::string& remote_username,
549 std::string* stun_username_attr_str) const {
550 stun_username_attr_str->clear();
551 *stun_username_attr_str = remote_username;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700552 stun_username_attr_str->append(":");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000553 stun_username_attr_str->append(username_fragment());
554}
555
556void Port::SendBindingResponse(StunMessage* request,
557 const rtc::SocketAddress& addr) {
nisseede5da42017-01-12 05:15:36 -0800558 RTC_DCHECK(request->type() == STUN_BINDING_REQUEST);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000559
560 // Retrieve the username from the request.
561 const StunByteStringAttribute* username_attr =
562 request->GetByteString(STUN_ATTR_USERNAME);
nisseede5da42017-01-12 05:15:36 -0800563 RTC_DCHECK(username_attr != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000564 if (username_attr == NULL) {
565 // No valid username, skip the response.
566 return;
567 }
568
569 // Fill in the response message.
570 StunMessage response;
571 response.SetType(STUN_BINDING_RESPONSE);
572 response.SetTransactionID(request->transaction_id());
573 const StunUInt32Attribute* retransmit_attr =
574 request->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
575 if (retransmit_attr) {
576 // Inherit the incoming retransmit value in the response so the other side
577 // can see our view of lost pings.
578 response.AddAttribute(new StunUInt32Attribute(
579 STUN_ATTR_RETRANSMIT_COUNT, retransmit_attr->value()));
580
581 if (retransmit_attr->value() > CONNECTION_WRITE_CONNECT_FAILURES) {
582 LOG_J(LS_INFO, this)
583 << "Received a remote ping with high retransmit count: "
584 << retransmit_attr->value();
585 }
586 }
587
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700588 response.AddAttribute(
589 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, addr));
590 response.AddMessageIntegrity(password_);
591 response.AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000592
593 // Send the response message.
jbauchf1f87202016-03-30 06:43:37 -0700594 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000595 response.Write(&buf);
596 rtc::PacketOptions options(DefaultDscpValue());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700597 auto err = SendTo(buf.Data(), buf.Length(), addr, options, false);
598 if (err < 0) {
599 LOG_J(LS_ERROR, this)
600 << "Failed to send STUN ping response"
601 << ", to=" << addr.ToSensitiveString()
602 << ", err=" << err
603 << ", id=" << rtc::hex_encode(response.transaction_id());
604 } else {
605 // Log at LS_INFO if we send a stun ping response on an unwritable
606 // connection.
honghaiz9b5ee9c2015-11-11 13:19:17 -0800607 Connection* conn = GetConnection(addr);
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700608 rtc::LoggingSeverity sev = (conn && !conn->writable()) ?
609 rtc::LS_INFO : rtc::LS_VERBOSE;
610 LOG_JV(sev, this)
611 << "Sent STUN ping response"
612 << ", to=" << addr.ToSensitiveString()
613 << ", id=" << rtc::hex_encode(response.transaction_id());
zhihuang5ecf16c2016-06-01 17:09:15 -0700614
615 conn->stats_.sent_ping_responses++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000616 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000617}
618
619void Port::SendBindingErrorResponse(StunMessage* request,
620 const rtc::SocketAddress& addr,
621 int error_code, const std::string& reason) {
nisseede5da42017-01-12 05:15:36 -0800622 RTC_DCHECK(request->type() == STUN_BINDING_REQUEST);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000623
624 // Fill in the response message.
625 StunMessage response;
626 response.SetType(STUN_BINDING_ERROR_RESPONSE);
627 response.SetTransactionID(request->transaction_id());
628
629 // When doing GICE, we need to write out the error code incorrectly to
630 // maintain backwards compatiblility.
631 StunErrorCodeAttribute* error_attr = StunAttribute::CreateErrorCode();
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700632 error_attr->SetCode(error_code);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000633 error_attr->SetReason(reason);
634 response.AddAttribute(error_attr);
635
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700636 // Per Section 10.1.2, certain error cases don't get a MESSAGE-INTEGRITY,
637 // because we don't have enough information to determine the shared secret.
638 if (error_code != STUN_ERROR_BAD_REQUEST &&
639 error_code != STUN_ERROR_UNAUTHORIZED)
640 response.AddMessageIntegrity(password_);
641 response.AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000642
643 // Send the response message.
jbauchf1f87202016-03-30 06:43:37 -0700644 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000645 response.Write(&buf);
646 rtc::PacketOptions options(DefaultDscpValue());
647 SendTo(buf.Data(), buf.Length(), addr, options, false);
648 LOG_J(LS_INFO, this) << "Sending STUN binding error: reason=" << reason
649 << " to " << addr.ToSensitiveString();
650}
651
Honghai Zhanga74363c2016-07-28 18:06:15 -0700652void Port::KeepAliveUntilPruned() {
653 // If it is pruned, we won't bring it up again.
654 if (state_ == State::INIT) {
655 state_ = State::KEEP_ALIVE_UNTIL_PRUNED;
656 }
657}
658
659void Port::Prune() {
660 state_ = State::PRUNED;
661 thread_->Post(RTC_FROM_HERE, this, MSG_DESTROY_IF_DEAD);
662}
663
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000664void Port::OnMessage(rtc::Message *pmsg) {
nisseede5da42017-01-12 05:15:36 -0800665 RTC_DCHECK(pmsg->message_id == MSG_DESTROY_IF_DEAD);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700666 bool dead =
667 (state_ == State::INIT || state_ == State::PRUNED) &&
668 connections_.empty() &&
669 rtc::TimeMillis() - last_time_all_connections_removed_ >= timeout_delay_;
670 if (dead) {
honghaizd0b31432015-09-30 12:42:17 -0700671 Destroy();
672 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000673}
674
Honghai Zhang351d77b2016-05-20 15:08:29 -0700675void Port::OnNetworkTypeChanged(const rtc::Network* network) {
nisseede5da42017-01-12 05:15:36 -0800676 RTC_DCHECK(network == network_);
Honghai Zhang351d77b2016-05-20 15:08:29 -0700677
678 UpdateNetworkCost();
679}
680
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000681std::string Port::ToString() const {
682 std::stringstream ss;
honghaize3c6c822016-02-17 13:00:28 -0800683 ss << "Port[" << std::hex << this << std::dec << ":" << content_name_ << ":"
684 << component_ << ":" << generation_ << ":" << type_ << ":"
685 << network_->ToString() << "]";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000686 return ss.str();
687}
688
Honghai Zhang351d77b2016-05-20 15:08:29 -0700689// TODO(honghaiz): Make the network cost configurable from user setting.
690void Port::UpdateNetworkCost() {
691 uint16_t new_cost = network_->GetCost();
692 if (network_cost_ == new_cost) {
693 return;
694 }
695 LOG(LS_INFO) << "Network cost changed from " << network_cost_
696 << " to " << new_cost
697 << ". Number of candidates created: " << candidates_.size()
698 << ". Number of connections created: " << connections_.size();
699 network_cost_ = new_cost;
700 for (cricket::Candidate& candidate : candidates_) {
701 candidate.set_network_cost(network_cost_);
702 }
703 // Network cost change will affect the connection selection criteria.
704 // Signal the connection state change on each connection to force a
705 // re-sort in P2PTransportChannel.
706 for (auto kv : connections_) {
707 Connection* conn = kv.second;
708 conn->SignalStateChange(conn);
709 }
710}
711
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000712void Port::EnablePortPackets() {
713 enable_port_packets_ = true;
714}
715
716void Port::OnConnectionDestroyed(Connection* conn) {
717 AddressMap::iterator iter =
718 connections_.find(conn->remote_candidate().address());
nisseede5da42017-01-12 05:15:36 -0800719 RTC_DCHECK(iter != connections_.end());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000720 connections_.erase(iter);
honghaiz36f50e82016-06-01 15:57:03 -0700721 HandleConnectionDestroyed(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000722
Honghai Zhanga74363c2016-07-28 18:06:15 -0700723 // Ports time out after all connections fail if it is not marked as
724 // "keep alive until pruned."
honghaizd0b31432015-09-30 12:42:17 -0700725 // Note: If a new connection is added after this message is posted, but it
726 // fails and is removed before kPortTimeoutDelay, then this message will
Honghai Zhangb5db1ec2016-07-28 13:23:05 -0700727 // not cause the Port to be destroyed.
Honghai Zhanga74363c2016-07-28 18:06:15 -0700728 if (connections_.empty()) {
Honghai Zhangb5db1ec2016-07-28 13:23:05 -0700729 last_time_all_connections_removed_ = rtc::TimeMillis();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700730 thread_->PostDelayed(RTC_FROM_HERE, timeout_delay_, this,
731 MSG_DESTROY_IF_DEAD);
honghaizd0b31432015-09-30 12:42:17 -0700732 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000733}
734
735void Port::Destroy() {
nisseede5da42017-01-12 05:15:36 -0800736 RTC_DCHECK(connections_.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000737 LOG_J(LS_INFO, this) << "Port deleted";
738 SignalDestroyed(this);
739 delete this;
740}
741
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000742const std::string Port::username_fragment() const {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700743 return ice_username_fragment_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000744}
745
746// A ConnectionRequest is a simple STUN ping used to determine writability.
747class ConnectionRequest : public StunRequest {
748 public:
749 explicit ConnectionRequest(Connection* connection)
750 : StunRequest(new IceMessage()),
751 connection_(connection) {
752 }
753
754 virtual ~ConnectionRequest() {
755 }
756
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700757 void Prepare(StunMessage* request) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000758 request->SetType(STUN_BINDING_REQUEST);
759 std::string username;
760 connection_->port()->CreateStunUsername(
761 connection_->remote_candidate().username(), &username);
762 request->AddAttribute(
763 new StunByteStringAttribute(STUN_ATTR_USERNAME, username));
764
765 // connection_ already holds this ping, so subtract one from count.
766 if (connection_->port()->send_retransmit_count_attribute()) {
767 request->AddAttribute(new StunUInt32Attribute(
768 STUN_ATTR_RETRANSMIT_COUNT,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200769 static_cast<uint32_t>(connection_->pings_since_last_response_.size() -
770 1)));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000771 }
honghaiza0c44ea2016-03-23 16:07:48 -0700772 uint32_t network_info = connection_->port()->Network()->id();
773 network_info = (network_info << 16) | connection_->port()->network_cost();
774 request->AddAttribute(
775 new StunUInt32Attribute(STUN_ATTR_NETWORK_INFO, network_info));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000776
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700777 // Adding ICE_CONTROLLED or ICE_CONTROLLING attribute based on the role.
778 if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLING) {
779 request->AddAttribute(new StunUInt64Attribute(
780 STUN_ATTR_ICE_CONTROLLING, connection_->port()->IceTiebreaker()));
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700781 // We should have either USE_CANDIDATE attribute or ICE_NOMINATION
782 // attribute but not both. That was enforced in p2ptransportchannel.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700783 if (connection_->use_candidate_attr()) {
784 request->AddAttribute(new StunByteStringAttribute(
785 STUN_ATTR_USE_CANDIDATE));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000786 }
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700787 if (connection_->nomination() &&
788 connection_->nomination() != connection_->acked_nomination()) {
789 request->AddAttribute(new StunUInt32Attribute(
790 STUN_ATTR_NOMINATION, connection_->nomination()));
791 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700792 } else if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLED) {
793 request->AddAttribute(new StunUInt64Attribute(
794 STUN_ATTR_ICE_CONTROLLED, connection_->port()->IceTiebreaker()));
795 } else {
nissec80e7412017-01-11 05:56:46 -0800796 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000797 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700798
799 // Adding PRIORITY Attribute.
800 // Changing the type preference to Peer Reflexive and local preference
801 // and component id information is unchanged from the original priority.
802 // priority = (2^24)*(type preference) +
803 // (2^8)*(local preference) +
804 // (2^0)*(256 - component ID)
Taylor Brandstetter62351c92016-08-11 16:05:07 -0700805 uint32_t type_preference =
806 (connection_->local_candidate().protocol() == TCP_PROTOCOL_NAME)
807 ? ICE_TYPE_PREFERENCE_PRFLX_TCP
808 : ICE_TYPE_PREFERENCE_PRFLX;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200809 uint32_t prflx_priority =
Taylor Brandstetter62351c92016-08-11 16:05:07 -0700810 type_preference << 24 |
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700811 (connection_->local_candidate().priority() & 0x00FFFFFF);
812 request->AddAttribute(
813 new StunUInt32Attribute(STUN_ATTR_PRIORITY, prflx_priority));
814
815 // Adding Message Integrity attribute.
816 request->AddMessageIntegrity(connection_->remote_candidate().password());
817 // Adding Fingerprint.
818 request->AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000819 }
820
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700821 void OnResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000822 connection_->OnConnectionRequestResponse(this, response);
823 }
824
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700825 void OnErrorResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000826 connection_->OnConnectionRequestErrorResponse(this, response);
827 }
828
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700829 void OnTimeout() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000830 connection_->OnConnectionRequestTimeout(this);
831 }
832
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700833 void OnSent() override {
834 connection_->OnConnectionRequestSent(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000835 // Each request is sent only once. After a single delay , the request will
836 // time out.
837 timeout_ = true;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700838 }
839
840 int resend_delay() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000841 return CONNECTION_RESPONSE_TIMEOUT;
842 }
843
844 private:
845 Connection* connection_;
846};
847
848//
849// Connection
850//
851
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000852Connection::Connection(Port* port,
853 size_t index,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000854 const Candidate& remote_candidate)
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000855 : port_(port),
856 local_candidate_index_(index),
857 remote_candidate_(remote_candidate),
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700858 recv_rate_tracker_(100, 10u),
859 send_rate_tracker_(100, 10u),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000860 write_state_(STATE_WRITE_INIT),
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700861 receiving_(false),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000862 connected_(true),
863 pruned_(false),
864 use_candidate_attr_(false),
865 remote_ice_mode_(ICEMODE_FULL),
866 requests_(port->thread()),
867 rtt_(DEFAULT_RTT),
868 last_ping_sent_(0),
869 last_ping_received_(0),
870 last_data_received_(0),
871 last_ping_response_received_(0),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000872 reported_(false),
hbos06495bc2017-01-02 08:08:18 -0800873 state_(IceCandidatePairState::WAITING),
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700874 receiving_timeout_(WEAK_CONNECTION_RECEIVE_TIMEOUT),
nisse1bffc1d2016-05-02 08:18:55 -0700875 time_created_ms_(rtc::TimeMillis()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000876 // All of our connections start in WAITING state.
877 // TODO(mallinath) - Start connections from STATE_FROZEN.
878 // Wire up to send stun packets
879 requests_.SignalSendPacket.connect(this, &Connection::OnSendStunPacket);
880 LOG_J(LS_INFO, this) << "Connection created";
881}
882
883Connection::~Connection() {
884}
885
886const Candidate& Connection::local_candidate() const {
nisseede5da42017-01-12 05:15:36 -0800887 RTC_DCHECK(local_candidate_index_ < port_->Candidates().size());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000888 return port_->Candidates()[local_candidate_index_];
889}
890
Honghai Zhangcc411c02016-03-29 17:27:21 -0700891const Candidate& Connection::remote_candidate() const {
892 return remote_candidate_;
893}
894
Peter Boström0c4e06b2015-10-07 12:23:21 +0200895uint64_t Connection::priority() const {
896 uint64_t priority = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000897 // RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs
898 // Let G be the priority for the candidate provided by the controlling
899 // agent. Let D be the priority for the candidate provided by the
900 // controlled agent.
901 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
902 IceRole role = port_->GetIceRole();
903 if (role != ICEROLE_UNKNOWN) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200904 uint32_t g = 0;
905 uint32_t d = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000906 if (role == ICEROLE_CONTROLLING) {
907 g = local_candidate().priority();
908 d = remote_candidate_.priority();
909 } else {
910 g = remote_candidate_.priority();
911 d = local_candidate().priority();
912 }
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000913 priority = std::min(g, d);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000914 priority = priority << 32;
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000915 priority += 2 * std::max(g, d) + (g > d ? 1 : 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000916 }
917 return priority;
918}
919
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000920void Connection::set_write_state(WriteState value) {
921 WriteState old_value = write_state_;
922 write_state_ = value;
923 if (value != old_value) {
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +0000924 LOG_J(LS_VERBOSE, this) << "set_write_state from: " << old_value << " to "
925 << value;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000926 SignalStateChange(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000927 }
928}
929
honghaiz9ad0db52016-07-14 19:30:28 -0700930void Connection::UpdateReceiving(int64_t now) {
honghaize58d73d2016-10-24 16:38:26 -0700931 bool receiving =
932 last_received() > 0 && now <= last_received() + receiving_timeout_;
honghaiz9ad0db52016-07-14 19:30:28 -0700933 if (receiving_ == receiving) {
934 return;
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700935 }
honghaiz9ad0db52016-07-14 19:30:28 -0700936 LOG_J(LS_VERBOSE, this) << "set_receiving to " << receiving;
937 receiving_ = receiving;
938 receiving_unchanged_since_ = now;
939 SignalStateChange(this);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700940}
941
hbos06495bc2017-01-02 08:08:18 -0800942void Connection::set_state(IceCandidatePairState state) {
943 IceCandidatePairState old_state = state_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000944 state_ = state;
945 if (state != old_state) {
946 LOG_J(LS_VERBOSE, this) << "set_state";
947 }
948}
949
950void Connection::set_connected(bool value) {
951 bool old_value = connected_;
952 connected_ = value;
953 if (value != old_value) {
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700954 LOG_J(LS_VERBOSE, this) << "set_connected from: " << old_value << " to "
955 << value;
Taylor Brandstetterb825aee2016-06-29 13:07:16 -0700956 SignalStateChange(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000957 }
958}
959
960void Connection::set_use_candidate_attr(bool enable) {
961 use_candidate_attr_ = enable;
962}
963
964void Connection::OnSendStunPacket(const void* data, size_t size,
965 StunRequest* req) {
966 rtc::PacketOptions options(port_->DefaultDscpValue());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700967 auto err = port_->SendTo(
968 data, size, remote_candidate_.address(), options, false);
969 if (err < 0) {
970 LOG_J(LS_WARNING, this) << "Failed to send STUN ping "
971 << " err=" << err
972 << " id=" << rtc::hex_encode(req->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000973 }
974}
975
976void Connection::OnReadPacket(
977 const char* data, size_t size, const rtc::PacketTime& packet_time) {
kwiberg3ec46792016-04-27 07:22:53 -0700978 std::unique_ptr<IceMessage> msg;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000979 std::string remote_ufrag;
980 const rtc::SocketAddress& addr(remote_candidate_.address());
kwiberg6baec032016-03-15 11:09:39 -0700981 if (!port_->GetStunMessage(data, size, addr, &msg, &remote_ufrag)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000982 // The packet did not parse as a valid STUN message
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700983 // This is a data packet, pass it along.
nisse1bffc1d2016-05-02 08:18:55 -0700984 last_data_received_ = rtc::TimeMillis();
honghaiz9ad0db52016-07-14 19:30:28 -0700985 UpdateReceiving(last_data_received_);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700986 recv_rate_tracker_.AddSamples(size);
987 SignalReadPacket(this, data, size, packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000988
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700989 // If timed out sending writability checks, start up again
990 if (!pruned_ && (write_state_ == STATE_WRITE_TIMEOUT)) {
991 LOG(LS_WARNING) << "Received a data packet on a timed-out Connection. "
992 << "Resetting state to STATE_WRITE_INIT.";
993 set_write_state(STATE_WRITE_INIT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000994 }
995 } else if (!msg) {
996 // The packet was STUN, but failed a check and was handled internally.
997 } else {
998 // The packet is STUN and passed the Port checks.
999 // Perform our own checks to ensure this packet is valid.
honghaizd0b31432015-09-30 12:42:17 -07001000 // If this is a STUN request, then update the receiving bit and respond.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001001 // If this is a STUN response, then update the writable bit.
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001002 // Log at LS_INFO if we receive a ping on an unwritable connection.
1003 rtc::LoggingSeverity sev = (!writable() ? rtc::LS_INFO : rtc::LS_VERBOSE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001004 switch (msg->type()) {
1005 case STUN_BINDING_REQUEST:
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001006 LOG_JV(sev, this) << "Received STUN ping"
1007 << ", id=" << rtc::hex_encode(msg->transaction_id());
1008
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001009 if (remote_ufrag == remote_candidate_.username()) {
honghaiz9b5ee9c2015-11-11 13:19:17 -08001010 HandleBindingRequest(msg.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001011 } else {
1012 // The packet had the right local username, but the remote username
1013 // was not the right one for the remote address.
1014 LOG_J(LS_ERROR, this)
1015 << "Received STUN request with bad remote username "
1016 << remote_ufrag;
1017 port_->SendBindingErrorResponse(msg.get(), addr,
1018 STUN_ERROR_UNAUTHORIZED,
1019 STUN_ERROR_REASON_UNAUTHORIZED);
1020
1021 }
1022 break;
1023
1024 // Response from remote peer. Does it match request sent?
1025 // This doesn't just check, it makes callbacks if transaction
1026 // id's match.
1027 case STUN_BINDING_RESPONSE:
1028 case STUN_BINDING_ERROR_RESPONSE:
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001029 if (msg->ValidateMessageIntegrity(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001030 data, size, remote_candidate().password())) {
1031 requests_.CheckResponse(msg.get());
1032 }
1033 // Otherwise silently discard the response message.
1034 break;
1035
honghaizd0b31432015-09-30 12:42:17 -07001036 // Remote end point sent an STUN indication instead of regular binding
1037 // request. In this case |last_ping_received_| will be updated but no
1038 // response will be sent.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001039 case STUN_BINDING_INDICATION:
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001040 ReceivedPing();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001041 break;
1042
1043 default:
nissec80e7412017-01-11 05:56:46 -08001044 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001045 break;
1046 }
1047 }
1048}
1049
honghaiz9b5ee9c2015-11-11 13:19:17 -08001050void Connection::HandleBindingRequest(IceMessage* msg) {
1051 // This connection should now be receiving.
1052 ReceivedPing();
1053
1054 const rtc::SocketAddress& remote_addr = remote_candidate_.address();
1055 const std::string& remote_ufrag = remote_candidate_.username();
1056 // Check for role conflicts.
1057 if (!port_->MaybeIceRoleConflict(remote_addr, msg, remote_ufrag)) {
1058 // Received conflicting role from the peer.
1059 LOG(LS_INFO) << "Received conflicting role from the peer.";
1060 return;
1061 }
1062
zhihuang5ecf16c2016-06-01 17:09:15 -07001063 stats_.recv_ping_requests++;
1064
honghaiz9b5ee9c2015-11-11 13:19:17 -08001065 // This is a validated stun request from remote peer.
1066 port_->SendBindingResponse(msg, remote_addr);
1067
1068 // If it timed out on writing check, start up again
1069 if (!pruned_ && write_state_ == STATE_WRITE_TIMEOUT) {
1070 set_write_state(STATE_WRITE_INIT);
1071 }
1072
1073 if (port_->GetIceRole() == ICEROLE_CONTROLLED) {
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001074 const StunUInt32Attribute* nomination_attr =
1075 msg->GetUInt32(STUN_ATTR_NOMINATION);
1076 uint32_t nomination = 0;
1077 if (nomination_attr) {
1078 nomination = nomination_attr->value();
1079 if (nomination == 0) {
1080 LOG(LS_ERROR) << "Invalid nomination: " << nomination;
1081 }
1082 } else {
1083 const StunByteStringAttribute* use_candidate_attr =
1084 msg->GetByteString(STUN_ATTR_USE_CANDIDATE);
1085 if (use_candidate_attr) {
1086 nomination = 1;
1087 }
1088 }
1089 // We don't un-nominate a connection, so we only keep a larger nomination.
1090 if (nomination > remote_nomination_) {
1091 set_remote_nomination(nomination);
honghaiz9b5ee9c2015-11-11 13:19:17 -08001092 SignalNominated(this);
1093 }
1094 }
Honghai Zhang351d77b2016-05-20 15:08:29 -07001095 // Set the remote cost if the network_info attribute is available.
1096 // Note: If packets are re-ordered, we may get incorrect network cost
1097 // temporarily, but it should get the correct value shortly after that.
1098 const StunUInt32Attribute* network_attr =
1099 msg->GetUInt32(STUN_ATTR_NETWORK_INFO);
1100 if (network_attr) {
1101 uint32_t network_info = network_attr->value();
1102 uint16_t network_cost = static_cast<uint16_t>(network_info);
1103 if (network_cost != remote_candidate_.network_cost()) {
1104 remote_candidate_.set_network_cost(network_cost);
1105 // Network cost change will affect the connection ranking, so signal
1106 // state change to force a re-sort in P2PTransportChannel.
1107 SignalStateChange(this);
1108 }
1109 }
honghaiz9b5ee9c2015-11-11 13:19:17 -08001110}
1111
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001112void Connection::OnReadyToSend() {
deadbeefdd7fb432016-09-30 15:16:48 -07001113 SignalReadyToSend(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001114}
1115
1116void Connection::Prune() {
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001117 if (!pruned_ || active()) {
Honghai Zhang1590c392016-05-24 13:15:02 -07001118 LOG_J(LS_INFO, this) << "Connection pruned";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001119 pruned_ = true;
1120 requests_.Clear();
1121 set_write_state(STATE_WRITE_TIMEOUT);
1122 }
1123}
1124
1125void Connection::Destroy() {
1126 LOG_J(LS_VERBOSE, this) << "Connection destroyed";
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001127 port_->thread()->Post(RTC_FROM_HERE, this, MSG_DELETE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001128}
1129
deadbeef376e1232015-11-25 09:00:08 -08001130void Connection::FailAndDestroy() {
hbos06495bc2017-01-02 08:08:18 -08001131 set_state(IceCandidatePairState::FAILED);
deadbeef376e1232015-11-25 09:00:08 -08001132 Destroy();
1133}
1134
honghaiz079a7a12016-06-22 16:26:29 -07001135void Connection::FailAndPrune() {
hbos06495bc2017-01-02 08:08:18 -08001136 set_state(IceCandidatePairState::FAILED);
honghaiz079a7a12016-06-22 16:26:29 -07001137 Prune();
1138}
1139
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001140void Connection::PrintPingsSinceLastResponse(std::string* s, size_t max) {
1141 std::ostringstream oss;
1142 oss << std::boolalpha;
1143 if (pings_since_last_response_.size() > max) {
1144 for (size_t i = 0; i < max; i++) {
1145 const SentPing& ping = pings_since_last_response_[i];
1146 oss << rtc::hex_encode(ping.id) << " ";
1147 }
1148 oss << "... " << (pings_since_last_response_.size() - max) << " more";
1149 } else {
1150 for (const SentPing& ping : pings_since_last_response_) {
1151 oss << rtc::hex_encode(ping.id) << " ";
1152 }
1153 }
1154 *s = oss.str();
1155}
1156
honghaiz34b11eb2016-03-16 08:55:44 -07001157void Connection::UpdateState(int64_t now) {
1158 int rtt = ConservativeRTTEstimate(rtt_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001159
Peter Thatcherb2d26232015-05-15 11:25:14 -07001160 if (LOG_CHECK_LEVEL(LS_VERBOSE)) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001161 std::string pings;
1162 PrintPingsSinceLastResponse(&pings, 5);
1163 LOG_J(LS_VERBOSE, this) << "UpdateState()"
1164 << ", ms since last received response="
1165 << now - last_ping_response_received_
1166 << ", ms since last received data="
1167 << now - last_data_received_
1168 << ", rtt=" << rtt
1169 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001170 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001171
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001172 // Check the writable state. (The order of these checks is important.)
1173 //
1174 // Before becoming unwritable, we allow for a fixed number of pings to fail
1175 // (i.e., receive no response). We also have to give the response time to
1176 // get back, so we include a conservative estimate of this.
1177 //
1178 // Before timing out writability, we give a fixed amount of time. This is to
1179 // allow for changes in network conditions.
1180
1181 if ((write_state_ == STATE_WRITABLE) &&
1182 TooManyFailures(pings_since_last_response_,
1183 CONNECTION_WRITE_CONNECT_FAILURES,
1184 rtt,
1185 now) &&
1186 TooLongWithoutResponse(pings_since_last_response_,
1187 CONNECTION_WRITE_CONNECT_TIMEOUT,
1188 now)) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001189 uint32_t max_pings = CONNECTION_WRITE_CONNECT_FAILURES;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001190 LOG_J(LS_INFO, this) << "Unwritable after " << max_pings
1191 << " ping failures and "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001192 << now - pings_since_last_response_[0].sent_time
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001193 << " ms without a response,"
1194 << " ms since last received ping="
1195 << now - last_ping_received_
1196 << " ms since last received data="
1197 << now - last_data_received_
1198 << " rtt=" << rtt;
1199 set_write_state(STATE_WRITE_UNRELIABLE);
1200 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001201 if ((write_state_ == STATE_WRITE_UNRELIABLE ||
1202 write_state_ == STATE_WRITE_INIT) &&
1203 TooLongWithoutResponse(pings_since_last_response_,
1204 CONNECTION_WRITE_TIMEOUT,
1205 now)) {
1206 LOG_J(LS_INFO, this) << "Timed out after "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001207 << now - pings_since_last_response_[0].sent_time
1208 << " ms without a response"
1209 << ", rtt=" << rtt;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001210 set_write_state(STATE_WRITE_TIMEOUT);
1211 }
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001212
honghaiz9ad0db52016-07-14 19:30:28 -07001213 // Update the receiving state.
1214 UpdateReceiving(now);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001215 if (dead(now)) {
1216 Destroy();
1217 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001218}
1219
honghaiz34b11eb2016-03-16 08:55:44 -07001220void Connection::Ping(int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001221 last_ping_sent_ = now;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001222 ConnectionRequest *req = new ConnectionRequest(this);
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001223 pings_since_last_response_.push_back(SentPing(req->id(), now, nomination_));
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001224 LOG_J(LS_VERBOSE, this) << "Sending STUN ping "
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001225 << ", id=" << rtc::hex_encode(req->id())
1226 << ", nomination=" << nomination_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001227 requests_.Send(req);
hbos06495bc2017-01-02 08:08:18 -08001228 state_ = IceCandidatePairState::IN_PROGRESS;
honghaiz524ecc22016-05-25 12:48:31 -07001229 num_pings_sent_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001230}
1231
1232void Connection::ReceivedPing() {
nisse1bffc1d2016-05-02 08:18:55 -07001233 last_ping_received_ = rtc::TimeMillis();
honghaiz9ad0db52016-07-14 19:30:28 -07001234 UpdateReceiving(last_ping_received_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001235}
1236
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001237void Connection::ReceivedPingResponse(int rtt, const std::string& request_id) {
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001238 // We've already validated that this is a STUN binding response with
1239 // the correct local and remote username for this connection.
1240 // So if we're not already, become writable. We may be bringing a pruned
1241 // connection back to life, but if we don't really want it, we can always
1242 // prune it again.
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001243 auto iter = std::find_if(
1244 pings_since_last_response_.begin(), pings_since_last_response_.end(),
1245 [request_id](const SentPing& ping) { return ping.id == request_id; });
1246 if (iter != pings_since_last_response_.end() &&
1247 iter->nomination > acked_nomination_) {
1248 acked_nomination_ = iter->nomination;
1249 }
1250
1251 pings_since_last_response_.clear();
honghaiz9ad0db52016-07-14 19:30:28 -07001252 last_ping_response_received_ = rtc::TimeMillis();
1253 UpdateReceiving(last_ping_response_received_);
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001254 set_write_state(STATE_WRITABLE);
hbos06495bc2017-01-02 08:08:18 -08001255 set_state(IceCandidatePairState::SUCCEEDED);
skvladd0309122017-02-02 17:18:37 -08001256 if (rtt_samples_ > 0) {
1257 rtt_ = (RTT_RATIO * rtt_ + rtt) / (RTT_RATIO + 1);
1258 } else {
1259 rtt_ = rtt;
1260 }
zhihuang435264a2016-06-21 11:28:38 -07001261 rtt_samples_++;
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001262}
1263
honghaiz34b11eb2016-03-16 08:55:44 -07001264bool Connection::dead(int64_t now) const {
honghaiz37389b42016-01-04 21:57:33 -08001265 if (last_received() > 0) {
1266 // If it has ever received anything, we keep it alive until it hasn't
1267 // received anything for DEAD_CONNECTION_RECEIVE_TIMEOUT. This covers the
1268 // normal case of a successfully used connection that stops working. This
1269 // also allows a remote peer to continue pinging over a locally inactive
1270 // (pruned) connection.
1271 return (now > (last_received() + DEAD_CONNECTION_RECEIVE_TIMEOUT));
1272 }
1273
1274 if (active()) {
1275 // If it has never received anything, keep it alive as long as it is
1276 // actively pinging and not pruned. Otherwise, the connection might be
1277 // deleted before it has a chance to ping. This is the normal case for a
1278 // new connection that is pinging but hasn't received anything yet.
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001279 return false;
1280 }
1281
honghaiz37389b42016-01-04 21:57:33 -08001282 // If it has never received anything and is not actively pinging (pruned), we
1283 // keep it around for at least MIN_CONNECTION_LIFETIME to prevent connections
1284 // from being pruned too quickly during a network change event when two
1285 // networks would be up simultaneously but only for a brief period.
1286 return now > (time_created_ms_ + MIN_CONNECTION_LIFETIME);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001287}
1288
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001289bool Connection::stable(int64_t now) const {
zhihuang435264a2016-06-21 11:28:38 -07001290 // A connection is stable if it's RTT has converged and it isn't missing any
1291 // responses. We should send pings at a higher rate until the RTT converges
1292 // and whenever a ping response is missing (so that we can detect
1293 // unwritability faster)
1294 return rtt_converged() && !missing_responses(now);
1295}
1296
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +00001297std::string Connection::ToDebugId() const {
1298 std::stringstream ss;
1299 ss << std::hex << this;
1300 return ss.str();
1301}
1302
honghaize1a0c942016-02-16 14:54:56 -08001303uint32_t Connection::ComputeNetworkCost() const {
1304 // TODO(honghaiz): Will add rtt as part of the network cost.
Honghai Zhang351d77b2016-05-20 15:08:29 -07001305 return port()->network_cost() + remote_candidate_.network_cost();
honghaize1a0c942016-02-16 14:54:56 -08001306}
1307
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001308std::string Connection::ToString() const {
1309 const char CONNECT_STATE_ABBREV[2] = {
1310 '-', // not connected (false)
1311 'C', // connected (true)
1312 };
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001313 const char RECEIVE_STATE_ABBREV[2] = {
1314 '-', // not receiving (false)
1315 'R', // receiving (true)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001316 };
1317 const char WRITE_STATE_ABBREV[4] = {
1318 'W', // STATE_WRITABLE
1319 'w', // STATE_WRITE_UNRELIABLE
1320 '-', // STATE_WRITE_INIT
1321 'x', // STATE_WRITE_TIMEOUT
1322 };
1323 const std::string ICESTATE[4] = {
1324 "W", // STATE_WAITING
1325 "I", // STATE_INPROGRESS
1326 "S", // STATE_SUCCEEDED
1327 "F" // STATE_FAILED
1328 };
1329 const Candidate& local = local_candidate();
1330 const Candidate& remote = remote_candidate();
1331 std::stringstream ss;
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001332 ss << "Conn[" << ToDebugId() << ":" << port_->content_name() << ":"
1333 << local.id() << ":" << local.component() << ":" << local.generation()
1334 << ":" << local.type() << ":" << local.protocol() << ":"
1335 << local.address().ToSensitiveString() << "->" << remote.id() << ":"
1336 << remote.component() << ":" << remote.priority() << ":" << remote.type()
1337 << ":" << remote.protocol() << ":" << remote.address().ToSensitiveString()
1338 << "|" << CONNECT_STATE_ABBREV[connected()]
1339 << RECEIVE_STATE_ABBREV[receiving()] << WRITE_STATE_ABBREV[write_state()]
hbos06495bc2017-01-02 08:08:18 -08001340 << ICESTATE[static_cast<int>(state())] << "|" << remote_nomination() << "|"
1341 << nomination() << "|" << priority() << "|";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001342 if (rtt_ < DEFAULT_RTT) {
1343 ss << rtt_ << "]";
1344 } else {
1345 ss << "-]";
1346 }
1347 return ss.str();
1348}
1349
1350std::string Connection::ToSensitiveString() const {
1351 return ToString();
1352}
1353
1354void Connection::OnConnectionRequestResponse(ConnectionRequest* request,
1355 StunMessage* response) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001356 // Log at LS_INFO if we receive a ping response on an unwritable
1357 // connection.
1358 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1359
honghaiz34b11eb2016-03-16 08:55:44 -07001360 int rtt = request->Elapsed();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001361
Peter Thatcherb2d26232015-05-15 11:25:14 -07001362 if (LOG_CHECK_LEVEL_V(sev)) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001363 std::string pings;
1364 PrintPingsSinceLastResponse(&pings, 5);
1365 LOG_JV(sev, this) << "Received STUN ping response"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001366 << ", id=" << rtc::hex_encode(request->id())
1367 << ", code=0" // Makes logging easier to parse.
1368 << ", rtt=" << rtt
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001369 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001370 }
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001371 ReceivedPingResponse(rtt, request->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001372
zhihuang5ecf16c2016-06-01 17:09:15 -07001373 stats_.recv_ping_responses++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001374
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001375 MaybeUpdateLocalCandidate(request, response);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001376}
1377
1378void Connection::OnConnectionRequestErrorResponse(ConnectionRequest* request,
1379 StunMessage* response) {
1380 const StunErrorCodeAttribute* error_attr = response->GetErrorCode();
1381 int error_code = STUN_ERROR_GLOBAL_FAILURE;
1382 if (error_attr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001383 error_code = error_attr->code();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001384 }
1385
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001386 LOG_J(LS_INFO, this) << "Received STUN error response"
1387 << " id=" << rtc::hex_encode(request->id())
1388 << " code=" << error_code
1389 << " rtt=" << request->Elapsed();
1390
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001391 if (error_code == STUN_ERROR_UNKNOWN_ATTRIBUTE ||
1392 error_code == STUN_ERROR_SERVER_ERROR ||
1393 error_code == STUN_ERROR_UNAUTHORIZED) {
1394 // Recoverable error, retry
1395 } else if (error_code == STUN_ERROR_STALE_CREDENTIALS) {
1396 // Race failure, retry
1397 } else if (error_code == STUN_ERROR_ROLE_CONFLICT) {
1398 HandleRoleConflictFromPeer();
1399 } else {
1400 // This is not a valid connection.
1401 LOG_J(LS_ERROR, this) << "Received STUN error response, code="
1402 << error_code << "; killing connection";
deadbeef376e1232015-11-25 09:00:08 -08001403 FailAndDestroy();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001404 }
1405}
1406
1407void Connection::OnConnectionRequestTimeout(ConnectionRequest* request) {
1408 // Log at LS_INFO if we miss a ping on a writable connection.
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001409 rtc::LoggingSeverity sev = writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1410 LOG_JV(sev, this) << "Timing-out STUN ping "
1411 << rtc::hex_encode(request->id())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001412 << " after " << request->Elapsed() << " ms";
1413}
1414
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001415void Connection::OnConnectionRequestSent(ConnectionRequest* request) {
1416 // Log at LS_INFO if we send a ping on an unwritable connection.
1417 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1418 LOG_JV(sev, this) << "Sent STUN ping"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001419 << ", id=" << rtc::hex_encode(request->id())
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001420 << ", use_candidate=" << use_candidate_attr()
1421 << ", nomination=" << nomination();
zhihuang5ecf16c2016-06-01 17:09:15 -07001422 stats_.sent_ping_requests_total++;
1423 if (stats_.recv_ping_responses == 0) {
1424 stats_.sent_ping_requests_before_first_response++;
1425 }
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001426}
1427
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001428void Connection::HandleRoleConflictFromPeer() {
1429 port_->SignalRoleConflict(port_);
1430}
1431
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001432void Connection::MaybeSetRemoteIceParametersAndGeneration(
1433 const IceParameters& ice_params,
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001434 int generation) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001435 if (remote_candidate_.username() == ice_params.ufrag &&
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001436 remote_candidate_.password().empty()) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001437 remote_candidate_.set_password(ice_params.pwd);
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001438 }
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001439 // TODO(deadbeef): A value of '0' for the generation is used for both
1440 // generation 0 and "generation unknown". It should be changed to an
1441 // rtc::Optional to fix this.
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001442 if (remote_candidate_.username() == ice_params.ufrag &&
1443 remote_candidate_.password() == ice_params.pwd &&
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001444 remote_candidate_.generation() == 0) {
1445 remote_candidate_.set_generation(generation);
1446 }
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001447}
1448
1449void Connection::MaybeUpdatePeerReflexiveCandidate(
1450 const Candidate& new_candidate) {
1451 if (remote_candidate_.type() == PRFLX_PORT_TYPE &&
1452 new_candidate.type() != PRFLX_PORT_TYPE &&
1453 remote_candidate_.protocol() == new_candidate.protocol() &&
1454 remote_candidate_.address() == new_candidate.address() &&
1455 remote_candidate_.username() == new_candidate.username() &&
1456 remote_candidate_.password() == new_candidate.password() &&
1457 remote_candidate_.generation() == new_candidate.generation()) {
1458 remote_candidate_ = new_candidate;
1459 }
1460}
1461
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001462void Connection::OnMessage(rtc::Message *pmsg) {
nisseede5da42017-01-12 05:15:36 -08001463 RTC_DCHECK(pmsg->message_id == MSG_DELETE);
honghaiz18f9da02016-06-01 23:53:01 -07001464 LOG(LS_INFO) << "Connection deleted with number of pings sent: "
1465 << num_pings_sent_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001466 SignalDestroyed(this);
1467 delete this;
1468}
1469
honghaiz34b11eb2016-03-16 08:55:44 -07001470int64_t Connection::last_received() const {
Peter Thatcher54360512015-07-08 11:08:35 -07001471 return std::max(last_data_received_,
1472 std::max(last_ping_received_, last_ping_response_received_));
1473}
1474
zhihuang5ecf16c2016-06-01 17:09:15 -07001475ConnectionInfo Connection::stats() {
1476 stats_.recv_bytes_second = round(recv_rate_tracker_.ComputeRate());
1477 stats_.recv_total_bytes = recv_rate_tracker_.TotalSampleCount();
1478 stats_.sent_bytes_second = round(send_rate_tracker_.ComputeRate());
1479 stats_.sent_total_bytes = send_rate_tracker_.TotalSampleCount();
hbos06495bc2017-01-02 08:08:18 -08001480 stats_.receiving = receiving_;
1481 stats_.writable = write_state_ == STATE_WRITABLE;
1482 stats_.timeout = write_state_ == STATE_WRITE_TIMEOUT;
1483 stats_.new_connection = !reported_;
1484 stats_.rtt = rtt_;
1485 stats_.local_candidate = local_candidate();
1486 stats_.remote_candidate = remote_candidate();
1487 stats_.key = this;
1488 stats_.state = state_;
1489 stats_.priority = priority();
zhihuang5ecf16c2016-06-01 17:09:15 -07001490 return stats_;
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001491}
1492
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001493void Connection::MaybeUpdateLocalCandidate(ConnectionRequest* request,
1494 StunMessage* response) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001495 // RFC 5245
1496 // The agent checks the mapped address from the STUN response. If the
1497 // transport address does not match any of the local candidates that the
1498 // agent knows about, the mapped address represents a new candidate -- a
1499 // peer reflexive candidate.
1500 const StunAddressAttribute* addr =
1501 response->GetAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
1502 if (!addr) {
1503 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1504 << "No MAPPED-ADDRESS or XOR-MAPPED-ADDRESS found in the "
1505 << "stun response message";
1506 return;
1507 }
1508
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001509 for (size_t i = 0; i < port_->Candidates().size(); ++i) {
1510 if (port_->Candidates()[i].address() == addr->GetAddress()) {
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001511 if (local_candidate_index_ != i) {
1512 LOG_J(LS_INFO, this) << "Updating local candidate type to srflx.";
1513 local_candidate_index_ = i;
1514 // SignalStateChange to force a re-sort in P2PTransportChannel as this
1515 // Connection's local candidate has changed.
1516 SignalStateChange(this);
1517 }
1518 return;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001519 }
1520 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001521
1522 // RFC 5245
1523 // Its priority is set equal to the value of the PRIORITY attribute
1524 // in the Binding request.
1525 const StunUInt32Attribute* priority_attr =
1526 request->msg()->GetUInt32(STUN_ATTR_PRIORITY);
1527 if (!priority_attr) {
1528 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1529 << "No STUN_ATTR_PRIORITY found in the "
1530 << "stun response message";
1531 return;
1532 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001533 const uint32_t priority = priority_attr->value();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001534 std::string id = rtc::CreateRandomString(8);
1535
1536 Candidate new_local_candidate;
1537 new_local_candidate.set_id(id);
1538 new_local_candidate.set_component(local_candidate().component());
1539 new_local_candidate.set_type(PRFLX_PORT_TYPE);
1540 new_local_candidate.set_protocol(local_candidate().protocol());
1541 new_local_candidate.set_address(addr->GetAddress());
1542 new_local_candidate.set_priority(priority);
1543 new_local_candidate.set_username(local_candidate().username());
1544 new_local_candidate.set_password(local_candidate().password());
1545 new_local_candidate.set_network_name(local_candidate().network_name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001546 new_local_candidate.set_network_type(local_candidate().network_type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001547 new_local_candidate.set_related_address(local_candidate().address());
Taylor Brandstetterf7c15a92016-06-22 13:13:55 -07001548 new_local_candidate.set_generation(local_candidate().generation());
Honghai Zhang80f1db92016-01-27 11:54:45 -08001549 new_local_candidate.set_foundation(ComputeFoundation(
1550 PRFLX_PORT_TYPE, local_candidate().protocol(),
1551 local_candidate().relay_protocol(), local_candidate().address()));
honghaiza0c44ea2016-03-23 16:07:48 -07001552 new_local_candidate.set_network_id(local_candidate().network_id());
1553 new_local_candidate.set_network_cost(local_candidate().network_cost());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001554
1555 // Change the local candidate of this Connection to the new prflx candidate.
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001556 LOG_J(LS_INFO, this) << "Updating local candidate type to prflx.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001557 local_candidate_index_ = port_->AddPrflxCandidate(new_local_candidate);
1558
1559 // SignalStateChange to force a re-sort in P2PTransportChannel as this
1560 // Connection's local candidate has changed.
1561 SignalStateChange(this);
1562}
1563
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001564bool Connection::rtt_converged() const {
zhihuang435264a2016-06-21 11:28:38 -07001565 return rtt_samples_ > (RTT_RATIO + 1);
1566}
1567
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001568bool Connection::missing_responses(int64_t now) const {
zhihuang435264a2016-06-21 11:28:38 -07001569 if (pings_since_last_response_.empty()) {
1570 return false;
1571 }
1572
1573 int64_t waiting = now - pings_since_last_response_[0].sent_time;
1574 return waiting > 2 * rtt();
1575}
1576
deadbeef376e1232015-11-25 09:00:08 -08001577ProxyConnection::ProxyConnection(Port* port,
1578 size_t index,
1579 const Candidate& remote_candidate)
1580 : Connection(port, index, remote_candidate) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001581
1582int ProxyConnection::Send(const void* data, size_t size,
1583 const rtc::PacketOptions& options) {
zhihuang5ecf16c2016-06-01 17:09:15 -07001584 stats_.sent_total_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001585 int sent = port_->SendTo(data, size, remote_candidate_.address(),
1586 options, true);
1587 if (sent <= 0) {
nisseede5da42017-01-12 05:15:36 -08001588 RTC_DCHECK(sent < 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001589 error_ = port_->GetError();
zhihuang5ecf16c2016-06-01 17:09:15 -07001590 stats_.sent_discarded_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001591 } else {
Tim Psiaki63046262015-09-14 10:38:08 -07001592 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001593 }
1594 return sent;
1595}
1596
1597} // namespace cricket