blob: e77baf525692d9d1107fa04b1a9a730ef93fb935 [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "p2p/base/port.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000012
Raphael Kubo da Costa7f90e2c2017-10-13 15:49:32 +020013#include <math.h>
14
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000015#include <algorithm>
Steve Antonbabf9172017-11-29 10:19:02 -080016#include <utility>
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000017#include <vector>
18
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "p2p/base/portallocator.h"
20#include "rtc_base/base64.h"
21#include "rtc_base/checks.h"
22#include "rtc_base/crc32.h"
23#include "rtc_base/helpers.h"
24#include "rtc_base/logging.h"
25#include "rtc_base/messagedigest.h"
26#include "rtc_base/network.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010027#include "rtc_base/numerics/safe_minmax.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "rtc_base/stringencode.h"
30#include "rtc_base/stringutils.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000031
32namespace {
33
34// Determines whether we have seen at least the given maximum number of
35// pings fail to have a response.
36inline bool TooManyFailures(
Peter Thatcher1cf6f812015-05-15 10:40:45 -070037 const std::vector<cricket::Connection::SentPing>& pings_since_last_response,
Peter Boström0c4e06b2015-10-07 12:23:21 +020038 uint32_t maximum_failures,
honghaiz34b11eb2016-03-16 08:55:44 -070039 int rtt_estimate,
40 int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000041 // If we haven't sent that many pings, then we can't have failed that many.
42 if (pings_since_last_response.size() < maximum_failures)
43 return false;
44
45 // Check if the window in which we would expect a response to the ping has
46 // already elapsed.
honghaiz34b11eb2016-03-16 08:55:44 -070047 int64_t expected_response_time =
Peter Thatcher1cf6f812015-05-15 10:40:45 -070048 pings_since_last_response[maximum_failures - 1].sent_time + rtt_estimate;
49 return now > expected_response_time;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000050}
51
52// Determines whether we have gone too long without seeing any response.
53inline bool TooLongWithoutResponse(
Peter Thatcher1cf6f812015-05-15 10:40:45 -070054 const std::vector<cricket::Connection::SentPing>& pings_since_last_response,
honghaiz34b11eb2016-03-16 08:55:44 -070055 int64_t maximum_time,
56 int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000057 if (pings_since_last_response.size() == 0)
58 return false;
59
Peter Thatcher1cf6f812015-05-15 10:40:45 -070060 auto first = pings_since_last_response[0];
61 return now > (first.sent_time + maximum_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000062}
63
Qingsi Wang93a84392018-01-30 17:13:09 -080064// Helper methods for converting string values of log description fields to
65// enum.
66webrtc::IceCandidateType GetCandidateTypeByString(const std::string& type) {
67 if (type == cricket::LOCAL_PORT_TYPE) {
68 return webrtc::IceCandidateType::kLocal;
69 } else if (type == cricket::STUN_PORT_TYPE) {
70 return webrtc::IceCandidateType::kStun;
71 } else if (type == cricket::PRFLX_PORT_TYPE) {
72 return webrtc::IceCandidateType::kPrflx;
73 } else if (type == cricket::RELAY_PORT_TYPE) {
74 return webrtc::IceCandidateType::kRelay;
75 }
76 return webrtc::IceCandidateType::kUnknown;
77}
78
79webrtc::IceCandidatePairProtocol GetProtocolByString(
80 const std::string& protocol) {
81 if (protocol == cricket::UDP_PROTOCOL_NAME) {
82 return webrtc::IceCandidatePairProtocol::kUdp;
83 } else if (protocol == cricket::TCP_PROTOCOL_NAME) {
84 return webrtc::IceCandidatePairProtocol::kTcp;
85 } else if (protocol == cricket::SSLTCP_PROTOCOL_NAME) {
86 return webrtc::IceCandidatePairProtocol::kSsltcp;
87 } else if (protocol == cricket::TLS_PROTOCOL_NAME) {
88 return webrtc::IceCandidatePairProtocol::kTls;
89 }
90 return webrtc::IceCandidatePairProtocol::kUnknown;
91}
92
93webrtc::IceCandidatePairAddressFamily GetAddressFamilyByInt(
94 int address_family) {
95 if (address_family == AF_INET) {
96 return webrtc::IceCandidatePairAddressFamily::kIpv4;
97 } else if (address_family == AF_INET6) {
98 return webrtc::IceCandidatePairAddressFamily::kIpv6;
99 }
100 return webrtc::IceCandidatePairAddressFamily::kUnknown;
101}
102
103webrtc::IceCandidateNetworkType ConvertNetworkType(rtc::AdapterType type) {
104 if (type == rtc::ADAPTER_TYPE_ETHERNET) {
105 return webrtc::IceCandidateNetworkType::kEthernet;
106 } else if (type == rtc::ADAPTER_TYPE_LOOPBACK) {
107 return webrtc::IceCandidateNetworkType::kLoopback;
108 } else if (type == rtc::ADAPTER_TYPE_WIFI) {
109 return webrtc::IceCandidateNetworkType::kWifi;
110 } else if (type == rtc::ADAPTER_TYPE_VPN) {
111 return webrtc::IceCandidateNetworkType::kVpn;
112 } else if (type == rtc::ADAPTER_TYPE_CELLULAR) {
113 return webrtc::IceCandidateNetworkType::kCellular;
114 }
115 return webrtc::IceCandidateNetworkType::kUnknown;
116}
117
Qingsi Wang6e641e62018-04-11 20:14:17 -0700118rtc::PacketInfoProtocolType ConvertProtocolTypeToPacketInfoProtocolType(
119 cricket::ProtocolType type) {
120 switch (type) {
121 case cricket::ProtocolType::PROTO_UDP:
122 return rtc::PacketInfoProtocolType::kUdp;
123 case cricket::ProtocolType::PROTO_TCP:
124 return rtc::PacketInfoProtocolType::kTcp;
125 case cricket::ProtocolType::PROTO_SSLTCP:
126 return rtc::PacketInfoProtocolType::kSsltcp;
127 case cricket::ProtocolType::PROTO_TLS:
128 return rtc::PacketInfoProtocolType::kTls;
129 default:
130 return rtc::PacketInfoProtocolType::kUnknown;
131 }
132}
133
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000134// We will restrict RTT estimates (when used for determining state) to be
135// within a reasonable range.
honghaiz34b11eb2016-03-16 08:55:44 -0700136const int MINIMUM_RTT = 100; // 0.1 seconds
skvlad51072462017-02-02 11:50:14 -0800137const int MAXIMUM_RTT = 60000; // 60 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000138
139// When we don't have any RTT data, we have to pick something reasonable. We
140// use a large value just in case the connection is really slow.
skvlad51072462017-02-02 11:50:14 -0800141const int DEFAULT_RTT = 3000; // 3 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000142
143// Computes our estimate of the RTT given the current estimate.
honghaiz34b11eb2016-03-16 08:55:44 -0700144inline int ConservativeRTTEstimate(int rtt) {
kwiberg07038562017-06-12 11:40:47 -0700145 return rtc::SafeClamp(2 * rtt, MINIMUM_RTT, MAXIMUM_RTT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000146}
147
148// Weighting of the old rtt value to new data.
149const int RTT_RATIO = 3; // 3 : 1
150
pthatcher94a2f212017-02-08 14:42:22 -0800151// The delay before we begin checking if this port is useless. We set
152// it to a little higher than a total STUN timeout.
153const int kPortTimeoutDelay = cricket::STUN_TOTAL_TIMEOUT + 5000;
zsteinabbacbf2017-03-20 10:53:12 -0700154
155// For packet loss estimation.
156const int64_t kConsiderPacketLostAfter = 3000; // 3 seconds
157
158// For packet loss estimation.
159const int64_t kForgetPacketAfter = 30000; // 30 seconds
160
Honghai Zhang351d77b2016-05-20 15:08:29 -0700161} // namespace
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000162
163namespace cricket {
164
Qingsi Wangdea68892018-03-27 10:55:21 -0700165using webrtc::RTCErrorType;
166using webrtc::RTCError;
167
zhihuang38989e52017-03-21 11:04:53 -0700168// TODO(ronghuawu): Use "local", "srflx", "prflx" and "relay". But this requires
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000169// the signaling part be updated correspondingly as well.
170const char LOCAL_PORT_TYPE[] = "local";
171const char STUN_PORT_TYPE[] = "stun";
172const char PRFLX_PORT_TYPE[] = "prflx";
173const char RELAY_PORT_TYPE[] = "relay";
174
hnsl277b2502016-12-13 05:17:23 -0800175static const char* const PROTO_NAMES[] = {UDP_PROTOCOL_NAME, TCP_PROTOCOL_NAME,
176 SSLTCP_PROTOCOL_NAME,
177 TLS_PROTOCOL_NAME};
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000178
179const char* ProtoToString(ProtocolType proto) {
180 return PROTO_NAMES[proto];
181}
182
183bool StringToProto(const char* value, ProtocolType* proto) {
184 for (size_t i = 0; i <= PROTO_LAST; ++i) {
185 if (_stricmp(PROTO_NAMES[i], value) == 0) {
186 *proto = static_cast<ProtocolType>(i);
187 return true;
188 }
189 }
190 return false;
191}
192
193// RFC 6544, TCP candidate encoding rules.
194const int DISCARD_PORT = 9;
195const char TCPTYPE_ACTIVE_STR[] = "active";
196const char TCPTYPE_PASSIVE_STR[] = "passive";
197const char TCPTYPE_SIMOPEN_STR[] = "so";
198
199// Foundation: An arbitrary string that is the same for two candidates
200// that have the same type, base IP address, protocol (UDP, TCP,
201// etc.), and STUN or TURN server. If any of these are different,
202// then the foundation will be different. Two candidate pairs with
203// the same foundation pairs are likely to have similar network
204// characteristics. Foundations are used in the frozen algorithm.
Honghai Zhang80f1db92016-01-27 11:54:45 -0800205static std::string ComputeFoundation(const std::string& type,
206 const std::string& protocol,
207 const std::string& relay_protocol,
208 const rtc::SocketAddress& base_address) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000209 std::ostringstream ost;
Honghai Zhang80f1db92016-01-27 11:54:45 -0800210 ost << type << base_address.ipaddr().ToString() << protocol << relay_protocol;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200211 return rtc::ToString<uint32_t>(rtc::ComputeCrc32(ost.str()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000212}
213
Qingsi Wang72a43a12018-02-20 16:03:18 -0800214CandidateStats::CandidateStats() = default;
215
216CandidateStats::CandidateStats(const CandidateStats&) = default;
217
218CandidateStats::CandidateStats(Candidate candidate) {
219 this->candidate = candidate;
220}
221
222CandidateStats::~CandidateStats() = default;
223
Taylor Brandstetter6e2e7ce2017-12-19 10:26:23 -0800224ConnectionInfo::ConnectionInfo()
225 : best_connection(false),
226 writable(false),
227 receiving(false),
228 timeout(false),
229 new_connection(false),
230 rtt(0),
231 sent_total_bytes(0),
232 sent_bytes_second(0),
233 sent_discarded_packets(0),
234 sent_total_packets(0),
235 sent_ping_requests_total(0),
236 sent_ping_requests_before_first_response(0),
237 sent_ping_responses(0),
238 recv_total_bytes(0),
239 recv_bytes_second(0),
240 recv_ping_requests(0),
241 recv_ping_responses(0),
242 key(nullptr),
243 state(IceCandidatePairState::WAITING),
244 priority(0),
245 nominated(false),
246 total_round_trip_time_ms(0) {}
247
248ConnectionInfo::ConnectionInfo(const ConnectionInfo&) = default;
249
250ConnectionInfo::~ConnectionInfo() = default;
251
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000252Port::Port(rtc::Thread* thread,
Honghai Zhangd00c0572016-06-28 09:44:47 -0700253 const std::string& type,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000254 rtc::PacketSocketFactory* factory,
255 rtc::Network* network,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000256 const std::string& username_fragment,
257 const std::string& password)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000258 : thread_(thread),
259 factory_(factory),
Honghai Zhangd00c0572016-06-28 09:44:47 -0700260 type_(type),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000261 send_retransmit_count_attribute_(false),
262 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000263 min_port_(0),
264 max_port_(0),
265 component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
266 generation_(0),
267 ice_username_fragment_(username_fragment),
268 password_(password),
269 timeout_delay_(kPortTimeoutDelay),
270 enable_port_packets_(false),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000271 ice_role_(ICEROLE_UNKNOWN),
272 tiebreaker_(0),
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700273 shared_socket_(true) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000274 Construct();
275}
276
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000277Port::Port(rtc::Thread* thread,
278 const std::string& type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000279 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000280 rtc::Network* network,
Steve Antonf2737d22017-10-31 16:27:34 -0700281 const rtc::IPAddress& ip,
282 const std::string& username_fragment,
283 const std::string& password)
284 : Port(thread, type, factory, network, username_fragment, password) {}
285
286Port::Port(rtc::Thread* thread,
287 const std::string& type,
288 rtc::PacketSocketFactory* factory,
289 rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200290 uint16_t min_port,
291 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000292 const std::string& username_fragment,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000293 const std::string& password)
294 : thread_(thread),
295 factory_(factory),
296 type_(type),
297 send_retransmit_count_attribute_(false),
298 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000299 min_port_(min_port),
300 max_port_(max_port),
301 component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
302 generation_(0),
303 ice_username_fragment_(username_fragment),
304 password_(password),
305 timeout_delay_(kPortTimeoutDelay),
306 enable_port_packets_(false),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000307 ice_role_(ICEROLE_UNKNOWN),
308 tiebreaker_(0),
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700309 shared_socket_(false) {
nisseede5da42017-01-12 05:15:36 -0800310 RTC_DCHECK(factory_ != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000311 Construct();
312}
313
314void Port::Construct() {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700315 // TODO(pthatcher): Remove this old behavior once we're sure no one
316 // relies on it. If the username_fragment and password are empty,
317 // we should just create one.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000318 if (ice_username_fragment_.empty()) {
nisseede5da42017-01-12 05:15:36 -0800319 RTC_DCHECK(password_.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000320 ice_username_fragment_ = rtc::CreateRandomString(ICE_UFRAG_LENGTH);
321 password_ = rtc::CreateRandomString(ICE_PWD_LENGTH);
322 }
Honghai Zhang351d77b2016-05-20 15:08:29 -0700323 network_->SignalTypeChanged.connect(this, &Port::OnNetworkTypeChanged);
324 network_cost_ = network_->GetCost();
honghaize1a0c942016-02-16 14:54:56 -0800325
Honghai Zhanga74363c2016-07-28 18:06:15 -0700326 thread_->PostDelayed(RTC_FROM_HERE, timeout_delay_, this,
327 MSG_DESTROY_IF_DEAD);
Jonas Olssond7d762d2018-03-28 09:47:51 +0200328 RTC_LOG(LS_INFO) << ToString()
329 << ": Port created with network cost " << network_cost_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000330}
331
332Port::~Port() {
333 // Delete all of the remaining connections. We copy the list up front
334 // because each deletion will cause it to be modified.
335
336 std::vector<Connection*> list;
337
338 AddressMap::iterator iter = connections_.begin();
339 while (iter != connections_.end()) {
340 list.push_back(iter->second);
341 ++iter;
342 }
343
Peter Boström0c4e06b2015-10-07 12:23:21 +0200344 for (uint32_t i = 0; i < list.size(); i++)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000345 delete list[i];
346}
347
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700348const std::string& Port::Type() const {
349 return type_;
350}
351rtc::Network* Port::Network() const {
352 return network_;
353}
354
355IceRole Port::GetIceRole() const {
356 return ice_role_;
357}
358
359void Port::SetIceRole(IceRole role) {
360 ice_role_ = role;
361}
362
363void Port::SetIceTiebreaker(uint64_t tiebreaker) {
364 tiebreaker_ = tiebreaker;
365}
366uint64_t Port::IceTiebreaker() const {
367 return tiebreaker_;
368}
369
370bool Port::SharedSocket() const {
371 return shared_socket_;
372}
373
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700374void Port::SetIceParameters(int component,
375 const std::string& username_fragment,
376 const std::string& password) {
377 component_ = component;
378 ice_username_fragment_ = username_fragment;
379 password_ = password;
380 for (Candidate& c : candidates_) {
381 c.set_component(component);
382 c.set_username(username_fragment);
383 c.set_password(password);
384 }
385}
386
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700387const std::vector<Candidate>& Port::Candidates() const {
388 return candidates_;
389}
390
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000391Connection* Port::GetConnection(const rtc::SocketAddress& remote_addr) {
392 AddressMap::const_iterator iter = connections_.find(remote_addr);
393 if (iter != connections_.end())
394 return iter->second;
395 else
396 return NULL;
397}
398
399void Port::AddAddress(const rtc::SocketAddress& address,
400 const rtc::SocketAddress& base_address,
401 const rtc::SocketAddress& related_address,
402 const std::string& protocol,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700403 const std::string& relay_protocol,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000404 const std::string& tcptype,
405 const std::string& type,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200406 uint32_t type_preference,
407 uint32_t relay_preference,
Peter Boström2758c662017-02-13 20:33:27 -0500408 bool final) {
409 AddAddress(address, base_address, related_address, protocol, relay_protocol,
410 tcptype, type, type_preference, relay_preference, "", final);
411}
412
413void Port::AddAddress(const rtc::SocketAddress& address,
414 const rtc::SocketAddress& base_address,
415 const rtc::SocketAddress& related_address,
416 const std::string& protocol,
417 const std::string& relay_protocol,
418 const std::string& tcptype,
419 const std::string& type,
420 uint32_t type_preference,
421 uint32_t relay_preference,
zhihuang26d99c22017-02-13 12:47:27 -0800422 const std::string& url,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000423 bool final) {
424 if (protocol == TCP_PROTOCOL_NAME && type == LOCAL_PORT_TYPE) {
nisseede5da42017-01-12 05:15:36 -0800425 RTC_DCHECK(!tcptype.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000426 }
427
honghaiza0c44ea2016-03-23 16:07:48 -0700428 std::string foundation =
429 ComputeFoundation(type, protocol, relay_protocol, base_address);
430 Candidate c(component_, protocol, address, 0U, username_fragment(), password_,
431 type, generation_, foundation, network_->id(), network_cost_);
432 c.set_priority(
433 c.GetPriority(type_preference, network_->preference(), relay_preference));
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700434 c.set_relay_protocol(relay_protocol);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000435 c.set_tcptype(tcptype);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000436 c.set_network_name(network_->name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +0000437 c.set_network_type(network_->type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000438 c.set_related_address(related_address);
zhihuang26d99c22017-02-13 12:47:27 -0800439 c.set_url(url);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000440 candidates_.push_back(c);
441 SignalCandidateReady(this, c);
442
443 if (final) {
444 SignalPortComplete(this);
445 }
446}
447
honghaiz36f50e82016-06-01 15:57:03 -0700448void Port::AddOrReplaceConnection(Connection* conn) {
449 auto ret = connections_.insert(
450 std::make_pair(conn->remote_candidate().address(), conn));
451 // If there is a different connection on the same remote address, replace
452 // it with the new one and destroy the old one.
453 if (ret.second == false && ret.first->second != conn) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200454 RTC_LOG(LS_WARNING)
455 << ToString()
456 << ": A new connection was created on an existing remote address. "
457 "New remote candidate: "
458 << conn->remote_candidate().ToString();
honghaiz36f50e82016-06-01 15:57:03 -0700459 ret.first->second->SignalDestroyed.disconnect(this);
460 ret.first->second->Destroy();
461 ret.first->second = conn;
462 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000463 conn->SignalDestroyed.connect(this, &Port::OnConnectionDestroyed);
464 SignalConnectionCreated(this, conn);
465}
466
467void Port::OnReadPacket(
468 const char* data, size_t size, const rtc::SocketAddress& addr,
469 ProtocolType proto) {
470 // If the user has enabled port packets, just hand this over.
471 if (enable_port_packets_) {
472 SignalReadPacket(this, data, size, addr);
473 return;
474 }
475
476 // If this is an authenticated STUN request, then signal unknown address and
477 // send back a proper binding response.
kwiberg3ec46792016-04-27 07:22:53 -0700478 std::unique_ptr<IceMessage> msg;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000479 std::string remote_username;
kwiberg6baec032016-03-15 11:09:39 -0700480 if (!GetStunMessage(data, size, addr, &msg, &remote_username)) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200481 RTC_LOG(LS_ERROR) << ToString()
482 << ": Received non-STUN packet from unknown address: "
483 << addr.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000484 } else if (!msg) {
485 // STUN message handled already
486 } else if (msg->type() == STUN_BINDING_REQUEST) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200487 RTC_LOG(LS_INFO) << "Received STUN ping id="
488 << rtc::hex_encode(msg->transaction_id())
Mirko Bonadei675513b2017-11-09 11:09:25 +0100489 << " from unknown address " << addr.ToSensitiveString();
Qingsi Wang2bd41f92018-03-23 14:28:37 -0700490 // We need to signal an unknown address before we handle any role conflict
491 // below. Otherwise there would be no candidate pair and TURN entry created
492 // to send the error response in case of a role conflict.
493 SignalUnknownAddress(this, addr, proto, msg.get(), remote_username, false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000494 // Check for role conflicts.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700495 if (!MaybeIceRoleConflict(addr, msg.get(), remote_username)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100496 RTC_LOG(LS_INFO) << "Received conflicting role from the peer.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000497 return;
498 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000499 } else {
500 // NOTE(tschmelcher): STUN_BINDING_RESPONSE is benign. It occurs if we
501 // pruned a connection for this port while it had STUN requests in flight,
502 // because we then get back responses for them, which this code correctly
503 // does not handle.
504 if (msg->type() != STUN_BINDING_RESPONSE) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200505 RTC_LOG(LS_ERROR) << ToString()
506 << ": Received unexpected STUN message type: "
507 << msg->type() << " from unknown address: "
508 << addr.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000509 }
510 }
511}
512
513void Port::OnReadyToSend() {
514 AddressMap::iterator iter = connections_.begin();
515 for (; iter != connections_.end(); ++iter) {
516 iter->second->OnReadyToSend();
517 }
518}
519
520size_t Port::AddPrflxCandidate(const Candidate& local) {
521 candidates_.push_back(local);
522 return (candidates_.size() - 1);
523}
524
kwiberg6baec032016-03-15 11:09:39 -0700525bool Port::GetStunMessage(const char* data,
526 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000527 const rtc::SocketAddress& addr,
kwiberg3ec46792016-04-27 07:22:53 -0700528 std::unique_ptr<IceMessage>* out_msg,
kwiberg6baec032016-03-15 11:09:39 -0700529 std::string* out_username) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000530 // NOTE: This could clearly be optimized to avoid allocating any memory.
531 // However, at the data rates we'll be looking at on the client side,
532 // this probably isn't worth worrying about.
nisseede5da42017-01-12 05:15:36 -0800533 RTC_DCHECK(out_msg != NULL);
534 RTC_DCHECK(out_username != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000535 out_username->clear();
536
537 // Don't bother parsing the packet if we can tell it's not STUN.
538 // In ICE mode, all STUN packets will have a valid fingerprint.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700539 if (!StunMessage::ValidateFingerprint(data, size)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000540 return false;
541 }
542
543 // Parse the request message. If the packet is not a complete and correct
544 // STUN message, then ignore it.
kwiberg3ec46792016-04-27 07:22:53 -0700545 std::unique_ptr<IceMessage> stun_msg(new IceMessage());
jbauchf1f87202016-03-30 06:43:37 -0700546 rtc::ByteBufferReader buf(data, size);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000547 if (!stun_msg->Read(&buf) || (buf.Length() > 0)) {
548 return false;
549 }
550
551 if (stun_msg->type() == STUN_BINDING_REQUEST) {
552 // Check for the presence of USERNAME and MESSAGE-INTEGRITY (if ICE) first.
553 // If not present, fail with a 400 Bad Request.
554 if (!stun_msg->GetByteString(STUN_ATTR_USERNAME) ||
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700555 !stun_msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY)) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200556 RTC_LOG(LS_ERROR) << ToString()
557 << ": Received STUN request without username/M-I from: "
558 << addr.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000559 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_BAD_REQUEST,
560 STUN_ERROR_REASON_BAD_REQUEST);
561 return true;
562 }
563
564 // If the username is bad or unknown, fail with a 401 Unauthorized.
565 std::string local_ufrag;
566 std::string remote_ufrag;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700567 if (!ParseStunUsername(stun_msg.get(), &local_ufrag, &remote_ufrag) ||
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000568 local_ufrag != username_fragment()) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200569 RTC_LOG(LS_ERROR) << ToString()
570 << ": Received STUN request with bad local username "
571 << local_ufrag << " from " << addr.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000572 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
573 STUN_ERROR_REASON_UNAUTHORIZED);
574 return true;
575 }
576
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000577 // If ICE, and the MESSAGE-INTEGRITY is bad, fail with a 401 Unauthorized
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700578 if (!stun_msg->ValidateMessageIntegrity(data, size, password_)) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200579 RTC_LOG(LS_ERROR) << ToString()
580 << ": Received STUN request with bad M-I from "
581 << addr.ToSensitiveString()
582 << ", password_=" << password_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000583 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
584 STUN_ERROR_REASON_UNAUTHORIZED);
585 return true;
586 }
587 out_username->assign(remote_ufrag);
588 } else if ((stun_msg->type() == STUN_BINDING_RESPONSE) ||
589 (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE)) {
590 if (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE) {
591 if (const StunErrorCodeAttribute* error_code = stun_msg->GetErrorCode()) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200592 RTC_LOG(LS_ERROR) << ToString()
593 << ": Received STUN binding error: class="
594 << error_code->eclass()
595 << " number=" << error_code->number() << " reason='"
596 << error_code->reason() << "' from "
597 << addr.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000598 // Return message to allow error-specific processing
599 } else {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200600 RTC_LOG(LS_ERROR)
601 << ToString()
602 << ": Received STUN binding error without a error code from "
603 << addr.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000604 return true;
605 }
606 }
607 // NOTE: Username should not be used in verifying response messages.
608 out_username->clear();
609 } else if (stun_msg->type() == STUN_BINDING_INDICATION) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200610 RTC_LOG(LS_VERBOSE) << ToString()
611 << ": Received STUN binding indication: from "
612 << addr.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000613 out_username->clear();
614 // No stun attributes will be verified, if it's stun indication message.
615 // Returning from end of the this method.
616 } else {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200617 RTC_LOG(LS_ERROR) << ToString()
618 << ": Received STUN packet with invalid type ("
619 << stun_msg->type() << ") from "
620 << addr.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000621 return true;
622 }
623
624 // Return the STUN message found.
kwiberg6baec032016-03-15 11:09:39 -0700625 *out_msg = std::move(stun_msg);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000626 return true;
627}
628
629bool Port::IsCompatibleAddress(const rtc::SocketAddress& addr) {
deadbeef5c3c1042017-08-04 15:01:57 -0700630 // Get a representative IP for the Network this port is configured to use.
631 rtc::IPAddress ip = network_->GetBestIP();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000632 // We use single-stack sockets, so families must match.
deadbeef5c3c1042017-08-04 15:01:57 -0700633 if (addr.family() != ip.family()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000634 return false;
635 }
636 // Link-local IPv6 ports can only connect to other link-local IPv6 ports.
deadbeef5c3c1042017-08-04 15:01:57 -0700637 if (ip.family() == AF_INET6 &&
638 (IPIsLinkLocal(ip) != IPIsLinkLocal(addr.ipaddr()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000639 return false;
640 }
641 return true;
642}
643
644bool Port::ParseStunUsername(const StunMessage* stun_msg,
645 std::string* local_ufrag,
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700646 std::string* remote_ufrag) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000647 // The packet must include a username that either begins or ends with our
648 // fragment. It should begin with our fragment if it is a request and it
649 // should end with our fragment if it is a response.
650 local_ufrag->clear();
651 remote_ufrag->clear();
652 const StunByteStringAttribute* username_attr =
653 stun_msg->GetByteString(STUN_ATTR_USERNAME);
654 if (username_attr == NULL)
655 return false;
656
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700657 // RFRAG:LFRAG
658 const std::string username = username_attr->GetString();
659 size_t colon_pos = username.find(":");
660 if (colon_pos == std::string::npos) {
661 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000662 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000663
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700664 *local_ufrag = username.substr(0, colon_pos);
665 *remote_ufrag = username.substr(colon_pos + 1, username.size());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000666 return true;
667}
668
669bool Port::MaybeIceRoleConflict(
670 const rtc::SocketAddress& addr, IceMessage* stun_msg,
671 const std::string& remote_ufrag) {
672 // Validate ICE_CONTROLLING or ICE_CONTROLLED attributes.
673 bool ret = true;
674 IceRole remote_ice_role = ICEROLE_UNKNOWN;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200675 uint64_t remote_tiebreaker = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000676 const StunUInt64Attribute* stun_attr =
677 stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
678 if (stun_attr) {
679 remote_ice_role = ICEROLE_CONTROLLING;
680 remote_tiebreaker = stun_attr->value();
681 }
682
683 // If |remote_ufrag| is same as port local username fragment and
684 // tie breaker value received in the ping message matches port
685 // tiebreaker value this must be a loopback call.
686 // We will treat this as valid scenario.
687 if (remote_ice_role == ICEROLE_CONTROLLING &&
688 username_fragment() == remote_ufrag &&
689 remote_tiebreaker == IceTiebreaker()) {
690 return true;
691 }
692
693 stun_attr = stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
694 if (stun_attr) {
695 remote_ice_role = ICEROLE_CONTROLLED;
696 remote_tiebreaker = stun_attr->value();
697 }
698
699 switch (ice_role_) {
700 case ICEROLE_CONTROLLING:
701 if (ICEROLE_CONTROLLING == remote_ice_role) {
702 if (remote_tiebreaker >= tiebreaker_) {
703 SignalRoleConflict(this);
704 } else {
705 // Send Role Conflict (487) error response.
706 SendBindingErrorResponse(stun_msg, addr,
707 STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
708 ret = false;
709 }
710 }
711 break;
712 case ICEROLE_CONTROLLED:
713 if (ICEROLE_CONTROLLED == remote_ice_role) {
714 if (remote_tiebreaker < tiebreaker_) {
715 SignalRoleConflict(this);
716 } else {
717 // Send Role Conflict (487) error response.
718 SendBindingErrorResponse(stun_msg, addr,
719 STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
720 ret = false;
721 }
722 }
723 break;
724 default:
nissec80e7412017-01-11 05:56:46 -0800725 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000726 }
727 return ret;
728}
729
730void Port::CreateStunUsername(const std::string& remote_username,
731 std::string* stun_username_attr_str) const {
732 stun_username_attr_str->clear();
733 *stun_username_attr_str = remote_username;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700734 stun_username_attr_str->append(":");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000735 stun_username_attr_str->append(username_fragment());
736}
737
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700738bool Port::HandleIncomingPacket(rtc::AsyncPacketSocket* socket,
739 const char* data,
740 size_t size,
741 const rtc::SocketAddress& remote_addr,
742 const rtc::PacketTime& packet_time) {
743 RTC_NOTREACHED();
744 return false;
745}
746
Jonas Oreland202994c2017-12-18 12:10:43 +0100747bool Port::CanHandleIncomingPacketsFrom(const rtc::SocketAddress&) const {
748 return false;
749}
750
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000751void Port::SendBindingResponse(StunMessage* request,
752 const rtc::SocketAddress& addr) {
nisseede5da42017-01-12 05:15:36 -0800753 RTC_DCHECK(request->type() == STUN_BINDING_REQUEST);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000754
755 // Retrieve the username from the request.
756 const StunByteStringAttribute* username_attr =
757 request->GetByteString(STUN_ATTR_USERNAME);
nisseede5da42017-01-12 05:15:36 -0800758 RTC_DCHECK(username_attr != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000759 if (username_attr == NULL) {
760 // No valid username, skip the response.
761 return;
762 }
763
764 // Fill in the response message.
765 StunMessage response;
766 response.SetType(STUN_BINDING_RESPONSE);
767 response.SetTransactionID(request->transaction_id());
768 const StunUInt32Attribute* retransmit_attr =
769 request->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
770 if (retransmit_attr) {
771 // Inherit the incoming retransmit value in the response so the other side
772 // can see our view of lost pings.
zsteinf42cc9d2017-03-27 16:17:19 -0700773 response.AddAttribute(rtc::MakeUnique<StunUInt32Attribute>(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000774 STUN_ATTR_RETRANSMIT_COUNT, retransmit_attr->value()));
775
776 if (retransmit_attr->value() > CONNECTION_WRITE_CONNECT_FAILURES) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200777 RTC_LOG(LS_INFO)
778 << ToString()
779 << ": Received a remote ping with high retransmit count: "
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000780 << retransmit_attr->value();
781 }
782 }
783
zsteinf42cc9d2017-03-27 16:17:19 -0700784 response.AddAttribute(rtc::MakeUnique<StunXorAddressAttribute>(
785 STUN_ATTR_XOR_MAPPED_ADDRESS, addr));
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700786 response.AddMessageIntegrity(password_);
787 response.AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000788
789 // Send the response message.
jbauchf1f87202016-03-30 06:43:37 -0700790 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000791 response.Write(&buf);
792 rtc::PacketOptions options(DefaultDscpValue());
Qingsi Wang6e641e62018-04-11 20:14:17 -0700793 options.info_signaled_after_sent.packet_type =
794 rtc::PacketType::kIceConnectivityCheckResponse;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700795 auto err = SendTo(buf.Data(), buf.Length(), addr, options, false);
796 if (err < 0) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200797 RTC_LOG(LS_ERROR) << ToString()
798 << ": Failed to send STUN ping response, to="
799 << addr.ToSensitiveString() << ", err=" << err
800 << ", id=" << rtc::hex_encode(response.transaction_id());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700801 } else {
802 // Log at LS_INFO if we send a stun ping response on an unwritable
803 // connection.
honghaiz9b5ee9c2015-11-11 13:19:17 -0800804 Connection* conn = GetConnection(addr);
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700805 rtc::LoggingSeverity sev = (conn && !conn->writable()) ?
806 rtc::LS_INFO : rtc::LS_VERBOSE;
Jonas Olssond7d762d2018-03-28 09:47:51 +0200807 RTC_LOG_V(sev) << ToString()
808 << ": Sent STUN ping response, to="
809 << addr.ToSensitiveString()
810 << ", id=" << rtc::hex_encode(response.transaction_id());
zhihuang5ecf16c2016-06-01 17:09:15 -0700811
812 conn->stats_.sent_ping_responses++;
Qingsi Wang93a84392018-01-30 17:13:09 -0800813 conn->LogCandidatePairEvent(
814 webrtc::IceCandidatePairEventType::kCheckResponseSent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000815 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000816}
817
818void Port::SendBindingErrorResponse(StunMessage* request,
819 const rtc::SocketAddress& addr,
820 int error_code, const std::string& reason) {
nisseede5da42017-01-12 05:15:36 -0800821 RTC_DCHECK(request->type() == STUN_BINDING_REQUEST);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000822
823 // Fill in the response message.
824 StunMessage response;
825 response.SetType(STUN_BINDING_ERROR_RESPONSE);
826 response.SetTransactionID(request->transaction_id());
827
828 // When doing GICE, we need to write out the error code incorrectly to
829 // maintain backwards compatiblility.
zsteinf42cc9d2017-03-27 16:17:19 -0700830 auto error_attr = StunAttribute::CreateErrorCode();
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700831 error_attr->SetCode(error_code);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000832 error_attr->SetReason(reason);
zsteinf42cc9d2017-03-27 16:17:19 -0700833 response.AddAttribute(std::move(error_attr));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000834
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700835 // Per Section 10.1.2, certain error cases don't get a MESSAGE-INTEGRITY,
836 // because we don't have enough information to determine the shared secret.
837 if (error_code != STUN_ERROR_BAD_REQUEST &&
838 error_code != STUN_ERROR_UNAUTHORIZED)
839 response.AddMessageIntegrity(password_);
840 response.AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000841
842 // Send the response message.
jbauchf1f87202016-03-30 06:43:37 -0700843 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000844 response.Write(&buf);
845 rtc::PacketOptions options(DefaultDscpValue());
Qingsi Wang6e641e62018-04-11 20:14:17 -0700846 options.info_signaled_after_sent.packet_type =
847 rtc::PacketType::kIceConnectivityCheckResponse;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000848 SendTo(buf.Data(), buf.Length(), addr, options, false);
Jonas Olssond7d762d2018-03-28 09:47:51 +0200849 RTC_LOG(LS_INFO) << ToString()
850 << ": Sending STUN binding error: reason=" << reason
851 << " to " << addr.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000852}
853
Honghai Zhanga74363c2016-07-28 18:06:15 -0700854void Port::KeepAliveUntilPruned() {
855 // If it is pruned, we won't bring it up again.
856 if (state_ == State::INIT) {
857 state_ = State::KEEP_ALIVE_UNTIL_PRUNED;
858 }
859}
860
861void Port::Prune() {
862 state_ = State::PRUNED;
863 thread_->Post(RTC_FROM_HERE, this, MSG_DESTROY_IF_DEAD);
864}
865
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000866void Port::OnMessage(rtc::Message *pmsg) {
nisseede5da42017-01-12 05:15:36 -0800867 RTC_DCHECK(pmsg->message_id == MSG_DESTROY_IF_DEAD);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700868 bool dead =
869 (state_ == State::INIT || state_ == State::PRUNED) &&
870 connections_.empty() &&
871 rtc::TimeMillis() - last_time_all_connections_removed_ >= timeout_delay_;
872 if (dead) {
honghaizd0b31432015-09-30 12:42:17 -0700873 Destroy();
874 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000875}
876
Honghai Zhang351d77b2016-05-20 15:08:29 -0700877void Port::OnNetworkTypeChanged(const rtc::Network* network) {
nisseede5da42017-01-12 05:15:36 -0800878 RTC_DCHECK(network == network_);
Honghai Zhang351d77b2016-05-20 15:08:29 -0700879
880 UpdateNetworkCost();
881}
882
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000883std::string Port::ToString() const {
884 std::stringstream ss;
honghaize3c6c822016-02-17 13:00:28 -0800885 ss << "Port[" << std::hex << this << std::dec << ":" << content_name_ << ":"
886 << component_ << ":" << generation_ << ":" << type_ << ":"
887 << network_->ToString() << "]";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000888 return ss.str();
889}
890
Honghai Zhang351d77b2016-05-20 15:08:29 -0700891// TODO(honghaiz): Make the network cost configurable from user setting.
892void Port::UpdateNetworkCost() {
893 uint16_t new_cost = network_->GetCost();
894 if (network_cost_ == new_cost) {
895 return;
896 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100897 RTC_LOG(LS_INFO) << "Network cost changed from " << network_cost_ << " to "
898 << new_cost
899 << ". Number of candidates created: " << candidates_.size()
900 << ". Number of connections created: "
901 << connections_.size();
Honghai Zhang351d77b2016-05-20 15:08:29 -0700902 network_cost_ = new_cost;
903 for (cricket::Candidate& candidate : candidates_) {
904 candidate.set_network_cost(network_cost_);
905 }
906 // Network cost change will affect the connection selection criteria.
907 // Signal the connection state change on each connection to force a
908 // re-sort in P2PTransportChannel.
909 for (auto kv : connections_) {
910 Connection* conn = kv.second;
911 conn->SignalStateChange(conn);
912 }
913}
914
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000915void Port::EnablePortPackets() {
916 enable_port_packets_ = true;
917}
918
919void Port::OnConnectionDestroyed(Connection* conn) {
920 AddressMap::iterator iter =
921 connections_.find(conn->remote_candidate().address());
nisseede5da42017-01-12 05:15:36 -0800922 RTC_DCHECK(iter != connections_.end());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000923 connections_.erase(iter);
honghaiz36f50e82016-06-01 15:57:03 -0700924 HandleConnectionDestroyed(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000925
Honghai Zhanga74363c2016-07-28 18:06:15 -0700926 // Ports time out after all connections fail if it is not marked as
927 // "keep alive until pruned."
honghaizd0b31432015-09-30 12:42:17 -0700928 // Note: If a new connection is added after this message is posted, but it
929 // fails and is removed before kPortTimeoutDelay, then this message will
Honghai Zhangb5db1ec2016-07-28 13:23:05 -0700930 // not cause the Port to be destroyed.
Honghai Zhanga74363c2016-07-28 18:06:15 -0700931 if (connections_.empty()) {
Honghai Zhangb5db1ec2016-07-28 13:23:05 -0700932 last_time_all_connections_removed_ = rtc::TimeMillis();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700933 thread_->PostDelayed(RTC_FROM_HERE, timeout_delay_, this,
934 MSG_DESTROY_IF_DEAD);
honghaizd0b31432015-09-30 12:42:17 -0700935 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000936}
937
938void Port::Destroy() {
nisseede5da42017-01-12 05:15:36 -0800939 RTC_DCHECK(connections_.empty());
Jonas Olssond7d762d2018-03-28 09:47:51 +0200940 RTC_LOG(LS_INFO) << ToString() << ": Port deleted";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000941 SignalDestroyed(this);
942 delete this;
943}
944
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000945const std::string Port::username_fragment() const {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700946 return ice_username_fragment_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000947}
948
Qingsi Wang6e641e62018-04-11 20:14:17 -0700949void Port::CopyPortInformationToPacketInfo(rtc::PacketInfo* info) const {
950 info->protocol = ConvertProtocolTypeToPacketInfoProtocolType(GetProtocol());
951 info->network_id = Network()->id();
952}
953
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000954// A ConnectionRequest is a simple STUN ping used to determine writability.
955class ConnectionRequest : public StunRequest {
956 public:
957 explicit ConnectionRequest(Connection* connection)
958 : StunRequest(new IceMessage()),
959 connection_(connection) {
960 }
961
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700962 void Prepare(StunMessage* request) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000963 request->SetType(STUN_BINDING_REQUEST);
964 std::string username;
965 connection_->port()->CreateStunUsername(
966 connection_->remote_candidate().username(), &username);
967 request->AddAttribute(
zsteinf42cc9d2017-03-27 16:17:19 -0700968 rtc::MakeUnique<StunByteStringAttribute>(STUN_ATTR_USERNAME, username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000969
970 // connection_ already holds this ping, so subtract one from count.
971 if (connection_->port()->send_retransmit_count_attribute()) {
zsteinf42cc9d2017-03-27 16:17:19 -0700972 request->AddAttribute(rtc::MakeUnique<StunUInt32Attribute>(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000973 STUN_ATTR_RETRANSMIT_COUNT,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200974 static_cast<uint32_t>(connection_->pings_since_last_response_.size() -
975 1)));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000976 }
honghaiza0c44ea2016-03-23 16:07:48 -0700977 uint32_t network_info = connection_->port()->Network()->id();
978 network_info = (network_info << 16) | connection_->port()->network_cost();
zsteinf42cc9d2017-03-27 16:17:19 -0700979 request->AddAttribute(rtc::MakeUnique<StunUInt32Attribute>(
980 STUN_ATTR_NETWORK_INFO, network_info));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000981
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700982 // Adding ICE_CONTROLLED or ICE_CONTROLLING attribute based on the role.
983 if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLING) {
zsteinf42cc9d2017-03-27 16:17:19 -0700984 request->AddAttribute(rtc::MakeUnique<StunUInt64Attribute>(
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700985 STUN_ATTR_ICE_CONTROLLING, connection_->port()->IceTiebreaker()));
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700986 // We should have either USE_CANDIDATE attribute or ICE_NOMINATION
987 // attribute but not both. That was enforced in p2ptransportchannel.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700988 if (connection_->use_candidate_attr()) {
zsteinf42cc9d2017-03-27 16:17:19 -0700989 request->AddAttribute(
990 rtc::MakeUnique<StunByteStringAttribute>(STUN_ATTR_USE_CANDIDATE));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000991 }
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700992 if (connection_->nomination() &&
993 connection_->nomination() != connection_->acked_nomination()) {
zsteinf42cc9d2017-03-27 16:17:19 -0700994 request->AddAttribute(rtc::MakeUnique<StunUInt32Attribute>(
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700995 STUN_ATTR_NOMINATION, connection_->nomination()));
996 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700997 } else if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLED) {
zsteinf42cc9d2017-03-27 16:17:19 -0700998 request->AddAttribute(rtc::MakeUnique<StunUInt64Attribute>(
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700999 STUN_ATTR_ICE_CONTROLLED, connection_->port()->IceTiebreaker()));
1000 } else {
nissec80e7412017-01-11 05:56:46 -08001001 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001002 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001003
1004 // Adding PRIORITY Attribute.
1005 // Changing the type preference to Peer Reflexive and local preference
1006 // and component id information is unchanged from the original priority.
1007 // priority = (2^24)*(type preference) +
1008 // (2^8)*(local preference) +
1009 // (2^0)*(256 - component ID)
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001010 uint32_t type_preference =
1011 (connection_->local_candidate().protocol() == TCP_PROTOCOL_NAME)
1012 ? ICE_TYPE_PREFERENCE_PRFLX_TCP
1013 : ICE_TYPE_PREFERENCE_PRFLX;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001014 uint32_t prflx_priority =
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001015 type_preference << 24 |
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001016 (connection_->local_candidate().priority() & 0x00FFFFFF);
zsteinf42cc9d2017-03-27 16:17:19 -07001017 request->AddAttribute(rtc::MakeUnique<StunUInt32Attribute>(
1018 STUN_ATTR_PRIORITY, prflx_priority));
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001019
1020 // Adding Message Integrity attribute.
1021 request->AddMessageIntegrity(connection_->remote_candidate().password());
1022 // Adding Fingerprint.
1023 request->AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001024 }
1025
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001026 void OnResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001027 connection_->OnConnectionRequestResponse(this, response);
1028 }
1029
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001030 void OnErrorResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001031 connection_->OnConnectionRequestErrorResponse(this, response);
1032 }
1033
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001034 void OnTimeout() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001035 connection_->OnConnectionRequestTimeout(this);
1036 }
1037
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001038 void OnSent() override {
1039 connection_->OnConnectionRequestSent(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001040 // Each request is sent only once. After a single delay , the request will
1041 // time out.
1042 timeout_ = true;
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001043 }
1044
1045 int resend_delay() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001046 return CONNECTION_RESPONSE_TIMEOUT;
1047 }
1048
1049 private:
1050 Connection* connection_;
1051};
1052
1053//
1054// Connection
1055//
1056
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001057Connection::Connection(Port* port,
1058 size_t index,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001059 const Candidate& remote_candidate)
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001060 : port_(port),
1061 local_candidate_index_(index),
1062 remote_candidate_(remote_candidate),
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001063 recv_rate_tracker_(100, 10u),
1064 send_rate_tracker_(100, 10u),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001065 write_state_(STATE_WRITE_INIT),
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001066 receiving_(false),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001067 connected_(true),
1068 pruned_(false),
1069 use_candidate_attr_(false),
1070 remote_ice_mode_(ICEMODE_FULL),
1071 requests_(port->thread()),
1072 rtt_(DEFAULT_RTT),
1073 last_ping_sent_(0),
1074 last_ping_received_(0),
1075 last_data_received_(0),
1076 last_ping_response_received_(0),
zsteinabbacbf2017-03-20 10:53:12 -07001077 packet_loss_estimator_(kConsiderPacketLostAfter, kForgetPacketAfter),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001078 reported_(false),
hbos06495bc2017-01-02 08:08:18 -08001079 state_(IceCandidatePairState::WAITING),
nisse1bffc1d2016-05-02 08:18:55 -07001080 time_created_ms_(rtc::TimeMillis()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001081 // All of our connections start in WAITING state.
1082 // TODO(mallinath) - Start connections from STATE_FROZEN.
1083 // Wire up to send stun packets
1084 requests_.SignalSendPacket.connect(this, &Connection::OnSendStunPacket);
Qingsi Wang93a84392018-01-30 17:13:09 -08001085 hash_ = static_cast<uint32_t>(std::hash<std::string>{}(ToString()));
Jonas Olssond7d762d2018-03-28 09:47:51 +02001086 RTC_LOG(LS_INFO) << ToString() << ": Connection created";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001087}
1088
1089Connection::~Connection() {
1090}
1091
1092const Candidate& Connection::local_candidate() const {
nisseede5da42017-01-12 05:15:36 -08001093 RTC_DCHECK(local_candidate_index_ < port_->Candidates().size());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001094 return port_->Candidates()[local_candidate_index_];
1095}
1096
Honghai Zhangcc411c02016-03-29 17:27:21 -07001097const Candidate& Connection::remote_candidate() const {
1098 return remote_candidate_;
1099}
1100
Peter Boström0c4e06b2015-10-07 12:23:21 +02001101uint64_t Connection::priority() const {
1102 uint64_t priority = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001103 // RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs
1104 // Let G be the priority for the candidate provided by the controlling
1105 // agent. Let D be the priority for the candidate provided by the
1106 // controlled agent.
1107 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
1108 IceRole role = port_->GetIceRole();
1109 if (role != ICEROLE_UNKNOWN) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001110 uint32_t g = 0;
1111 uint32_t d = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001112 if (role == ICEROLE_CONTROLLING) {
1113 g = local_candidate().priority();
1114 d = remote_candidate_.priority();
1115 } else {
1116 g = remote_candidate_.priority();
1117 d = local_candidate().priority();
1118 }
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00001119 priority = std::min(g, d);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001120 priority = priority << 32;
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00001121 priority += 2 * std::max(g, d) + (g > d ? 1 : 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001122 }
1123 return priority;
1124}
1125
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001126void Connection::set_write_state(WriteState value) {
1127 WriteState old_value = write_state_;
1128 write_state_ = value;
1129 if (value != old_value) {
Jonas Olssond7d762d2018-03-28 09:47:51 +02001130 RTC_LOG(LS_VERBOSE) << ToString()
1131 << ": set_write_state from: " << old_value << " to "
1132 << value;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001133 SignalStateChange(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001134 }
1135}
1136
honghaiz9ad0db52016-07-14 19:30:28 -07001137void Connection::UpdateReceiving(int64_t now) {
Qingsi Wangf82644c92018-04-16 16:47:32 -07001138 bool receiving;
1139 if (last_ping_sent() < last_ping_response_received()) {
1140 // We consider any candidate pair that has its last connectivity check
1141 // acknowledged by a response as receiving, particularly for backup
1142 // candidate pairs that send checks at a much slower pace than the selected
1143 // one. Otherwise, a backup candidate pair constantly becomes not receiving
1144 // as a side effect of a long ping interval, since we do not have a separate
1145 // receiving timeout for backup candidate pairs. See
1146 // IceConfig.ice_backup_candidate_pair_ping_interval,
1147 // IceConfig.ice_connection_receiving_timeout and their default value.
1148 receiving = true;
1149 } else {
1150 receiving =
1151 last_received() > 0 && now <= last_received() + receiving_timeout();
1152 }
honghaiz9ad0db52016-07-14 19:30:28 -07001153 if (receiving_ == receiving) {
1154 return;
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001155 }
Jonas Olssond7d762d2018-03-28 09:47:51 +02001156 RTC_LOG(LS_VERBOSE) << ToString() << ": set_receiving to "
1157 << receiving;
honghaiz9ad0db52016-07-14 19:30:28 -07001158 receiving_ = receiving;
1159 receiving_unchanged_since_ = now;
1160 SignalStateChange(this);
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001161}
1162
hbos06495bc2017-01-02 08:08:18 -08001163void Connection::set_state(IceCandidatePairState state) {
1164 IceCandidatePairState old_state = state_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001165 state_ = state;
1166 if (state != old_state) {
Jonas Olssond7d762d2018-03-28 09:47:51 +02001167 RTC_LOG(LS_VERBOSE) << ToString() << ": set_state";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001168 }
1169}
1170
1171void Connection::set_connected(bool value) {
1172 bool old_value = connected_;
1173 connected_ = value;
1174 if (value != old_value) {
Jonas Olssond7d762d2018-03-28 09:47:51 +02001175 RTC_LOG(LS_VERBOSE) << ToString()
1176 << ": Change connected_ to " << value;
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001177 SignalStateChange(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001178 }
1179}
1180
1181void Connection::set_use_candidate_attr(bool enable) {
1182 use_candidate_attr_ = enable;
1183}
1184
Qingsi Wang22e623a2018-03-13 10:53:57 -07001185int Connection::unwritable_timeout() const {
1186 return unwritable_timeout_.value_or(CONNECTION_WRITE_CONNECT_TIMEOUT);
1187}
1188
1189int Connection::unwritable_min_checks() const {
1190 return unwritable_min_checks_.value_or(CONNECTION_WRITE_CONNECT_FAILURES);
1191}
1192
Qingsi Wang866e08d2018-03-22 17:54:23 -07001193int Connection::receiving_timeout() const {
1194 return receiving_timeout_.value_or(WEAK_CONNECTION_RECEIVE_TIMEOUT);
1195}
1196
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001197void Connection::OnSendStunPacket(const void* data, size_t size,
1198 StunRequest* req) {
1199 rtc::PacketOptions options(port_->DefaultDscpValue());
Qingsi Wang6e641e62018-04-11 20:14:17 -07001200 options.info_signaled_after_sent.packet_type =
1201 rtc::PacketType::kIceConnectivityCheck;
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001202 auto err = port_->SendTo(
1203 data, size, remote_candidate_.address(), options, false);
1204 if (err < 0) {
Jonas Olssond7d762d2018-03-28 09:47:51 +02001205 RTC_LOG(LS_WARNING) << ToString()
1206 << ": Failed to send STUN ping "
1207 " err="
1208 << err << " id=" << rtc::hex_encode(req->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001209 }
1210}
1211
1212void Connection::OnReadPacket(
1213 const char* data, size_t size, const rtc::PacketTime& packet_time) {
kwiberg3ec46792016-04-27 07:22:53 -07001214 std::unique_ptr<IceMessage> msg;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001215 std::string remote_ufrag;
1216 const rtc::SocketAddress& addr(remote_candidate_.address());
kwiberg6baec032016-03-15 11:09:39 -07001217 if (!port_->GetStunMessage(data, size, addr, &msg, &remote_ufrag)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001218 // The packet did not parse as a valid STUN message
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001219 // This is a data packet, pass it along.
nisse1bffc1d2016-05-02 08:18:55 -07001220 last_data_received_ = rtc::TimeMillis();
honghaiz9ad0db52016-07-14 19:30:28 -07001221 UpdateReceiving(last_data_received_);
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001222 recv_rate_tracker_.AddSamples(size);
1223 SignalReadPacket(this, data, size, packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001224
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001225 // If timed out sending writability checks, start up again
1226 if (!pruned_ && (write_state_ == STATE_WRITE_TIMEOUT)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001227 RTC_LOG(LS_WARNING)
1228 << "Received a data packet on a timed-out Connection. "
Jonas Olssond7d762d2018-03-28 09:47:51 +02001229 "Resetting state to STATE_WRITE_INIT.";
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001230 set_write_state(STATE_WRITE_INIT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001231 }
1232 } else if (!msg) {
1233 // The packet was STUN, but failed a check and was handled internally.
1234 } else {
1235 // The packet is STUN and passed the Port checks.
1236 // Perform our own checks to ensure this packet is valid.
honghaizd0b31432015-09-30 12:42:17 -07001237 // If this is a STUN request, then update the receiving bit and respond.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001238 // If this is a STUN response, then update the writable bit.
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001239 // Log at LS_INFO if we receive a ping on an unwritable connection.
1240 rtc::LoggingSeverity sev = (!writable() ? rtc::LS_INFO : rtc::LS_VERBOSE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001241 switch (msg->type()) {
1242 case STUN_BINDING_REQUEST:
Jonas Olssond7d762d2018-03-28 09:47:51 +02001243 RTC_LOG_V(sev) << ToString()
1244 << ": Received STUN ping, id="
1245 << rtc::hex_encode(msg->transaction_id());
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001246
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001247 if (remote_ufrag == remote_candidate_.username()) {
honghaiz9b5ee9c2015-11-11 13:19:17 -08001248 HandleBindingRequest(msg.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001249 } else {
1250 // The packet had the right local username, but the remote username
1251 // was not the right one for the remote address.
Jonas Olssond7d762d2018-03-28 09:47:51 +02001252 RTC_LOG(LS_ERROR)
1253 << ToString()
1254 << ": Received STUN request with bad remote username "
1255 << remote_ufrag;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001256 port_->SendBindingErrorResponse(msg.get(), addr,
1257 STUN_ERROR_UNAUTHORIZED,
1258 STUN_ERROR_REASON_UNAUTHORIZED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001259 }
1260 break;
1261
1262 // Response from remote peer. Does it match request sent?
1263 // This doesn't just check, it makes callbacks if transaction
1264 // id's match.
1265 case STUN_BINDING_RESPONSE:
1266 case STUN_BINDING_ERROR_RESPONSE:
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001267 if (msg->ValidateMessageIntegrity(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001268 data, size, remote_candidate().password())) {
1269 requests_.CheckResponse(msg.get());
1270 }
1271 // Otherwise silently discard the response message.
1272 break;
1273
honghaizd0b31432015-09-30 12:42:17 -07001274 // Remote end point sent an STUN indication instead of regular binding
1275 // request. In this case |last_ping_received_| will be updated but no
1276 // response will be sent.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001277 case STUN_BINDING_INDICATION:
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001278 ReceivedPing();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001279 break;
1280
1281 default:
nissec80e7412017-01-11 05:56:46 -08001282 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001283 break;
1284 }
1285 }
1286}
1287
honghaiz9b5ee9c2015-11-11 13:19:17 -08001288void Connection::HandleBindingRequest(IceMessage* msg) {
1289 // This connection should now be receiving.
1290 ReceivedPing();
1291
1292 const rtc::SocketAddress& remote_addr = remote_candidate_.address();
1293 const std::string& remote_ufrag = remote_candidate_.username();
1294 // Check for role conflicts.
1295 if (!port_->MaybeIceRoleConflict(remote_addr, msg, remote_ufrag)) {
1296 // Received conflicting role from the peer.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001297 RTC_LOG(LS_INFO) << "Received conflicting role from the peer.";
honghaiz9b5ee9c2015-11-11 13:19:17 -08001298 return;
1299 }
1300
zhihuang5ecf16c2016-06-01 17:09:15 -07001301 stats_.recv_ping_requests++;
Qingsi Wang93a84392018-01-30 17:13:09 -08001302 LogCandidatePairEvent(webrtc::IceCandidatePairEventType::kCheckReceived);
zhihuang5ecf16c2016-06-01 17:09:15 -07001303
honghaiz9b5ee9c2015-11-11 13:19:17 -08001304 // This is a validated stun request from remote peer.
1305 port_->SendBindingResponse(msg, remote_addr);
1306
1307 // If it timed out on writing check, start up again
1308 if (!pruned_ && write_state_ == STATE_WRITE_TIMEOUT) {
1309 set_write_state(STATE_WRITE_INIT);
1310 }
1311
1312 if (port_->GetIceRole() == ICEROLE_CONTROLLED) {
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001313 const StunUInt32Attribute* nomination_attr =
1314 msg->GetUInt32(STUN_ATTR_NOMINATION);
1315 uint32_t nomination = 0;
1316 if (nomination_attr) {
1317 nomination = nomination_attr->value();
1318 if (nomination == 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001319 RTC_LOG(LS_ERROR) << "Invalid nomination: " << nomination;
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001320 }
1321 } else {
1322 const StunByteStringAttribute* use_candidate_attr =
1323 msg->GetByteString(STUN_ATTR_USE_CANDIDATE);
1324 if (use_candidate_attr) {
1325 nomination = 1;
1326 }
1327 }
1328 // We don't un-nominate a connection, so we only keep a larger nomination.
1329 if (nomination > remote_nomination_) {
1330 set_remote_nomination(nomination);
honghaiz9b5ee9c2015-11-11 13:19:17 -08001331 SignalNominated(this);
1332 }
1333 }
Honghai Zhang351d77b2016-05-20 15:08:29 -07001334 // Set the remote cost if the network_info attribute is available.
1335 // Note: If packets are re-ordered, we may get incorrect network cost
1336 // temporarily, but it should get the correct value shortly after that.
1337 const StunUInt32Attribute* network_attr =
1338 msg->GetUInt32(STUN_ATTR_NETWORK_INFO);
1339 if (network_attr) {
1340 uint32_t network_info = network_attr->value();
1341 uint16_t network_cost = static_cast<uint16_t>(network_info);
1342 if (network_cost != remote_candidate_.network_cost()) {
1343 remote_candidate_.set_network_cost(network_cost);
1344 // Network cost change will affect the connection ranking, so signal
1345 // state change to force a re-sort in P2PTransportChannel.
1346 SignalStateChange(this);
1347 }
1348 }
honghaiz9b5ee9c2015-11-11 13:19:17 -08001349}
1350
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001351void Connection::OnReadyToSend() {
deadbeefdd7fb432016-09-30 15:16:48 -07001352 SignalReadyToSend(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001353}
1354
1355void Connection::Prune() {
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001356 if (!pruned_ || active()) {
Jonas Olssond7d762d2018-03-28 09:47:51 +02001357 RTC_LOG(LS_INFO) << ToString() << ": Connection pruned";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001358 pruned_ = true;
1359 requests_.Clear();
1360 set_write_state(STATE_WRITE_TIMEOUT);
1361 }
1362}
1363
1364void Connection::Destroy() {
nisse7eaa4ea2017-05-08 05:25:41 -07001365 // TODO(deadbeef, nisse): This may leak if an application closes a
1366 // PeerConnection and then quickly destroys the PeerConnectionFactory (along
1367 // with the networking thread on which this message is posted). Also affects
1368 // tests, with a workaround in
1369 // AutoSocketServerThread::~AutoSocketServerThread.
Jonas Olssond7d762d2018-03-28 09:47:51 +02001370 RTC_LOG(LS_VERBOSE) << ToString()
1371 << ": Connection destroyed";
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001372 port_->thread()->Post(RTC_FROM_HERE, this, MSG_DELETE);
Bjorn Terelius59b4e3e2018-05-30 17:14:08 +02001373 LogCandidatePairConfig(webrtc::IceCandidatePairConfigType::kDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001374}
1375
deadbeef376e1232015-11-25 09:00:08 -08001376void Connection::FailAndDestroy() {
hbos06495bc2017-01-02 08:08:18 -08001377 set_state(IceCandidatePairState::FAILED);
deadbeef376e1232015-11-25 09:00:08 -08001378 Destroy();
1379}
1380
honghaiz079a7a12016-06-22 16:26:29 -07001381void Connection::FailAndPrune() {
hbos06495bc2017-01-02 08:08:18 -08001382 set_state(IceCandidatePairState::FAILED);
honghaiz079a7a12016-06-22 16:26:29 -07001383 Prune();
1384}
1385
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001386void Connection::PrintPingsSinceLastResponse(std::string* s, size_t max) {
1387 std::ostringstream oss;
1388 oss << std::boolalpha;
1389 if (pings_since_last_response_.size() > max) {
1390 for (size_t i = 0; i < max; i++) {
1391 const SentPing& ping = pings_since_last_response_[i];
1392 oss << rtc::hex_encode(ping.id) << " ";
1393 }
1394 oss << "... " << (pings_since_last_response_.size() - max) << " more";
1395 } else {
1396 for (const SentPing& ping : pings_since_last_response_) {
1397 oss << rtc::hex_encode(ping.id) << " ";
1398 }
1399 }
1400 *s = oss.str();
1401}
1402
honghaiz34b11eb2016-03-16 08:55:44 -07001403void Connection::UpdateState(int64_t now) {
1404 int rtt = ConservativeRTTEstimate(rtt_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001405
Mirko Bonadei675513b2017-11-09 11:09:25 +01001406 if (RTC_LOG_CHECK_LEVEL(LS_VERBOSE)) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001407 std::string pings;
1408 PrintPingsSinceLastResponse(&pings, 5);
Jonas Olssond7d762d2018-03-28 09:47:51 +02001409 RTC_LOG(LS_VERBOSE) << ToString()
1410 << ": UpdateState()"
1411 ", ms since last received response="
1412 << now - last_ping_response_received_
1413 << ", ms since last received data="
1414 << now - last_data_received_ << ", rtt=" << rtt
1415 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001416 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001417
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001418 // Check the writable state. (The order of these checks is important.)
1419 //
1420 // Before becoming unwritable, we allow for a fixed number of pings to fail
1421 // (i.e., receive no response). We also have to give the response time to
1422 // get back, so we include a conservative estimate of this.
1423 //
1424 // Before timing out writability, we give a fixed amount of time. This is to
1425 // allow for changes in network conditions.
1426
1427 if ((write_state_ == STATE_WRITABLE) &&
Qingsi Wang22e623a2018-03-13 10:53:57 -07001428 TooManyFailures(pings_since_last_response_, unwritable_min_checks(), rtt,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001429 now) &&
Qingsi Wang22e623a2018-03-13 10:53:57 -07001430 TooLongWithoutResponse(pings_since_last_response_, unwritable_timeout(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001431 now)) {
Qingsi Wang22e623a2018-03-13 10:53:57 -07001432 uint32_t max_pings = unwritable_min_checks();
Jonas Olssond7d762d2018-03-28 09:47:51 +02001433 RTC_LOG(LS_INFO) << ToString() << ": Unwritable after "
1434 << max_pings << " ping failures and "
1435 << now - pings_since_last_response_[0].sent_time
1436 << " ms without a response,"
1437 " ms since last received ping="
1438 << now - last_ping_received_
1439 << " ms since last received data="
1440 << now - last_data_received_ << " rtt=" << rtt;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001441 set_write_state(STATE_WRITE_UNRELIABLE);
1442 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001443 if ((write_state_ == STATE_WRITE_UNRELIABLE ||
1444 write_state_ == STATE_WRITE_INIT) &&
1445 TooLongWithoutResponse(pings_since_last_response_,
1446 CONNECTION_WRITE_TIMEOUT,
1447 now)) {
Jonas Olssond7d762d2018-03-28 09:47:51 +02001448 RTC_LOG(LS_INFO) << ToString() << ": Timed out after "
1449 << now - pings_since_last_response_[0].sent_time
1450 << " ms without a response, rtt=" << rtt;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001451 set_write_state(STATE_WRITE_TIMEOUT);
1452 }
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001453
honghaiz9ad0db52016-07-14 19:30:28 -07001454 // Update the receiving state.
1455 UpdateReceiving(now);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001456 if (dead(now)) {
1457 Destroy();
1458 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001459}
1460
honghaiz34b11eb2016-03-16 08:55:44 -07001461void Connection::Ping(int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001462 last_ping_sent_ = now;
Bjorn Terelius59b4e3e2018-05-30 17:14:08 +02001463 ConnectionRequest* req = new ConnectionRequest(this);
deadbeef86c40a12017-06-28 09:37:23 -07001464 // If not using renomination, we use "1" to mean "nominated" and "0" to mean
1465 // "not nominated". If using renomination, values greater than 1 are used for
1466 // re-nominated pairs.
1467 int nomination = use_candidate_attr_ ? 1 : 0;
1468 if (nomination_ > 0) {
1469 nomination = nomination_;
1470 }
1471 pings_since_last_response_.push_back(SentPing(req->id(), now, nomination));
zsteinabbacbf2017-03-20 10:53:12 -07001472 packet_loss_estimator_.ExpectResponse(req->id(), now);
Jonas Olssond7d762d2018-03-28 09:47:51 +02001473 RTC_LOG(LS_VERBOSE) << ToString()
1474 << ": Sending STUN ping, id="
1475 << rtc::hex_encode(req->id())
1476 << ", nomination=" << nomination_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001477 requests_.Send(req);
hbos06495bc2017-01-02 08:08:18 -08001478 state_ = IceCandidatePairState::IN_PROGRESS;
honghaiz524ecc22016-05-25 12:48:31 -07001479 num_pings_sent_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001480}
1481
1482void Connection::ReceivedPing() {
nisse1bffc1d2016-05-02 08:18:55 -07001483 last_ping_received_ = rtc::TimeMillis();
honghaiz9ad0db52016-07-14 19:30:28 -07001484 UpdateReceiving(last_ping_received_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001485}
1486
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001487void Connection::ReceivedPingResponse(int rtt, const std::string& request_id) {
hbosbf8d3e52017-02-28 06:34:47 -08001488 RTC_DCHECK_GE(rtt, 0);
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001489 // We've already validated that this is a STUN binding response with
1490 // the correct local and remote username for this connection.
1491 // So if we're not already, become writable. We may be bringing a pruned
1492 // connection back to life, but if we don't really want it, we can always
1493 // prune it again.
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001494 auto iter = std::find_if(
1495 pings_since_last_response_.begin(), pings_since_last_response_.end(),
1496 [request_id](const SentPing& ping) { return ping.id == request_id; });
1497 if (iter != pings_since_last_response_.end() &&
1498 iter->nomination > acked_nomination_) {
1499 acked_nomination_ = iter->nomination;
1500 }
1501
hbosbf8d3e52017-02-28 06:34:47 -08001502 total_round_trip_time_ms_ += rtt;
Oskar Sundbom903dcd72017-11-16 10:55:57 +01001503 current_round_trip_time_ms_ = static_cast<uint32_t>(rtt);
hbosbf8d3e52017-02-28 06:34:47 -08001504
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001505 pings_since_last_response_.clear();
honghaiz9ad0db52016-07-14 19:30:28 -07001506 last_ping_response_received_ = rtc::TimeMillis();
1507 UpdateReceiving(last_ping_response_received_);
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001508 set_write_state(STATE_WRITABLE);
hbos06495bc2017-01-02 08:08:18 -08001509 set_state(IceCandidatePairState::SUCCEEDED);
skvladd0309122017-02-02 17:18:37 -08001510 if (rtt_samples_ > 0) {
Qingsi Wang72a43a12018-02-20 16:03:18 -08001511 rtt_ = rtc::GetNextMovingAverage(rtt_, rtt, RTT_RATIO);
skvladd0309122017-02-02 17:18:37 -08001512 } else {
1513 rtt_ = rtt;
1514 }
zhihuang435264a2016-06-21 11:28:38 -07001515 rtt_samples_++;
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001516}
1517
honghaiz34b11eb2016-03-16 08:55:44 -07001518bool Connection::dead(int64_t now) const {
honghaiz37389b42016-01-04 21:57:33 -08001519 if (last_received() > 0) {
1520 // If it has ever received anything, we keep it alive until it hasn't
1521 // received anything for DEAD_CONNECTION_RECEIVE_TIMEOUT. This covers the
1522 // normal case of a successfully used connection that stops working. This
1523 // also allows a remote peer to continue pinging over a locally inactive
1524 // (pruned) connection.
1525 return (now > (last_received() + DEAD_CONNECTION_RECEIVE_TIMEOUT));
1526 }
1527
1528 if (active()) {
1529 // If it has never received anything, keep it alive as long as it is
1530 // actively pinging and not pruned. Otherwise, the connection might be
1531 // deleted before it has a chance to ping. This is the normal case for a
1532 // new connection that is pinging but hasn't received anything yet.
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001533 return false;
1534 }
1535
honghaiz37389b42016-01-04 21:57:33 -08001536 // If it has never received anything and is not actively pinging (pruned), we
1537 // keep it around for at least MIN_CONNECTION_LIFETIME to prevent connections
1538 // from being pruned too quickly during a network change event when two
1539 // networks would be up simultaneously but only for a brief period.
1540 return now > (time_created_ms_ + MIN_CONNECTION_LIFETIME);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001541}
1542
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001543bool Connection::stable(int64_t now) const {
zhihuang435264a2016-06-21 11:28:38 -07001544 // A connection is stable if it's RTT has converged and it isn't missing any
1545 // responses. We should send pings at a higher rate until the RTT converges
1546 // and whenever a ping response is missing (so that we can detect
1547 // unwritability faster)
1548 return rtt_converged() && !missing_responses(now);
1549}
1550
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +00001551std::string Connection::ToDebugId() const {
1552 std::stringstream ss;
1553 ss << std::hex << this;
1554 return ss.str();
1555}
1556
honghaize1a0c942016-02-16 14:54:56 -08001557uint32_t Connection::ComputeNetworkCost() const {
1558 // TODO(honghaiz): Will add rtt as part of the network cost.
Honghai Zhang351d77b2016-05-20 15:08:29 -07001559 return port()->network_cost() + remote_candidate_.network_cost();
honghaize1a0c942016-02-16 14:54:56 -08001560}
1561
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001562std::string Connection::ToString() const {
1563 const char CONNECT_STATE_ABBREV[2] = {
1564 '-', // not connected (false)
1565 'C', // connected (true)
1566 };
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001567 const char RECEIVE_STATE_ABBREV[2] = {
1568 '-', // not receiving (false)
1569 'R', // receiving (true)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001570 };
1571 const char WRITE_STATE_ABBREV[4] = {
1572 'W', // STATE_WRITABLE
1573 'w', // STATE_WRITE_UNRELIABLE
1574 '-', // STATE_WRITE_INIT
1575 'x', // STATE_WRITE_TIMEOUT
1576 };
1577 const std::string ICESTATE[4] = {
1578 "W", // STATE_WAITING
1579 "I", // STATE_INPROGRESS
1580 "S", // STATE_SUCCEEDED
1581 "F" // STATE_FAILED
1582 };
Qingsi Wang10a0e512018-05-16 13:37:03 -07001583 const std::string SELECTED_STATE_ABBREV[2] = {
1584 "-", // candidate pair not selected (false)
1585 "S", // selected (true)
1586 };
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001587 const Candidate& local = local_candidate();
1588 const Candidate& remote = remote_candidate();
1589 std::stringstream ss;
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001590 ss << "Conn[" << ToDebugId() << ":" << port_->content_name() << ":"
Qingsi Wang10a0e512018-05-16 13:37:03 -07001591 << port_->Network()->ToString() << ":" << local.id() << ":"
1592 << local.component() << ":" << local.generation() << ":" << local.type()
1593 << ":" << local.protocol() << ":" << local.address().ToSensitiveString()
1594 << "->" << remote.id() << ":" << remote.component() << ":"
1595 << remote.priority() << ":" << remote.type() << ":" << remote.protocol()
1596 << ":" << remote.address().ToSensitiveString() << "|"
1597 << CONNECT_STATE_ABBREV[connected()] << RECEIVE_STATE_ABBREV[receiving()]
1598 << WRITE_STATE_ABBREV[write_state()] << ICESTATE[static_cast<int>(state())]
1599 << "|" << SELECTED_STATE_ABBREV[selected()] << "|" << remote_nomination()
1600 << "|" << nomination() << "|" << priority() << "|";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001601 if (rtt_ < DEFAULT_RTT) {
1602 ss << rtt_ << "]";
1603 } else {
1604 ss << "-]";
1605 }
1606 return ss.str();
1607}
1608
1609std::string Connection::ToSensitiveString() const {
1610 return ToString();
1611}
1612
Qingsi Wang93a84392018-01-30 17:13:09 -08001613const webrtc::IceCandidatePairDescription& Connection::ToLogDescription() {
1614 if (log_description_.has_value()) {
1615 return log_description_.value();
1616 }
1617 const Candidate& local = local_candidate();
1618 const Candidate& remote = remote_candidate();
1619 const rtc::Network* network = port()->Network();
1620 log_description_ = webrtc::IceCandidatePairDescription();
1621 log_description_->local_candidate_type =
1622 GetCandidateTypeByString(local.type());
1623 log_description_->local_relay_protocol =
1624 GetProtocolByString(local.relay_protocol());
1625 log_description_->local_network_type = ConvertNetworkType(network->type());
1626 log_description_->local_address_family =
1627 GetAddressFamilyByInt(local.address().family());
1628 log_description_->remote_candidate_type =
1629 GetCandidateTypeByString(remote.type());
1630 log_description_->remote_address_family =
1631 GetAddressFamilyByInt(remote.address().family());
1632 log_description_->candidate_pair_protocol =
1633 GetProtocolByString(local.protocol());
1634 return log_description_.value();
1635}
1636
Bjorn Terelius59b4e3e2018-05-30 17:14:08 +02001637void Connection::LogCandidatePairConfig(
1638 webrtc::IceCandidatePairConfigType type) {
1639 if (ice_event_log_ == nullptr) {
1640 return;
1641 }
1642 ice_event_log_->LogCandidatePairConfig(type, hash(), ToLogDescription());
1643}
1644
Qingsi Wang93a84392018-01-30 17:13:09 -08001645void Connection::LogCandidatePairEvent(webrtc::IceCandidatePairEventType type) {
1646 if (ice_event_log_ == nullptr) {
1647 return;
1648 }
Bjorn Terelius59b4e3e2018-05-30 17:14:08 +02001649 ice_event_log_->LogCandidatePairEvent(type, hash());
Qingsi Wang93a84392018-01-30 17:13:09 -08001650}
1651
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001652void Connection::OnConnectionRequestResponse(ConnectionRequest* request,
1653 StunMessage* response) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001654 // Log at LS_INFO if we receive a ping response on an unwritable
1655 // connection.
1656 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1657
honghaiz34b11eb2016-03-16 08:55:44 -07001658 int rtt = request->Elapsed();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001659
Mirko Bonadei675513b2017-11-09 11:09:25 +01001660 if (RTC_LOG_CHECK_LEVEL_V(sev)) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001661 std::string pings;
1662 PrintPingsSinceLastResponse(&pings, 5);
Jonas Olssond7d762d2018-03-28 09:47:51 +02001663 RTC_LOG_V(sev) << ToString()
1664 << ": Received STUN ping response, id="
1665 << rtc::hex_encode(request->id())
1666 << ", code=0" // Makes logging easier to parse.
1667 ", rtt="
1668 << rtt << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001669 }
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001670 ReceivedPingResponse(rtt, request->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001671
zsteinabbacbf2017-03-20 10:53:12 -07001672 int64_t time_received = rtc::TimeMillis();
1673 packet_loss_estimator_.ReceivedResponse(request->id(), time_received);
1674
zhihuang5ecf16c2016-06-01 17:09:15 -07001675 stats_.recv_ping_responses++;
Qingsi Wang93a84392018-01-30 17:13:09 -08001676 LogCandidatePairEvent(
1677 webrtc::IceCandidatePairEventType::kCheckResponseReceived);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001678
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001679 MaybeUpdateLocalCandidate(request, response);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001680}
1681
1682void Connection::OnConnectionRequestErrorResponse(ConnectionRequest* request,
1683 StunMessage* response) {
deadbeef996fc6b2017-04-26 09:21:22 -07001684 int error_code = response->GetErrorCodeValue();
Jonas Olssond7d762d2018-03-28 09:47:51 +02001685 RTC_LOG(LS_WARNING) << ToString()
1686 << ": Received STUN error response id="
1687 << rtc::hex_encode(request->id())
1688 << " code=" << error_code
1689 << " rtt=" << request->Elapsed();
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001690
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001691 if (error_code == STUN_ERROR_UNKNOWN_ATTRIBUTE ||
1692 error_code == STUN_ERROR_SERVER_ERROR ||
1693 error_code == STUN_ERROR_UNAUTHORIZED) {
1694 // Recoverable error, retry
1695 } else if (error_code == STUN_ERROR_STALE_CREDENTIALS) {
1696 // Race failure, retry
1697 } else if (error_code == STUN_ERROR_ROLE_CONFLICT) {
1698 HandleRoleConflictFromPeer();
1699 } else {
1700 // This is not a valid connection.
Jonas Olssond7d762d2018-03-28 09:47:51 +02001701 RTC_LOG(LS_ERROR) << ToString()
1702 << ": Received STUN error response, code=" << error_code
1703 << "; killing connection";
deadbeef376e1232015-11-25 09:00:08 -08001704 FailAndDestroy();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001705 }
1706}
1707
1708void Connection::OnConnectionRequestTimeout(ConnectionRequest* request) {
1709 // Log at LS_INFO if we miss a ping on a writable connection.
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001710 rtc::LoggingSeverity sev = writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
Jonas Olssond7d762d2018-03-28 09:47:51 +02001711 RTC_LOG_V(sev) << ToString() << ": Timing-out STUN ping "
1712 << rtc::hex_encode(request->id()) << " after "
1713 << request->Elapsed() << " ms";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001714}
1715
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001716void Connection::OnConnectionRequestSent(ConnectionRequest* request) {
1717 // Log at LS_INFO if we send a ping on an unwritable connection.
1718 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
Jonas Olssond7d762d2018-03-28 09:47:51 +02001719 RTC_LOG_V(sev) << ToString()
1720 << ": Sent STUN ping, id=" << rtc::hex_encode(request->id())
1721 << ", use_candidate=" << use_candidate_attr()
1722 << ", nomination=" << nomination();
zhihuang5ecf16c2016-06-01 17:09:15 -07001723 stats_.sent_ping_requests_total++;
Qingsi Wang93a84392018-01-30 17:13:09 -08001724 LogCandidatePairEvent(webrtc::IceCandidatePairEventType::kCheckSent);
zhihuang5ecf16c2016-06-01 17:09:15 -07001725 if (stats_.recv_ping_responses == 0) {
1726 stats_.sent_ping_requests_before_first_response++;
1727 }
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001728}
1729
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001730void Connection::HandleRoleConflictFromPeer() {
1731 port_->SignalRoleConflict(port_);
1732}
1733
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001734void Connection::MaybeSetRemoteIceParametersAndGeneration(
1735 const IceParameters& ice_params,
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001736 int generation) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001737 if (remote_candidate_.username() == ice_params.ufrag &&
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001738 remote_candidate_.password().empty()) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001739 remote_candidate_.set_password(ice_params.pwd);
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001740 }
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001741 // TODO(deadbeef): A value of '0' for the generation is used for both
1742 // generation 0 and "generation unknown". It should be changed to an
Danil Chapovalov00c71832018-06-15 15:58:38 +02001743 // absl::optional to fix this.
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001744 if (remote_candidate_.username() == ice_params.ufrag &&
1745 remote_candidate_.password() == ice_params.pwd &&
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001746 remote_candidate_.generation() == 0) {
1747 remote_candidate_.set_generation(generation);
1748 }
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001749}
1750
1751void Connection::MaybeUpdatePeerReflexiveCandidate(
1752 const Candidate& new_candidate) {
1753 if (remote_candidate_.type() == PRFLX_PORT_TYPE &&
1754 new_candidate.type() != PRFLX_PORT_TYPE &&
1755 remote_candidate_.protocol() == new_candidate.protocol() &&
1756 remote_candidate_.address() == new_candidate.address() &&
1757 remote_candidate_.username() == new_candidate.username() &&
1758 remote_candidate_.password() == new_candidate.password() &&
1759 remote_candidate_.generation() == new_candidate.generation()) {
1760 remote_candidate_ = new_candidate;
1761 }
1762}
1763
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001764void Connection::OnMessage(rtc::Message *pmsg) {
nisseede5da42017-01-12 05:15:36 -08001765 RTC_DCHECK(pmsg->message_id == MSG_DELETE);
Mirko Bonadei675513b2017-11-09 11:09:25 +01001766 RTC_LOG(LS_INFO) << "Connection deleted with number of pings sent: "
1767 << num_pings_sent_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001768 SignalDestroyed(this);
1769 delete this;
1770}
1771
honghaiz34b11eb2016-03-16 08:55:44 -07001772int64_t Connection::last_received() const {
Peter Thatcher54360512015-07-08 11:08:35 -07001773 return std::max(last_data_received_,
1774 std::max(last_ping_received_, last_ping_response_received_));
1775}
1776
zhihuang5ecf16c2016-06-01 17:09:15 -07001777ConnectionInfo Connection::stats() {
1778 stats_.recv_bytes_second = round(recv_rate_tracker_.ComputeRate());
1779 stats_.recv_total_bytes = recv_rate_tracker_.TotalSampleCount();
1780 stats_.sent_bytes_second = round(send_rate_tracker_.ComputeRate());
1781 stats_.sent_total_bytes = send_rate_tracker_.TotalSampleCount();
hbos06495bc2017-01-02 08:08:18 -08001782 stats_.receiving = receiving_;
1783 stats_.writable = write_state_ == STATE_WRITABLE;
1784 stats_.timeout = write_state_ == STATE_WRITE_TIMEOUT;
1785 stats_.new_connection = !reported_;
1786 stats_.rtt = rtt_;
1787 stats_.local_candidate = local_candidate();
1788 stats_.remote_candidate = remote_candidate();
1789 stats_.key = this;
1790 stats_.state = state_;
1791 stats_.priority = priority();
hbos92eaec62017-02-27 01:38:08 -08001792 stats_.nominated = nominated();
hbosbf8d3e52017-02-28 06:34:47 -08001793 stats_.total_round_trip_time_ms = total_round_trip_time_ms_;
1794 stats_.current_round_trip_time_ms = current_round_trip_time_ms_;
zhihuang5ecf16c2016-06-01 17:09:15 -07001795 return stats_;
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001796}
1797
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001798void Connection::MaybeUpdateLocalCandidate(ConnectionRequest* request,
1799 StunMessage* response) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001800 // RFC 5245
1801 // The agent checks the mapped address from the STUN response. If the
1802 // transport address does not match any of the local candidates that the
1803 // agent knows about, the mapped address represents a new candidate -- a
1804 // peer reflexive candidate.
1805 const StunAddressAttribute* addr =
1806 response->GetAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
1807 if (!addr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001808 RTC_LOG(LS_WARNING)
1809 << "Connection::OnConnectionRequestResponse - "
Jonas Olssond7d762d2018-03-28 09:47:51 +02001810 "No MAPPED-ADDRESS or XOR-MAPPED-ADDRESS found in the "
1811 "stun response message";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001812 return;
1813 }
1814
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001815 for (size_t i = 0; i < port_->Candidates().size(); ++i) {
1816 if (port_->Candidates()[i].address() == addr->GetAddress()) {
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001817 if (local_candidate_index_ != i) {
Jonas Olssond7d762d2018-03-28 09:47:51 +02001818 RTC_LOG(LS_INFO) << ToString()
1819 << ": Updating local candidate type to srflx.";
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001820 local_candidate_index_ = i;
1821 // SignalStateChange to force a re-sort in P2PTransportChannel as this
1822 // Connection's local candidate has changed.
1823 SignalStateChange(this);
1824 }
1825 return;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001826 }
1827 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001828
1829 // RFC 5245
1830 // Its priority is set equal to the value of the PRIORITY attribute
1831 // in the Binding request.
1832 const StunUInt32Attribute* priority_attr =
1833 request->msg()->GetUInt32(STUN_ATTR_PRIORITY);
1834 if (!priority_attr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001835 RTC_LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
Jonas Olssond7d762d2018-03-28 09:47:51 +02001836 "No STUN_ATTR_PRIORITY found in the "
1837 "stun response message";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001838 return;
1839 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001840 const uint32_t priority = priority_attr->value();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001841 std::string id = rtc::CreateRandomString(8);
1842
1843 Candidate new_local_candidate;
1844 new_local_candidate.set_id(id);
1845 new_local_candidate.set_component(local_candidate().component());
1846 new_local_candidate.set_type(PRFLX_PORT_TYPE);
1847 new_local_candidate.set_protocol(local_candidate().protocol());
1848 new_local_candidate.set_address(addr->GetAddress());
1849 new_local_candidate.set_priority(priority);
1850 new_local_candidate.set_username(local_candidate().username());
1851 new_local_candidate.set_password(local_candidate().password());
1852 new_local_candidate.set_network_name(local_candidate().network_name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001853 new_local_candidate.set_network_type(local_candidate().network_type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001854 new_local_candidate.set_related_address(local_candidate().address());
Taylor Brandstetterf7c15a92016-06-22 13:13:55 -07001855 new_local_candidate.set_generation(local_candidate().generation());
Honghai Zhang80f1db92016-01-27 11:54:45 -08001856 new_local_candidate.set_foundation(ComputeFoundation(
1857 PRFLX_PORT_TYPE, local_candidate().protocol(),
1858 local_candidate().relay_protocol(), local_candidate().address()));
honghaiza0c44ea2016-03-23 16:07:48 -07001859 new_local_candidate.set_network_id(local_candidate().network_id());
1860 new_local_candidate.set_network_cost(local_candidate().network_cost());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001861
1862 // Change the local candidate of this Connection to the new prflx candidate.
Jonas Olssond7d762d2018-03-28 09:47:51 +02001863 RTC_LOG(LS_INFO) << ToString()
1864 << ": Updating local candidate type to prflx.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001865 local_candidate_index_ = port_->AddPrflxCandidate(new_local_candidate);
1866
1867 // SignalStateChange to force a re-sort in P2PTransportChannel as this
1868 // Connection's local candidate has changed.
1869 SignalStateChange(this);
1870}
1871
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001872bool Connection::rtt_converged() const {
zhihuang435264a2016-06-21 11:28:38 -07001873 return rtt_samples_ > (RTT_RATIO + 1);
1874}
1875
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001876bool Connection::missing_responses(int64_t now) const {
zhihuang435264a2016-06-21 11:28:38 -07001877 if (pings_since_last_response_.empty()) {
1878 return false;
1879 }
1880
1881 int64_t waiting = now - pings_since_last_response_[0].sent_time;
1882 return waiting > 2 * rtt();
1883}
1884
deadbeef376e1232015-11-25 09:00:08 -08001885ProxyConnection::ProxyConnection(Port* port,
1886 size_t index,
1887 const Candidate& remote_candidate)
1888 : Connection(port, index, remote_candidate) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001889
1890int ProxyConnection::Send(const void* data, size_t size,
1891 const rtc::PacketOptions& options) {
zhihuang5ecf16c2016-06-01 17:09:15 -07001892 stats_.sent_total_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001893 int sent = port_->SendTo(data, size, remote_candidate_.address(),
1894 options, true);
1895 if (sent <= 0) {
nisseede5da42017-01-12 05:15:36 -08001896 RTC_DCHECK(sent < 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001897 error_ = port_->GetError();
zhihuang5ecf16c2016-06-01 17:09:15 -07001898 stats_.sent_discarded_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001899 } else {
Tim Psiaki63046262015-09-14 10:38:08 -07001900 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001901 }
1902 return sent;
1903}
1904
Steve Anton1cf1b7d2017-10-30 10:00:15 -07001905int ProxyConnection::GetError() {
1906 return error_;
1907}
1908
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001909} // namespace cricket