blob: 4421db2a2ec98ed69b22964909c86ac0f1ac1357 [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>
16#include <vector>
17
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "p2p/base/common.h"
19#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
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000064// We will restrict RTT estimates (when used for determining state) to be
65// within a reasonable range.
honghaiz34b11eb2016-03-16 08:55:44 -070066const int MINIMUM_RTT = 100; // 0.1 seconds
skvlad51072462017-02-02 11:50:14 -080067const int MAXIMUM_RTT = 60000; // 60 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000068
69// When we don't have any RTT data, we have to pick something reasonable. We
70// use a large value just in case the connection is really slow.
skvlad51072462017-02-02 11:50:14 -080071const int DEFAULT_RTT = 3000; // 3 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000072
73// Computes our estimate of the RTT given the current estimate.
honghaiz34b11eb2016-03-16 08:55:44 -070074inline int ConservativeRTTEstimate(int rtt) {
kwiberg07038562017-06-12 11:40:47 -070075 return rtc::SafeClamp(2 * rtt, MINIMUM_RTT, MAXIMUM_RTT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000076}
77
78// Weighting of the old rtt value to new data.
79const int RTT_RATIO = 3; // 3 : 1
80
pthatcher94a2f212017-02-08 14:42:22 -080081// The delay before we begin checking if this port is useless. We set
82// it to a little higher than a total STUN timeout.
83const int kPortTimeoutDelay = cricket::STUN_TOTAL_TIMEOUT + 5000;
zsteinabbacbf2017-03-20 10:53:12 -070084
85// For packet loss estimation.
86const int64_t kConsiderPacketLostAfter = 3000; // 3 seconds
87
88// For packet loss estimation.
89const int64_t kForgetPacketAfter = 30000; // 30 seconds
90
Honghai Zhang351d77b2016-05-20 15:08:29 -070091} // namespace
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000092
93namespace cricket {
94
zhihuang38989e52017-03-21 11:04:53 -070095// TODO(ronghuawu): Use "local", "srflx", "prflx" and "relay". But this requires
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000096// the signaling part be updated correspondingly as well.
97const char LOCAL_PORT_TYPE[] = "local";
98const char STUN_PORT_TYPE[] = "stun";
99const char PRFLX_PORT_TYPE[] = "prflx";
100const char RELAY_PORT_TYPE[] = "relay";
101
hnsl277b2502016-12-13 05:17:23 -0800102static const char* const PROTO_NAMES[] = {UDP_PROTOCOL_NAME, TCP_PROTOCOL_NAME,
103 SSLTCP_PROTOCOL_NAME,
104 TLS_PROTOCOL_NAME};
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000105
106const char* ProtoToString(ProtocolType proto) {
107 return PROTO_NAMES[proto];
108}
109
110bool StringToProto(const char* value, ProtocolType* proto) {
111 for (size_t i = 0; i <= PROTO_LAST; ++i) {
112 if (_stricmp(PROTO_NAMES[i], value) == 0) {
113 *proto = static_cast<ProtocolType>(i);
114 return true;
115 }
116 }
117 return false;
118}
119
120// RFC 6544, TCP candidate encoding rules.
121const int DISCARD_PORT = 9;
122const char TCPTYPE_ACTIVE_STR[] = "active";
123const char TCPTYPE_PASSIVE_STR[] = "passive";
124const char TCPTYPE_SIMOPEN_STR[] = "so";
125
126// Foundation: An arbitrary string that is the same for two candidates
127// that have the same type, base IP address, protocol (UDP, TCP,
128// etc.), and STUN or TURN server. If any of these are different,
129// then the foundation will be different. Two candidate pairs with
130// the same foundation pairs are likely to have similar network
131// characteristics. Foundations are used in the frozen algorithm.
Honghai Zhang80f1db92016-01-27 11:54:45 -0800132static std::string ComputeFoundation(const std::string& type,
133 const std::string& protocol,
134 const std::string& relay_protocol,
135 const rtc::SocketAddress& base_address) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000136 std::ostringstream ost;
Honghai Zhang80f1db92016-01-27 11:54:45 -0800137 ost << type << base_address.ipaddr().ToString() << protocol << relay_protocol;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200138 return rtc::ToString<uint32_t>(rtc::ComputeCrc32(ost.str()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000139}
140
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000141Port::Port(rtc::Thread* thread,
Honghai Zhangd00c0572016-06-28 09:44:47 -0700142 const std::string& type,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000143 rtc::PacketSocketFactory* factory,
144 rtc::Network* network,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000145 const std::string& username_fragment,
146 const std::string& password)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000147 : thread_(thread),
148 factory_(factory),
Honghai Zhangd00c0572016-06-28 09:44:47 -0700149 type_(type),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000150 send_retransmit_count_attribute_(false),
151 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000152 min_port_(0),
153 max_port_(0),
154 component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
155 generation_(0),
156 ice_username_fragment_(username_fragment),
157 password_(password),
158 timeout_delay_(kPortTimeoutDelay),
159 enable_port_packets_(false),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000160 ice_role_(ICEROLE_UNKNOWN),
161 tiebreaker_(0),
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700162 shared_socket_(true) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000163 Construct();
164}
165
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000166Port::Port(rtc::Thread* thread,
167 const std::string& type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000168 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000169 rtc::Network* network,
Steve Antonf2737d22017-10-31 16:27:34 -0700170 const rtc::IPAddress& ip,
171 const std::string& username_fragment,
172 const std::string& password)
173 : Port(thread, type, factory, network, username_fragment, password) {}
174
175Port::Port(rtc::Thread* thread,
176 const std::string& type,
177 rtc::PacketSocketFactory* factory,
178 rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200179 uint16_t min_port,
180 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000181 const std::string& username_fragment,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000182 const std::string& password)
183 : thread_(thread),
184 factory_(factory),
185 type_(type),
186 send_retransmit_count_attribute_(false),
187 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000188 min_port_(min_port),
189 max_port_(max_port),
190 component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
191 generation_(0),
192 ice_username_fragment_(username_fragment),
193 password_(password),
194 timeout_delay_(kPortTimeoutDelay),
195 enable_port_packets_(false),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000196 ice_role_(ICEROLE_UNKNOWN),
197 tiebreaker_(0),
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700198 shared_socket_(false) {
nisseede5da42017-01-12 05:15:36 -0800199 RTC_DCHECK(factory_ != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000200 Construct();
201}
202
203void Port::Construct() {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700204 // TODO(pthatcher): Remove this old behavior once we're sure no one
205 // relies on it. If the username_fragment and password are empty,
206 // we should just create one.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000207 if (ice_username_fragment_.empty()) {
nisseede5da42017-01-12 05:15:36 -0800208 RTC_DCHECK(password_.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000209 ice_username_fragment_ = rtc::CreateRandomString(ICE_UFRAG_LENGTH);
210 password_ = rtc::CreateRandomString(ICE_PWD_LENGTH);
211 }
Honghai Zhang351d77b2016-05-20 15:08:29 -0700212 network_->SignalTypeChanged.connect(this, &Port::OnNetworkTypeChanged);
213 network_cost_ = network_->GetCost();
honghaize1a0c942016-02-16 14:54:56 -0800214
Honghai Zhanga74363c2016-07-28 18:06:15 -0700215 thread_->PostDelayed(RTC_FROM_HERE, timeout_delay_, this,
216 MSG_DESTROY_IF_DEAD);
Honghai Zhang351d77b2016-05-20 15:08:29 -0700217 LOG_J(LS_INFO, this) << "Port created with network cost " << network_cost_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000218}
219
220Port::~Port() {
221 // Delete all of the remaining connections. We copy the list up front
222 // because each deletion will cause it to be modified.
223
224 std::vector<Connection*> list;
225
226 AddressMap::iterator iter = connections_.begin();
227 while (iter != connections_.end()) {
228 list.push_back(iter->second);
229 ++iter;
230 }
231
Peter Boström0c4e06b2015-10-07 12:23:21 +0200232 for (uint32_t i = 0; i < list.size(); i++)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000233 delete list[i];
234}
235
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700236const std::string& Port::Type() const {
237 return type_;
238}
239rtc::Network* Port::Network() const {
240 return network_;
241}
242
243IceRole Port::GetIceRole() const {
244 return ice_role_;
245}
246
247void Port::SetIceRole(IceRole role) {
248 ice_role_ = role;
249}
250
251void Port::SetIceTiebreaker(uint64_t tiebreaker) {
252 tiebreaker_ = tiebreaker;
253}
254uint64_t Port::IceTiebreaker() const {
255 return tiebreaker_;
256}
257
258bool Port::SharedSocket() const {
259 return shared_socket_;
260}
261
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700262void Port::SetIceParameters(int component,
263 const std::string& username_fragment,
264 const std::string& password) {
265 component_ = component;
266 ice_username_fragment_ = username_fragment;
267 password_ = password;
268 for (Candidate& c : candidates_) {
269 c.set_component(component);
270 c.set_username(username_fragment);
271 c.set_password(password);
272 }
273}
274
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700275const std::vector<Candidate>& Port::Candidates() const {
276 return candidates_;
277}
278
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000279Connection* Port::GetConnection(const rtc::SocketAddress& remote_addr) {
280 AddressMap::const_iterator iter = connections_.find(remote_addr);
281 if (iter != connections_.end())
282 return iter->second;
283 else
284 return NULL;
285}
286
287void Port::AddAddress(const rtc::SocketAddress& address,
288 const rtc::SocketAddress& base_address,
289 const rtc::SocketAddress& related_address,
290 const std::string& protocol,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700291 const std::string& relay_protocol,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000292 const std::string& tcptype,
293 const std::string& type,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200294 uint32_t type_preference,
295 uint32_t relay_preference,
Peter Boström2758c662017-02-13 20:33:27 -0500296 bool final) {
297 AddAddress(address, base_address, related_address, protocol, relay_protocol,
298 tcptype, type, type_preference, relay_preference, "", final);
299}
300
301void Port::AddAddress(const rtc::SocketAddress& address,
302 const rtc::SocketAddress& base_address,
303 const rtc::SocketAddress& related_address,
304 const std::string& protocol,
305 const std::string& relay_protocol,
306 const std::string& tcptype,
307 const std::string& type,
308 uint32_t type_preference,
309 uint32_t relay_preference,
zhihuang26d99c22017-02-13 12:47:27 -0800310 const std::string& url,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000311 bool final) {
312 if (protocol == TCP_PROTOCOL_NAME && type == LOCAL_PORT_TYPE) {
nisseede5da42017-01-12 05:15:36 -0800313 RTC_DCHECK(!tcptype.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000314 }
315
honghaiza0c44ea2016-03-23 16:07:48 -0700316 std::string foundation =
317 ComputeFoundation(type, protocol, relay_protocol, base_address);
318 Candidate c(component_, protocol, address, 0U, username_fragment(), password_,
319 type, generation_, foundation, network_->id(), network_cost_);
320 c.set_priority(
321 c.GetPriority(type_preference, network_->preference(), relay_preference));
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700322 c.set_relay_protocol(relay_protocol);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000323 c.set_tcptype(tcptype);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000324 c.set_network_name(network_->name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +0000325 c.set_network_type(network_->type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000326 c.set_related_address(related_address);
zhihuang26d99c22017-02-13 12:47:27 -0800327 c.set_url(url);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000328 candidates_.push_back(c);
329 SignalCandidateReady(this, c);
330
331 if (final) {
332 SignalPortComplete(this);
333 }
334}
335
honghaiz36f50e82016-06-01 15:57:03 -0700336void Port::AddOrReplaceConnection(Connection* conn) {
337 auto ret = connections_.insert(
338 std::make_pair(conn->remote_candidate().address(), conn));
339 // If there is a different connection on the same remote address, replace
340 // it with the new one and destroy the old one.
341 if (ret.second == false && ret.first->second != conn) {
342 LOG_J(LS_WARNING, this)
343 << "A new connection was created on an existing remote address. "
344 << "New remote candidate: " << conn->remote_candidate().ToString();
345 ret.first->second->SignalDestroyed.disconnect(this);
346 ret.first->second->Destroy();
347 ret.first->second = conn;
348 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000349 conn->SignalDestroyed.connect(this, &Port::OnConnectionDestroyed);
350 SignalConnectionCreated(this, conn);
351}
352
353void Port::OnReadPacket(
354 const char* data, size_t size, const rtc::SocketAddress& addr,
355 ProtocolType proto) {
356 // If the user has enabled port packets, just hand this over.
357 if (enable_port_packets_) {
358 SignalReadPacket(this, data, size, addr);
359 return;
360 }
361
362 // If this is an authenticated STUN request, then signal unknown address and
363 // send back a proper binding response.
kwiberg3ec46792016-04-27 07:22:53 -0700364 std::unique_ptr<IceMessage> msg;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000365 std::string remote_username;
kwiberg6baec032016-03-15 11:09:39 -0700366 if (!GetStunMessage(data, size, addr, &msg, &remote_username)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000367 LOG_J(LS_ERROR, this) << "Received non-STUN packet from unknown address ("
368 << addr.ToSensitiveString() << ")";
369 } else if (!msg) {
370 // STUN message handled already
371 } else if (msg->type() == STUN_BINDING_REQUEST) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100372 RTC_LOG(LS_INFO) << "Received STUN ping "
373 << " id=" << rtc::hex_encode(msg->transaction_id())
374 << " from unknown address " << addr.ToSensitiveString();
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700375
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000376 // Check for role conflicts.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700377 if (!MaybeIceRoleConflict(addr, msg.get(), remote_username)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100378 RTC_LOG(LS_INFO) << "Received conflicting role from the peer.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000379 return;
380 }
381
382 SignalUnknownAddress(this, addr, proto, msg.get(), remote_username, false);
383 } else {
384 // NOTE(tschmelcher): STUN_BINDING_RESPONSE is benign. It occurs if we
385 // pruned a connection for this port while it had STUN requests in flight,
386 // because we then get back responses for them, which this code correctly
387 // does not handle.
388 if (msg->type() != STUN_BINDING_RESPONSE) {
389 LOG_J(LS_ERROR, this) << "Received unexpected STUN message type ("
390 << msg->type() << ") from unknown address ("
391 << addr.ToSensitiveString() << ")";
392 }
393 }
394}
395
396void Port::OnReadyToSend() {
397 AddressMap::iterator iter = connections_.begin();
398 for (; iter != connections_.end(); ++iter) {
399 iter->second->OnReadyToSend();
400 }
401}
402
403size_t Port::AddPrflxCandidate(const Candidate& local) {
404 candidates_.push_back(local);
405 return (candidates_.size() - 1);
406}
407
kwiberg6baec032016-03-15 11:09:39 -0700408bool Port::GetStunMessage(const char* data,
409 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000410 const rtc::SocketAddress& addr,
kwiberg3ec46792016-04-27 07:22:53 -0700411 std::unique_ptr<IceMessage>* out_msg,
kwiberg6baec032016-03-15 11:09:39 -0700412 std::string* out_username) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000413 // NOTE: This could clearly be optimized to avoid allocating any memory.
414 // However, at the data rates we'll be looking at on the client side,
415 // this probably isn't worth worrying about.
nisseede5da42017-01-12 05:15:36 -0800416 RTC_DCHECK(out_msg != NULL);
417 RTC_DCHECK(out_username != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000418 out_username->clear();
419
420 // Don't bother parsing the packet if we can tell it's not STUN.
421 // In ICE mode, all STUN packets will have a valid fingerprint.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700422 if (!StunMessage::ValidateFingerprint(data, size)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000423 return false;
424 }
425
426 // Parse the request message. If the packet is not a complete and correct
427 // STUN message, then ignore it.
kwiberg3ec46792016-04-27 07:22:53 -0700428 std::unique_ptr<IceMessage> stun_msg(new IceMessage());
jbauchf1f87202016-03-30 06:43:37 -0700429 rtc::ByteBufferReader buf(data, size);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000430 if (!stun_msg->Read(&buf) || (buf.Length() > 0)) {
431 return false;
432 }
433
434 if (stun_msg->type() == STUN_BINDING_REQUEST) {
435 // Check for the presence of USERNAME and MESSAGE-INTEGRITY (if ICE) first.
436 // If not present, fail with a 400 Bad Request.
437 if (!stun_msg->GetByteString(STUN_ATTR_USERNAME) ||
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700438 !stun_msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000439 LOG_J(LS_ERROR, this) << "Received STUN request without username/M-I "
440 << "from " << addr.ToSensitiveString();
441 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_BAD_REQUEST,
442 STUN_ERROR_REASON_BAD_REQUEST);
443 return true;
444 }
445
446 // If the username is bad or unknown, fail with a 401 Unauthorized.
447 std::string local_ufrag;
448 std::string remote_ufrag;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700449 if (!ParseStunUsername(stun_msg.get(), &local_ufrag, &remote_ufrag) ||
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000450 local_ufrag != username_fragment()) {
451 LOG_J(LS_ERROR, this) << "Received STUN request with bad local username "
452 << local_ufrag << " from "
453 << addr.ToSensitiveString();
454 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
455 STUN_ERROR_REASON_UNAUTHORIZED);
456 return true;
457 }
458
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000459 // If ICE, and the MESSAGE-INTEGRITY is bad, fail with a 401 Unauthorized
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700460 if (!stun_msg->ValidateMessageIntegrity(data, size, password_)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000461 LOG_J(LS_ERROR, this) << "Received STUN request with bad M-I "
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +0000462 << "from " << addr.ToSensitiveString()
463 << ", password_=" << password_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000464 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
465 STUN_ERROR_REASON_UNAUTHORIZED);
466 return true;
467 }
468 out_username->assign(remote_ufrag);
469 } else if ((stun_msg->type() == STUN_BINDING_RESPONSE) ||
470 (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE)) {
471 if (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE) {
472 if (const StunErrorCodeAttribute* error_code = stun_msg->GetErrorCode()) {
473 LOG_J(LS_ERROR, this) << "Received STUN binding error:"
474 << " class=" << error_code->eclass()
475 << " number=" << error_code->number()
476 << " reason='" << error_code->reason() << "'"
477 << " from " << addr.ToSensitiveString();
478 // Return message to allow error-specific processing
479 } else {
480 LOG_J(LS_ERROR, this) << "Received STUN binding error without a error "
481 << "code from " << addr.ToSensitiveString();
482 return true;
483 }
484 }
485 // NOTE: Username should not be used in verifying response messages.
486 out_username->clear();
487 } else if (stun_msg->type() == STUN_BINDING_INDICATION) {
488 LOG_J(LS_VERBOSE, this) << "Received STUN binding indication:"
489 << " from " << addr.ToSensitiveString();
490 out_username->clear();
491 // No stun attributes will be verified, if it's stun indication message.
492 // Returning from end of the this method.
493 } else {
494 LOG_J(LS_ERROR, this) << "Received STUN packet with invalid type ("
495 << stun_msg->type() << ") from "
496 << addr.ToSensitiveString();
497 return true;
498 }
499
500 // Return the STUN message found.
kwiberg6baec032016-03-15 11:09:39 -0700501 *out_msg = std::move(stun_msg);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000502 return true;
503}
504
505bool Port::IsCompatibleAddress(const rtc::SocketAddress& addr) {
deadbeef5c3c1042017-08-04 15:01:57 -0700506 // Get a representative IP for the Network this port is configured to use.
507 rtc::IPAddress ip = network_->GetBestIP();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000508 // We use single-stack sockets, so families must match.
deadbeef5c3c1042017-08-04 15:01:57 -0700509 if (addr.family() != ip.family()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000510 return false;
511 }
512 // Link-local IPv6 ports can only connect to other link-local IPv6 ports.
deadbeef5c3c1042017-08-04 15:01:57 -0700513 if (ip.family() == AF_INET6 &&
514 (IPIsLinkLocal(ip) != IPIsLinkLocal(addr.ipaddr()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000515 return false;
516 }
517 return true;
518}
519
520bool Port::ParseStunUsername(const StunMessage* stun_msg,
521 std::string* local_ufrag,
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700522 std::string* remote_ufrag) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000523 // The packet must include a username that either begins or ends with our
524 // fragment. It should begin with our fragment if it is a request and it
525 // should end with our fragment if it is a response.
526 local_ufrag->clear();
527 remote_ufrag->clear();
528 const StunByteStringAttribute* username_attr =
529 stun_msg->GetByteString(STUN_ATTR_USERNAME);
530 if (username_attr == NULL)
531 return false;
532
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700533 // RFRAG:LFRAG
534 const std::string username = username_attr->GetString();
535 size_t colon_pos = username.find(":");
536 if (colon_pos == std::string::npos) {
537 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000538 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000539
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700540 *local_ufrag = username.substr(0, colon_pos);
541 *remote_ufrag = username.substr(colon_pos + 1, username.size());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000542 return true;
543}
544
545bool Port::MaybeIceRoleConflict(
546 const rtc::SocketAddress& addr, IceMessage* stun_msg,
547 const std::string& remote_ufrag) {
548 // Validate ICE_CONTROLLING or ICE_CONTROLLED attributes.
549 bool ret = true;
550 IceRole remote_ice_role = ICEROLE_UNKNOWN;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200551 uint64_t remote_tiebreaker = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000552 const StunUInt64Attribute* stun_attr =
553 stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
554 if (stun_attr) {
555 remote_ice_role = ICEROLE_CONTROLLING;
556 remote_tiebreaker = stun_attr->value();
557 }
558
559 // If |remote_ufrag| is same as port local username fragment and
560 // tie breaker value received in the ping message matches port
561 // tiebreaker value this must be a loopback call.
562 // We will treat this as valid scenario.
563 if (remote_ice_role == ICEROLE_CONTROLLING &&
564 username_fragment() == remote_ufrag &&
565 remote_tiebreaker == IceTiebreaker()) {
566 return true;
567 }
568
569 stun_attr = stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
570 if (stun_attr) {
571 remote_ice_role = ICEROLE_CONTROLLED;
572 remote_tiebreaker = stun_attr->value();
573 }
574
575 switch (ice_role_) {
576 case ICEROLE_CONTROLLING:
577 if (ICEROLE_CONTROLLING == remote_ice_role) {
578 if (remote_tiebreaker >= tiebreaker_) {
579 SignalRoleConflict(this);
580 } else {
581 // Send Role Conflict (487) error response.
582 SendBindingErrorResponse(stun_msg, addr,
583 STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
584 ret = false;
585 }
586 }
587 break;
588 case ICEROLE_CONTROLLED:
589 if (ICEROLE_CONTROLLED == remote_ice_role) {
590 if (remote_tiebreaker < tiebreaker_) {
591 SignalRoleConflict(this);
592 } else {
593 // Send Role Conflict (487) error response.
594 SendBindingErrorResponse(stun_msg, addr,
595 STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
596 ret = false;
597 }
598 }
599 break;
600 default:
nissec80e7412017-01-11 05:56:46 -0800601 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000602 }
603 return ret;
604}
605
606void Port::CreateStunUsername(const std::string& remote_username,
607 std::string* stun_username_attr_str) const {
608 stun_username_attr_str->clear();
609 *stun_username_attr_str = remote_username;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700610 stun_username_attr_str->append(":");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000611 stun_username_attr_str->append(username_fragment());
612}
613
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700614bool Port::HandleIncomingPacket(rtc::AsyncPacketSocket* socket,
615 const char* data,
616 size_t size,
617 const rtc::SocketAddress& remote_addr,
618 const rtc::PacketTime& packet_time) {
619 RTC_NOTREACHED();
620 return false;
621}
622
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000623void Port::SendBindingResponse(StunMessage* request,
624 const rtc::SocketAddress& addr) {
nisseede5da42017-01-12 05:15:36 -0800625 RTC_DCHECK(request->type() == STUN_BINDING_REQUEST);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000626
627 // Retrieve the username from the request.
628 const StunByteStringAttribute* username_attr =
629 request->GetByteString(STUN_ATTR_USERNAME);
nisseede5da42017-01-12 05:15:36 -0800630 RTC_DCHECK(username_attr != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000631 if (username_attr == NULL) {
632 // No valid username, skip the response.
633 return;
634 }
635
636 // Fill in the response message.
637 StunMessage response;
638 response.SetType(STUN_BINDING_RESPONSE);
639 response.SetTransactionID(request->transaction_id());
640 const StunUInt32Attribute* retransmit_attr =
641 request->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
642 if (retransmit_attr) {
643 // Inherit the incoming retransmit value in the response so the other side
644 // can see our view of lost pings.
zsteinf42cc9d2017-03-27 16:17:19 -0700645 response.AddAttribute(rtc::MakeUnique<StunUInt32Attribute>(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000646 STUN_ATTR_RETRANSMIT_COUNT, retransmit_attr->value()));
647
648 if (retransmit_attr->value() > CONNECTION_WRITE_CONNECT_FAILURES) {
649 LOG_J(LS_INFO, this)
650 << "Received a remote ping with high retransmit count: "
651 << retransmit_attr->value();
652 }
653 }
654
zsteinf42cc9d2017-03-27 16:17:19 -0700655 response.AddAttribute(rtc::MakeUnique<StunXorAddressAttribute>(
656 STUN_ATTR_XOR_MAPPED_ADDRESS, addr));
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700657 response.AddMessageIntegrity(password_);
658 response.AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000659
660 // Send the response message.
jbauchf1f87202016-03-30 06:43:37 -0700661 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000662 response.Write(&buf);
663 rtc::PacketOptions options(DefaultDscpValue());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700664 auto err = SendTo(buf.Data(), buf.Length(), addr, options, false);
665 if (err < 0) {
666 LOG_J(LS_ERROR, this)
667 << "Failed to send STUN ping response"
668 << ", to=" << addr.ToSensitiveString()
669 << ", err=" << err
670 << ", id=" << rtc::hex_encode(response.transaction_id());
671 } else {
672 // Log at LS_INFO if we send a stun ping response on an unwritable
673 // connection.
honghaiz9b5ee9c2015-11-11 13:19:17 -0800674 Connection* conn = GetConnection(addr);
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700675 rtc::LoggingSeverity sev = (conn && !conn->writable()) ?
676 rtc::LS_INFO : rtc::LS_VERBOSE;
677 LOG_JV(sev, this)
678 << "Sent STUN ping response"
679 << ", to=" << addr.ToSensitiveString()
680 << ", id=" << rtc::hex_encode(response.transaction_id());
zhihuang5ecf16c2016-06-01 17:09:15 -0700681
682 conn->stats_.sent_ping_responses++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000683 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000684}
685
686void Port::SendBindingErrorResponse(StunMessage* request,
687 const rtc::SocketAddress& addr,
688 int error_code, const std::string& reason) {
nisseede5da42017-01-12 05:15:36 -0800689 RTC_DCHECK(request->type() == STUN_BINDING_REQUEST);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000690
691 // Fill in the response message.
692 StunMessage response;
693 response.SetType(STUN_BINDING_ERROR_RESPONSE);
694 response.SetTransactionID(request->transaction_id());
695
696 // When doing GICE, we need to write out the error code incorrectly to
697 // maintain backwards compatiblility.
zsteinf42cc9d2017-03-27 16:17:19 -0700698 auto error_attr = StunAttribute::CreateErrorCode();
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700699 error_attr->SetCode(error_code);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000700 error_attr->SetReason(reason);
zsteinf42cc9d2017-03-27 16:17:19 -0700701 response.AddAttribute(std::move(error_attr));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000702
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700703 // Per Section 10.1.2, certain error cases don't get a MESSAGE-INTEGRITY,
704 // because we don't have enough information to determine the shared secret.
705 if (error_code != STUN_ERROR_BAD_REQUEST &&
706 error_code != STUN_ERROR_UNAUTHORIZED)
707 response.AddMessageIntegrity(password_);
708 response.AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000709
710 // Send the response message.
jbauchf1f87202016-03-30 06:43:37 -0700711 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000712 response.Write(&buf);
713 rtc::PacketOptions options(DefaultDscpValue());
714 SendTo(buf.Data(), buf.Length(), addr, options, false);
715 LOG_J(LS_INFO, this) << "Sending STUN binding error: reason=" << reason
716 << " to " << addr.ToSensitiveString();
717}
718
Honghai Zhanga74363c2016-07-28 18:06:15 -0700719void Port::KeepAliveUntilPruned() {
720 // If it is pruned, we won't bring it up again.
721 if (state_ == State::INIT) {
722 state_ = State::KEEP_ALIVE_UNTIL_PRUNED;
723 }
724}
725
726void Port::Prune() {
727 state_ = State::PRUNED;
728 thread_->Post(RTC_FROM_HERE, this, MSG_DESTROY_IF_DEAD);
729}
730
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000731void Port::OnMessage(rtc::Message *pmsg) {
nisseede5da42017-01-12 05:15:36 -0800732 RTC_DCHECK(pmsg->message_id == MSG_DESTROY_IF_DEAD);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700733 bool dead =
734 (state_ == State::INIT || state_ == State::PRUNED) &&
735 connections_.empty() &&
736 rtc::TimeMillis() - last_time_all_connections_removed_ >= timeout_delay_;
737 if (dead) {
honghaizd0b31432015-09-30 12:42:17 -0700738 Destroy();
739 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000740}
741
Honghai Zhang351d77b2016-05-20 15:08:29 -0700742void Port::OnNetworkTypeChanged(const rtc::Network* network) {
nisseede5da42017-01-12 05:15:36 -0800743 RTC_DCHECK(network == network_);
Honghai Zhang351d77b2016-05-20 15:08:29 -0700744
745 UpdateNetworkCost();
746}
747
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000748std::string Port::ToString() const {
749 std::stringstream ss;
honghaize3c6c822016-02-17 13:00:28 -0800750 ss << "Port[" << std::hex << this << std::dec << ":" << content_name_ << ":"
751 << component_ << ":" << generation_ << ":" << type_ << ":"
752 << network_->ToString() << "]";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000753 return ss.str();
754}
755
Honghai Zhang351d77b2016-05-20 15:08:29 -0700756// TODO(honghaiz): Make the network cost configurable from user setting.
757void Port::UpdateNetworkCost() {
758 uint16_t new_cost = network_->GetCost();
759 if (network_cost_ == new_cost) {
760 return;
761 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100762 RTC_LOG(LS_INFO) << "Network cost changed from " << network_cost_ << " to "
763 << new_cost
764 << ". Number of candidates created: " << candidates_.size()
765 << ". Number of connections created: "
766 << connections_.size();
Honghai Zhang351d77b2016-05-20 15:08:29 -0700767 network_cost_ = new_cost;
768 for (cricket::Candidate& candidate : candidates_) {
769 candidate.set_network_cost(network_cost_);
770 }
771 // Network cost change will affect the connection selection criteria.
772 // Signal the connection state change on each connection to force a
773 // re-sort in P2PTransportChannel.
774 for (auto kv : connections_) {
775 Connection* conn = kv.second;
776 conn->SignalStateChange(conn);
777 }
778}
779
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000780void Port::EnablePortPackets() {
781 enable_port_packets_ = true;
782}
783
784void Port::OnConnectionDestroyed(Connection* conn) {
785 AddressMap::iterator iter =
786 connections_.find(conn->remote_candidate().address());
nisseede5da42017-01-12 05:15:36 -0800787 RTC_DCHECK(iter != connections_.end());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000788 connections_.erase(iter);
honghaiz36f50e82016-06-01 15:57:03 -0700789 HandleConnectionDestroyed(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000790
Honghai Zhanga74363c2016-07-28 18:06:15 -0700791 // Ports time out after all connections fail if it is not marked as
792 // "keep alive until pruned."
honghaizd0b31432015-09-30 12:42:17 -0700793 // Note: If a new connection is added after this message is posted, but it
794 // fails and is removed before kPortTimeoutDelay, then this message will
Honghai Zhangb5db1ec2016-07-28 13:23:05 -0700795 // not cause the Port to be destroyed.
Honghai Zhanga74363c2016-07-28 18:06:15 -0700796 if (connections_.empty()) {
Honghai Zhangb5db1ec2016-07-28 13:23:05 -0700797 last_time_all_connections_removed_ = rtc::TimeMillis();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700798 thread_->PostDelayed(RTC_FROM_HERE, timeout_delay_, this,
799 MSG_DESTROY_IF_DEAD);
honghaizd0b31432015-09-30 12:42:17 -0700800 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000801}
802
803void Port::Destroy() {
nisseede5da42017-01-12 05:15:36 -0800804 RTC_DCHECK(connections_.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000805 LOG_J(LS_INFO, this) << "Port deleted";
806 SignalDestroyed(this);
807 delete this;
808}
809
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000810const std::string Port::username_fragment() const {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700811 return ice_username_fragment_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000812}
813
814// A ConnectionRequest is a simple STUN ping used to determine writability.
815class ConnectionRequest : public StunRequest {
816 public:
817 explicit ConnectionRequest(Connection* connection)
818 : StunRequest(new IceMessage()),
819 connection_(connection) {
820 }
821
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700822 void Prepare(StunMessage* request) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000823 request->SetType(STUN_BINDING_REQUEST);
824 std::string username;
825 connection_->port()->CreateStunUsername(
826 connection_->remote_candidate().username(), &username);
827 request->AddAttribute(
zsteinf42cc9d2017-03-27 16:17:19 -0700828 rtc::MakeUnique<StunByteStringAttribute>(STUN_ATTR_USERNAME, username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000829
830 // connection_ already holds this ping, so subtract one from count.
831 if (connection_->port()->send_retransmit_count_attribute()) {
zsteinf42cc9d2017-03-27 16:17:19 -0700832 request->AddAttribute(rtc::MakeUnique<StunUInt32Attribute>(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000833 STUN_ATTR_RETRANSMIT_COUNT,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200834 static_cast<uint32_t>(connection_->pings_since_last_response_.size() -
835 1)));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000836 }
honghaiza0c44ea2016-03-23 16:07:48 -0700837 uint32_t network_info = connection_->port()->Network()->id();
838 network_info = (network_info << 16) | connection_->port()->network_cost();
zsteinf42cc9d2017-03-27 16:17:19 -0700839 request->AddAttribute(rtc::MakeUnique<StunUInt32Attribute>(
840 STUN_ATTR_NETWORK_INFO, network_info));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000841
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700842 // Adding ICE_CONTROLLED or ICE_CONTROLLING attribute based on the role.
843 if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLING) {
zsteinf42cc9d2017-03-27 16:17:19 -0700844 request->AddAttribute(rtc::MakeUnique<StunUInt64Attribute>(
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700845 STUN_ATTR_ICE_CONTROLLING, connection_->port()->IceTiebreaker()));
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700846 // We should have either USE_CANDIDATE attribute or ICE_NOMINATION
847 // attribute but not both. That was enforced in p2ptransportchannel.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700848 if (connection_->use_candidate_attr()) {
zsteinf42cc9d2017-03-27 16:17:19 -0700849 request->AddAttribute(
850 rtc::MakeUnique<StunByteStringAttribute>(STUN_ATTR_USE_CANDIDATE));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000851 }
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700852 if (connection_->nomination() &&
853 connection_->nomination() != connection_->acked_nomination()) {
zsteinf42cc9d2017-03-27 16:17:19 -0700854 request->AddAttribute(rtc::MakeUnique<StunUInt32Attribute>(
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700855 STUN_ATTR_NOMINATION, connection_->nomination()));
856 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700857 } else if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLED) {
zsteinf42cc9d2017-03-27 16:17:19 -0700858 request->AddAttribute(rtc::MakeUnique<StunUInt64Attribute>(
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700859 STUN_ATTR_ICE_CONTROLLED, connection_->port()->IceTiebreaker()));
860 } else {
nissec80e7412017-01-11 05:56:46 -0800861 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000862 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700863
864 // Adding PRIORITY Attribute.
865 // Changing the type preference to Peer Reflexive and local preference
866 // and component id information is unchanged from the original priority.
867 // priority = (2^24)*(type preference) +
868 // (2^8)*(local preference) +
869 // (2^0)*(256 - component ID)
Taylor Brandstetter62351c92016-08-11 16:05:07 -0700870 uint32_t type_preference =
871 (connection_->local_candidate().protocol() == TCP_PROTOCOL_NAME)
872 ? ICE_TYPE_PREFERENCE_PRFLX_TCP
873 : ICE_TYPE_PREFERENCE_PRFLX;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200874 uint32_t prflx_priority =
Taylor Brandstetter62351c92016-08-11 16:05:07 -0700875 type_preference << 24 |
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700876 (connection_->local_candidate().priority() & 0x00FFFFFF);
zsteinf42cc9d2017-03-27 16:17:19 -0700877 request->AddAttribute(rtc::MakeUnique<StunUInt32Attribute>(
878 STUN_ATTR_PRIORITY, prflx_priority));
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700879
880 // Adding Message Integrity attribute.
881 request->AddMessageIntegrity(connection_->remote_candidate().password());
882 // Adding Fingerprint.
883 request->AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000884 }
885
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700886 void OnResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000887 connection_->OnConnectionRequestResponse(this, response);
888 }
889
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700890 void OnErrorResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000891 connection_->OnConnectionRequestErrorResponse(this, response);
892 }
893
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700894 void OnTimeout() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000895 connection_->OnConnectionRequestTimeout(this);
896 }
897
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700898 void OnSent() override {
899 connection_->OnConnectionRequestSent(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000900 // Each request is sent only once. After a single delay , the request will
901 // time out.
902 timeout_ = true;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700903 }
904
905 int resend_delay() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000906 return CONNECTION_RESPONSE_TIMEOUT;
907 }
908
909 private:
910 Connection* connection_;
911};
912
913//
914// Connection
915//
916
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000917Connection::Connection(Port* port,
918 size_t index,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000919 const Candidate& remote_candidate)
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000920 : port_(port),
921 local_candidate_index_(index),
922 remote_candidate_(remote_candidate),
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700923 recv_rate_tracker_(100, 10u),
924 send_rate_tracker_(100, 10u),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000925 write_state_(STATE_WRITE_INIT),
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700926 receiving_(false),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000927 connected_(true),
928 pruned_(false),
929 use_candidate_attr_(false),
930 remote_ice_mode_(ICEMODE_FULL),
931 requests_(port->thread()),
932 rtt_(DEFAULT_RTT),
933 last_ping_sent_(0),
934 last_ping_received_(0),
935 last_data_received_(0),
936 last_ping_response_received_(0),
zsteinabbacbf2017-03-20 10:53:12 -0700937 packet_loss_estimator_(kConsiderPacketLostAfter, kForgetPacketAfter),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000938 reported_(false),
hbos06495bc2017-01-02 08:08:18 -0800939 state_(IceCandidatePairState::WAITING),
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700940 receiving_timeout_(WEAK_CONNECTION_RECEIVE_TIMEOUT),
nisse1bffc1d2016-05-02 08:18:55 -0700941 time_created_ms_(rtc::TimeMillis()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000942 // All of our connections start in WAITING state.
943 // TODO(mallinath) - Start connections from STATE_FROZEN.
944 // Wire up to send stun packets
945 requests_.SignalSendPacket.connect(this, &Connection::OnSendStunPacket);
946 LOG_J(LS_INFO, this) << "Connection created";
947}
948
949Connection::~Connection() {
950}
951
952const Candidate& Connection::local_candidate() const {
nisseede5da42017-01-12 05:15:36 -0800953 RTC_DCHECK(local_candidate_index_ < port_->Candidates().size());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000954 return port_->Candidates()[local_candidate_index_];
955}
956
Honghai Zhangcc411c02016-03-29 17:27:21 -0700957const Candidate& Connection::remote_candidate() const {
958 return remote_candidate_;
959}
960
Peter Boström0c4e06b2015-10-07 12:23:21 +0200961uint64_t Connection::priority() const {
962 uint64_t priority = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000963 // RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs
964 // Let G be the priority for the candidate provided by the controlling
965 // agent. Let D be the priority for the candidate provided by the
966 // controlled agent.
967 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
968 IceRole role = port_->GetIceRole();
969 if (role != ICEROLE_UNKNOWN) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200970 uint32_t g = 0;
971 uint32_t d = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000972 if (role == ICEROLE_CONTROLLING) {
973 g = local_candidate().priority();
974 d = remote_candidate_.priority();
975 } else {
976 g = remote_candidate_.priority();
977 d = local_candidate().priority();
978 }
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000979 priority = std::min(g, d);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000980 priority = priority << 32;
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000981 priority += 2 * std::max(g, d) + (g > d ? 1 : 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000982 }
983 return priority;
984}
985
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000986void Connection::set_write_state(WriteState value) {
987 WriteState old_value = write_state_;
988 write_state_ = value;
989 if (value != old_value) {
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +0000990 LOG_J(LS_VERBOSE, this) << "set_write_state from: " << old_value << " to "
991 << value;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000992 SignalStateChange(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000993 }
994}
995
honghaiz9ad0db52016-07-14 19:30:28 -0700996void Connection::UpdateReceiving(int64_t now) {
honghaize58d73d2016-10-24 16:38:26 -0700997 bool receiving =
998 last_received() > 0 && now <= last_received() + receiving_timeout_;
honghaiz9ad0db52016-07-14 19:30:28 -0700999 if (receiving_ == receiving) {
1000 return;
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001001 }
honghaiz9ad0db52016-07-14 19:30:28 -07001002 LOG_J(LS_VERBOSE, this) << "set_receiving to " << receiving;
1003 receiving_ = receiving;
1004 receiving_unchanged_since_ = now;
1005 SignalStateChange(this);
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001006}
1007
hbos06495bc2017-01-02 08:08:18 -08001008void Connection::set_state(IceCandidatePairState state) {
1009 IceCandidatePairState old_state = state_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001010 state_ = state;
1011 if (state != old_state) {
1012 LOG_J(LS_VERBOSE, this) << "set_state";
1013 }
1014}
1015
1016void Connection::set_connected(bool value) {
1017 bool old_value = connected_;
1018 connected_ = value;
1019 if (value != old_value) {
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07001020 LOG_J(LS_VERBOSE, this) << "set_connected from: " << old_value << " to "
1021 << value;
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001022 SignalStateChange(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001023 }
1024}
1025
1026void Connection::set_use_candidate_attr(bool enable) {
1027 use_candidate_attr_ = enable;
1028}
1029
1030void Connection::OnSendStunPacket(const void* data, size_t size,
1031 StunRequest* req) {
1032 rtc::PacketOptions options(port_->DefaultDscpValue());
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001033 auto err = port_->SendTo(
1034 data, size, remote_candidate_.address(), options, false);
1035 if (err < 0) {
1036 LOG_J(LS_WARNING, this) << "Failed to send STUN ping "
1037 << " err=" << err
1038 << " id=" << rtc::hex_encode(req->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001039 }
1040}
1041
1042void Connection::OnReadPacket(
1043 const char* data, size_t size, const rtc::PacketTime& packet_time) {
kwiberg3ec46792016-04-27 07:22:53 -07001044 std::unique_ptr<IceMessage> msg;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001045 std::string remote_ufrag;
1046 const rtc::SocketAddress& addr(remote_candidate_.address());
kwiberg6baec032016-03-15 11:09:39 -07001047 if (!port_->GetStunMessage(data, size, addr, &msg, &remote_ufrag)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001048 // The packet did not parse as a valid STUN message
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001049 // This is a data packet, pass it along.
nisse1bffc1d2016-05-02 08:18:55 -07001050 last_data_received_ = rtc::TimeMillis();
honghaiz9ad0db52016-07-14 19:30:28 -07001051 UpdateReceiving(last_data_received_);
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001052 recv_rate_tracker_.AddSamples(size);
1053 SignalReadPacket(this, data, size, packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001054
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001055 // If timed out sending writability checks, start up again
1056 if (!pruned_ && (write_state_ == STATE_WRITE_TIMEOUT)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001057 RTC_LOG(LS_WARNING)
1058 << "Received a data packet on a timed-out Connection. "
1059 << "Resetting state to STATE_WRITE_INIT.";
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001060 set_write_state(STATE_WRITE_INIT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001061 }
1062 } else if (!msg) {
1063 // The packet was STUN, but failed a check and was handled internally.
1064 } else {
1065 // The packet is STUN and passed the Port checks.
1066 // Perform our own checks to ensure this packet is valid.
honghaizd0b31432015-09-30 12:42:17 -07001067 // If this is a STUN request, then update the receiving bit and respond.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001068 // If this is a STUN response, then update the writable bit.
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001069 // Log at LS_INFO if we receive a ping on an unwritable connection.
1070 rtc::LoggingSeverity sev = (!writable() ? rtc::LS_INFO : rtc::LS_VERBOSE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001071 switch (msg->type()) {
1072 case STUN_BINDING_REQUEST:
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001073 LOG_JV(sev, this) << "Received STUN ping"
1074 << ", id=" << rtc::hex_encode(msg->transaction_id());
1075
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001076 if (remote_ufrag == remote_candidate_.username()) {
honghaiz9b5ee9c2015-11-11 13:19:17 -08001077 HandleBindingRequest(msg.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001078 } else {
1079 // The packet had the right local username, but the remote username
1080 // was not the right one for the remote address.
1081 LOG_J(LS_ERROR, this)
1082 << "Received STUN request with bad remote username "
1083 << remote_ufrag;
1084 port_->SendBindingErrorResponse(msg.get(), addr,
1085 STUN_ERROR_UNAUTHORIZED,
1086 STUN_ERROR_REASON_UNAUTHORIZED);
1087
1088 }
1089 break;
1090
1091 // Response from remote peer. Does it match request sent?
1092 // This doesn't just check, it makes callbacks if transaction
1093 // id's match.
1094 case STUN_BINDING_RESPONSE:
1095 case STUN_BINDING_ERROR_RESPONSE:
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001096 if (msg->ValidateMessageIntegrity(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001097 data, size, remote_candidate().password())) {
1098 requests_.CheckResponse(msg.get());
1099 }
1100 // Otherwise silently discard the response message.
1101 break;
1102
honghaizd0b31432015-09-30 12:42:17 -07001103 // Remote end point sent an STUN indication instead of regular binding
1104 // request. In this case |last_ping_received_| will be updated but no
1105 // response will be sent.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001106 case STUN_BINDING_INDICATION:
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001107 ReceivedPing();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001108 break;
1109
1110 default:
nissec80e7412017-01-11 05:56:46 -08001111 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001112 break;
1113 }
1114 }
1115}
1116
honghaiz9b5ee9c2015-11-11 13:19:17 -08001117void Connection::HandleBindingRequest(IceMessage* msg) {
1118 // This connection should now be receiving.
1119 ReceivedPing();
1120
1121 const rtc::SocketAddress& remote_addr = remote_candidate_.address();
1122 const std::string& remote_ufrag = remote_candidate_.username();
1123 // Check for role conflicts.
1124 if (!port_->MaybeIceRoleConflict(remote_addr, msg, remote_ufrag)) {
1125 // Received conflicting role from the peer.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001126 RTC_LOG(LS_INFO) << "Received conflicting role from the peer.";
honghaiz9b5ee9c2015-11-11 13:19:17 -08001127 return;
1128 }
1129
zhihuang5ecf16c2016-06-01 17:09:15 -07001130 stats_.recv_ping_requests++;
1131
honghaiz9b5ee9c2015-11-11 13:19:17 -08001132 // This is a validated stun request from remote peer.
1133 port_->SendBindingResponse(msg, remote_addr);
1134
1135 // If it timed out on writing check, start up again
1136 if (!pruned_ && write_state_ == STATE_WRITE_TIMEOUT) {
1137 set_write_state(STATE_WRITE_INIT);
1138 }
1139
1140 if (port_->GetIceRole() == ICEROLE_CONTROLLED) {
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001141 const StunUInt32Attribute* nomination_attr =
1142 msg->GetUInt32(STUN_ATTR_NOMINATION);
1143 uint32_t nomination = 0;
1144 if (nomination_attr) {
1145 nomination = nomination_attr->value();
1146 if (nomination == 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001147 RTC_LOG(LS_ERROR) << "Invalid nomination: " << nomination;
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001148 }
1149 } else {
1150 const StunByteStringAttribute* use_candidate_attr =
1151 msg->GetByteString(STUN_ATTR_USE_CANDIDATE);
1152 if (use_candidate_attr) {
1153 nomination = 1;
1154 }
1155 }
1156 // We don't un-nominate a connection, so we only keep a larger nomination.
1157 if (nomination > remote_nomination_) {
1158 set_remote_nomination(nomination);
honghaiz9b5ee9c2015-11-11 13:19:17 -08001159 SignalNominated(this);
1160 }
1161 }
Honghai Zhang351d77b2016-05-20 15:08:29 -07001162 // Set the remote cost if the network_info attribute is available.
1163 // Note: If packets are re-ordered, we may get incorrect network cost
1164 // temporarily, but it should get the correct value shortly after that.
1165 const StunUInt32Attribute* network_attr =
1166 msg->GetUInt32(STUN_ATTR_NETWORK_INFO);
1167 if (network_attr) {
1168 uint32_t network_info = network_attr->value();
1169 uint16_t network_cost = static_cast<uint16_t>(network_info);
1170 if (network_cost != remote_candidate_.network_cost()) {
1171 remote_candidate_.set_network_cost(network_cost);
1172 // Network cost change will affect the connection ranking, so signal
1173 // state change to force a re-sort in P2PTransportChannel.
1174 SignalStateChange(this);
1175 }
1176 }
honghaiz9b5ee9c2015-11-11 13:19:17 -08001177}
1178
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001179void Connection::OnReadyToSend() {
deadbeefdd7fb432016-09-30 15:16:48 -07001180 SignalReadyToSend(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001181}
1182
1183void Connection::Prune() {
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001184 if (!pruned_ || active()) {
Honghai Zhang1590c392016-05-24 13:15:02 -07001185 LOG_J(LS_INFO, this) << "Connection pruned";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001186 pruned_ = true;
1187 requests_.Clear();
1188 set_write_state(STATE_WRITE_TIMEOUT);
1189 }
1190}
1191
1192void Connection::Destroy() {
nisse7eaa4ea2017-05-08 05:25:41 -07001193 // TODO(deadbeef, nisse): This may leak if an application closes a
1194 // PeerConnection and then quickly destroys the PeerConnectionFactory (along
1195 // with the networking thread on which this message is posted). Also affects
1196 // tests, with a workaround in
1197 // AutoSocketServerThread::~AutoSocketServerThread.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001198 LOG_J(LS_VERBOSE, this) << "Connection destroyed";
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001199 port_->thread()->Post(RTC_FROM_HERE, this, MSG_DELETE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001200}
1201
deadbeef376e1232015-11-25 09:00:08 -08001202void Connection::FailAndDestroy() {
hbos06495bc2017-01-02 08:08:18 -08001203 set_state(IceCandidatePairState::FAILED);
deadbeef376e1232015-11-25 09:00:08 -08001204 Destroy();
1205}
1206
honghaiz079a7a12016-06-22 16:26:29 -07001207void Connection::FailAndPrune() {
hbos06495bc2017-01-02 08:08:18 -08001208 set_state(IceCandidatePairState::FAILED);
honghaiz079a7a12016-06-22 16:26:29 -07001209 Prune();
1210}
1211
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001212void Connection::PrintPingsSinceLastResponse(std::string* s, size_t max) {
1213 std::ostringstream oss;
1214 oss << std::boolalpha;
1215 if (pings_since_last_response_.size() > max) {
1216 for (size_t i = 0; i < max; i++) {
1217 const SentPing& ping = pings_since_last_response_[i];
1218 oss << rtc::hex_encode(ping.id) << " ";
1219 }
1220 oss << "... " << (pings_since_last_response_.size() - max) << " more";
1221 } else {
1222 for (const SentPing& ping : pings_since_last_response_) {
1223 oss << rtc::hex_encode(ping.id) << " ";
1224 }
1225 }
1226 *s = oss.str();
1227}
1228
honghaiz34b11eb2016-03-16 08:55:44 -07001229void Connection::UpdateState(int64_t now) {
1230 int rtt = ConservativeRTTEstimate(rtt_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001231
Mirko Bonadei675513b2017-11-09 11:09:25 +01001232 if (RTC_LOG_CHECK_LEVEL(LS_VERBOSE)) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001233 std::string pings;
1234 PrintPingsSinceLastResponse(&pings, 5);
1235 LOG_J(LS_VERBOSE, this) << "UpdateState()"
1236 << ", ms since last received response="
1237 << now - last_ping_response_received_
1238 << ", ms since last received data="
1239 << now - last_data_received_
1240 << ", rtt=" << rtt
1241 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001242 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001243
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001244 // Check the writable state. (The order of these checks is important.)
1245 //
1246 // Before becoming unwritable, we allow for a fixed number of pings to fail
1247 // (i.e., receive no response). We also have to give the response time to
1248 // get back, so we include a conservative estimate of this.
1249 //
1250 // Before timing out writability, we give a fixed amount of time. This is to
1251 // allow for changes in network conditions.
1252
1253 if ((write_state_ == STATE_WRITABLE) &&
1254 TooManyFailures(pings_since_last_response_,
1255 CONNECTION_WRITE_CONNECT_FAILURES,
1256 rtt,
1257 now) &&
1258 TooLongWithoutResponse(pings_since_last_response_,
1259 CONNECTION_WRITE_CONNECT_TIMEOUT,
1260 now)) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001261 uint32_t max_pings = CONNECTION_WRITE_CONNECT_FAILURES;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001262 LOG_J(LS_INFO, this) << "Unwritable after " << max_pings
1263 << " ping failures and "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001264 << now - pings_since_last_response_[0].sent_time
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001265 << " ms without a response,"
1266 << " ms since last received ping="
1267 << now - last_ping_received_
1268 << " ms since last received data="
1269 << now - last_data_received_
1270 << " rtt=" << rtt;
1271 set_write_state(STATE_WRITE_UNRELIABLE);
1272 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001273 if ((write_state_ == STATE_WRITE_UNRELIABLE ||
1274 write_state_ == STATE_WRITE_INIT) &&
1275 TooLongWithoutResponse(pings_since_last_response_,
1276 CONNECTION_WRITE_TIMEOUT,
1277 now)) {
1278 LOG_J(LS_INFO, this) << "Timed out after "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001279 << now - pings_since_last_response_[0].sent_time
1280 << " ms without a response"
1281 << ", rtt=" << rtt;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001282 set_write_state(STATE_WRITE_TIMEOUT);
1283 }
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001284
honghaiz9ad0db52016-07-14 19:30:28 -07001285 // Update the receiving state.
1286 UpdateReceiving(now);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001287 if (dead(now)) {
1288 Destroy();
1289 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001290}
1291
honghaiz34b11eb2016-03-16 08:55:44 -07001292void Connection::Ping(int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001293 last_ping_sent_ = now;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001294 ConnectionRequest *req = new ConnectionRequest(this);
deadbeef86c40a12017-06-28 09:37:23 -07001295 // If not using renomination, we use "1" to mean "nominated" and "0" to mean
1296 // "not nominated". If using renomination, values greater than 1 are used for
1297 // re-nominated pairs.
1298 int nomination = use_candidate_attr_ ? 1 : 0;
1299 if (nomination_ > 0) {
1300 nomination = nomination_;
1301 }
1302 pings_since_last_response_.push_back(SentPing(req->id(), now, nomination));
zsteinabbacbf2017-03-20 10:53:12 -07001303 packet_loss_estimator_.ExpectResponse(req->id(), now);
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001304 LOG_J(LS_VERBOSE, this) << "Sending STUN ping "
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001305 << ", id=" << rtc::hex_encode(req->id())
1306 << ", nomination=" << nomination_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001307 requests_.Send(req);
hbos06495bc2017-01-02 08:08:18 -08001308 state_ = IceCandidatePairState::IN_PROGRESS;
honghaiz524ecc22016-05-25 12:48:31 -07001309 num_pings_sent_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001310}
1311
1312void Connection::ReceivedPing() {
nisse1bffc1d2016-05-02 08:18:55 -07001313 last_ping_received_ = rtc::TimeMillis();
honghaiz9ad0db52016-07-14 19:30:28 -07001314 UpdateReceiving(last_ping_received_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001315}
1316
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001317void Connection::ReceivedPingResponse(int rtt, const std::string& request_id) {
hbosbf8d3e52017-02-28 06:34:47 -08001318 RTC_DCHECK_GE(rtt, 0);
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001319 // We've already validated that this is a STUN binding response with
1320 // the correct local and remote username for this connection.
1321 // So if we're not already, become writable. We may be bringing a pruned
1322 // connection back to life, but if we don't really want it, we can always
1323 // prune it again.
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001324 auto iter = std::find_if(
1325 pings_since_last_response_.begin(), pings_since_last_response_.end(),
1326 [request_id](const SentPing& ping) { return ping.id == request_id; });
1327 if (iter != pings_since_last_response_.end() &&
1328 iter->nomination > acked_nomination_) {
1329 acked_nomination_ = iter->nomination;
1330 }
1331
hbosbf8d3e52017-02-28 06:34:47 -08001332 total_round_trip_time_ms_ += rtt;
1333 current_round_trip_time_ms_ = rtc::Optional<uint32_t>(
1334 static_cast<uint32_t>(rtt));
1335
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001336 pings_since_last_response_.clear();
honghaiz9ad0db52016-07-14 19:30:28 -07001337 last_ping_response_received_ = rtc::TimeMillis();
1338 UpdateReceiving(last_ping_response_received_);
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001339 set_write_state(STATE_WRITABLE);
hbos06495bc2017-01-02 08:08:18 -08001340 set_state(IceCandidatePairState::SUCCEEDED);
skvladd0309122017-02-02 17:18:37 -08001341 if (rtt_samples_ > 0) {
1342 rtt_ = (RTT_RATIO * rtt_ + rtt) / (RTT_RATIO + 1);
1343 } else {
1344 rtt_ = rtt;
1345 }
zhihuang435264a2016-06-21 11:28:38 -07001346 rtt_samples_++;
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001347}
1348
honghaiz34b11eb2016-03-16 08:55:44 -07001349bool Connection::dead(int64_t now) const {
honghaiz37389b42016-01-04 21:57:33 -08001350 if (last_received() > 0) {
1351 // If it has ever received anything, we keep it alive until it hasn't
1352 // received anything for DEAD_CONNECTION_RECEIVE_TIMEOUT. This covers the
1353 // normal case of a successfully used connection that stops working. This
1354 // also allows a remote peer to continue pinging over a locally inactive
1355 // (pruned) connection.
1356 return (now > (last_received() + DEAD_CONNECTION_RECEIVE_TIMEOUT));
1357 }
1358
1359 if (active()) {
1360 // If it has never received anything, keep it alive as long as it is
1361 // actively pinging and not pruned. Otherwise, the connection might be
1362 // deleted before it has a chance to ping. This is the normal case for a
1363 // new connection that is pinging but hasn't received anything yet.
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001364 return false;
1365 }
1366
honghaiz37389b42016-01-04 21:57:33 -08001367 // If it has never received anything and is not actively pinging (pruned), we
1368 // keep it around for at least MIN_CONNECTION_LIFETIME to prevent connections
1369 // from being pruned too quickly during a network change event when two
1370 // networks would be up simultaneously but only for a brief period.
1371 return now > (time_created_ms_ + MIN_CONNECTION_LIFETIME);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001372}
1373
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001374bool Connection::stable(int64_t now) const {
zhihuang435264a2016-06-21 11:28:38 -07001375 // A connection is stable if it's RTT has converged and it isn't missing any
1376 // responses. We should send pings at a higher rate until the RTT converges
1377 // and whenever a ping response is missing (so that we can detect
1378 // unwritability faster)
1379 return rtt_converged() && !missing_responses(now);
1380}
1381
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +00001382std::string Connection::ToDebugId() const {
1383 std::stringstream ss;
1384 ss << std::hex << this;
1385 return ss.str();
1386}
1387
honghaize1a0c942016-02-16 14:54:56 -08001388uint32_t Connection::ComputeNetworkCost() const {
1389 // TODO(honghaiz): Will add rtt as part of the network cost.
Honghai Zhang351d77b2016-05-20 15:08:29 -07001390 return port()->network_cost() + remote_candidate_.network_cost();
honghaize1a0c942016-02-16 14:54:56 -08001391}
1392
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001393std::string Connection::ToString() const {
1394 const char CONNECT_STATE_ABBREV[2] = {
1395 '-', // not connected (false)
1396 'C', // connected (true)
1397 };
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001398 const char RECEIVE_STATE_ABBREV[2] = {
1399 '-', // not receiving (false)
1400 'R', // receiving (true)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001401 };
1402 const char WRITE_STATE_ABBREV[4] = {
1403 'W', // STATE_WRITABLE
1404 'w', // STATE_WRITE_UNRELIABLE
1405 '-', // STATE_WRITE_INIT
1406 'x', // STATE_WRITE_TIMEOUT
1407 };
1408 const std::string ICESTATE[4] = {
1409 "W", // STATE_WAITING
1410 "I", // STATE_INPROGRESS
1411 "S", // STATE_SUCCEEDED
1412 "F" // STATE_FAILED
1413 };
1414 const Candidate& local = local_candidate();
1415 const Candidate& remote = remote_candidate();
1416 std::stringstream ss;
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001417 ss << "Conn[" << ToDebugId() << ":" << port_->content_name() << ":"
1418 << local.id() << ":" << local.component() << ":" << local.generation()
1419 << ":" << local.type() << ":" << local.protocol() << ":"
1420 << local.address().ToSensitiveString() << "->" << remote.id() << ":"
1421 << remote.component() << ":" << remote.priority() << ":" << remote.type()
1422 << ":" << remote.protocol() << ":" << remote.address().ToSensitiveString()
1423 << "|" << CONNECT_STATE_ABBREV[connected()]
1424 << RECEIVE_STATE_ABBREV[receiving()] << WRITE_STATE_ABBREV[write_state()]
hbos06495bc2017-01-02 08:08:18 -08001425 << ICESTATE[static_cast<int>(state())] << "|" << remote_nomination() << "|"
1426 << nomination() << "|" << priority() << "|";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001427 if (rtt_ < DEFAULT_RTT) {
1428 ss << rtt_ << "]";
1429 } else {
1430 ss << "-]";
1431 }
1432 return ss.str();
1433}
1434
1435std::string Connection::ToSensitiveString() const {
1436 return ToString();
1437}
1438
1439void Connection::OnConnectionRequestResponse(ConnectionRequest* request,
1440 StunMessage* response) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001441 // Log at LS_INFO if we receive a ping response on an unwritable
1442 // connection.
1443 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1444
honghaiz34b11eb2016-03-16 08:55:44 -07001445 int rtt = request->Elapsed();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001446
Mirko Bonadei675513b2017-11-09 11:09:25 +01001447 if (RTC_LOG_CHECK_LEVEL_V(sev)) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001448 std::string pings;
1449 PrintPingsSinceLastResponse(&pings, 5);
1450 LOG_JV(sev, this) << "Received STUN ping response"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001451 << ", id=" << rtc::hex_encode(request->id())
1452 << ", code=0" // Makes logging easier to parse.
1453 << ", rtt=" << rtt
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001454 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001455 }
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001456 ReceivedPingResponse(rtt, request->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001457
zsteinabbacbf2017-03-20 10:53:12 -07001458 int64_t time_received = rtc::TimeMillis();
1459 packet_loss_estimator_.ReceivedResponse(request->id(), time_received);
1460
zhihuang5ecf16c2016-06-01 17:09:15 -07001461 stats_.recv_ping_responses++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001462
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001463 MaybeUpdateLocalCandidate(request, response);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001464}
1465
1466void Connection::OnConnectionRequestErrorResponse(ConnectionRequest* request,
1467 StunMessage* response) {
deadbeef996fc6b2017-04-26 09:21:22 -07001468 int error_code = response->GetErrorCodeValue();
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001469 LOG_J(LS_INFO, this) << "Received STUN error response"
1470 << " id=" << rtc::hex_encode(request->id())
1471 << " code=" << error_code
1472 << " rtt=" << request->Elapsed();
1473
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001474 if (error_code == STUN_ERROR_UNKNOWN_ATTRIBUTE ||
1475 error_code == STUN_ERROR_SERVER_ERROR ||
1476 error_code == STUN_ERROR_UNAUTHORIZED) {
1477 // Recoverable error, retry
1478 } else if (error_code == STUN_ERROR_STALE_CREDENTIALS) {
1479 // Race failure, retry
1480 } else if (error_code == STUN_ERROR_ROLE_CONFLICT) {
1481 HandleRoleConflictFromPeer();
1482 } else {
1483 // This is not a valid connection.
1484 LOG_J(LS_ERROR, this) << "Received STUN error response, code="
1485 << error_code << "; killing connection";
deadbeef376e1232015-11-25 09:00:08 -08001486 FailAndDestroy();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001487 }
1488}
1489
1490void Connection::OnConnectionRequestTimeout(ConnectionRequest* request) {
1491 // Log at LS_INFO if we miss a ping on a writable connection.
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001492 rtc::LoggingSeverity sev = writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1493 LOG_JV(sev, this) << "Timing-out STUN ping "
1494 << rtc::hex_encode(request->id())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001495 << " after " << request->Elapsed() << " ms";
1496}
1497
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001498void Connection::OnConnectionRequestSent(ConnectionRequest* request) {
1499 // Log at LS_INFO if we send a ping on an unwritable connection.
1500 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1501 LOG_JV(sev, this) << "Sent STUN ping"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001502 << ", id=" << rtc::hex_encode(request->id())
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001503 << ", use_candidate=" << use_candidate_attr()
1504 << ", nomination=" << nomination();
zhihuang5ecf16c2016-06-01 17:09:15 -07001505 stats_.sent_ping_requests_total++;
1506 if (stats_.recv_ping_responses == 0) {
1507 stats_.sent_ping_requests_before_first_response++;
1508 }
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001509}
1510
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001511void Connection::HandleRoleConflictFromPeer() {
1512 port_->SignalRoleConflict(port_);
1513}
1514
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001515void Connection::MaybeSetRemoteIceParametersAndGeneration(
1516 const IceParameters& ice_params,
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001517 int generation) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001518 if (remote_candidate_.username() == ice_params.ufrag &&
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001519 remote_candidate_.password().empty()) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001520 remote_candidate_.set_password(ice_params.pwd);
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001521 }
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001522 // TODO(deadbeef): A value of '0' for the generation is used for both
1523 // generation 0 and "generation unknown". It should be changed to an
1524 // rtc::Optional to fix this.
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001525 if (remote_candidate_.username() == ice_params.ufrag &&
1526 remote_candidate_.password() == ice_params.pwd &&
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001527 remote_candidate_.generation() == 0) {
1528 remote_candidate_.set_generation(generation);
1529 }
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001530}
1531
1532void Connection::MaybeUpdatePeerReflexiveCandidate(
1533 const Candidate& new_candidate) {
1534 if (remote_candidate_.type() == PRFLX_PORT_TYPE &&
1535 new_candidate.type() != PRFLX_PORT_TYPE &&
1536 remote_candidate_.protocol() == new_candidate.protocol() &&
1537 remote_candidate_.address() == new_candidate.address() &&
1538 remote_candidate_.username() == new_candidate.username() &&
1539 remote_candidate_.password() == new_candidate.password() &&
1540 remote_candidate_.generation() == new_candidate.generation()) {
1541 remote_candidate_ = new_candidate;
1542 }
1543}
1544
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001545void Connection::OnMessage(rtc::Message *pmsg) {
nisseede5da42017-01-12 05:15:36 -08001546 RTC_DCHECK(pmsg->message_id == MSG_DELETE);
Mirko Bonadei675513b2017-11-09 11:09:25 +01001547 RTC_LOG(LS_INFO) << "Connection deleted with number of pings sent: "
1548 << num_pings_sent_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001549 SignalDestroyed(this);
1550 delete this;
1551}
1552
honghaiz34b11eb2016-03-16 08:55:44 -07001553int64_t Connection::last_received() const {
Peter Thatcher54360512015-07-08 11:08:35 -07001554 return std::max(last_data_received_,
1555 std::max(last_ping_received_, last_ping_response_received_));
1556}
1557
zhihuang5ecf16c2016-06-01 17:09:15 -07001558ConnectionInfo Connection::stats() {
1559 stats_.recv_bytes_second = round(recv_rate_tracker_.ComputeRate());
1560 stats_.recv_total_bytes = recv_rate_tracker_.TotalSampleCount();
1561 stats_.sent_bytes_second = round(send_rate_tracker_.ComputeRate());
1562 stats_.sent_total_bytes = send_rate_tracker_.TotalSampleCount();
hbos06495bc2017-01-02 08:08:18 -08001563 stats_.receiving = receiving_;
1564 stats_.writable = write_state_ == STATE_WRITABLE;
1565 stats_.timeout = write_state_ == STATE_WRITE_TIMEOUT;
1566 stats_.new_connection = !reported_;
1567 stats_.rtt = rtt_;
1568 stats_.local_candidate = local_candidate();
1569 stats_.remote_candidate = remote_candidate();
1570 stats_.key = this;
1571 stats_.state = state_;
1572 stats_.priority = priority();
hbos92eaec62017-02-27 01:38:08 -08001573 stats_.nominated = nominated();
hbosbf8d3e52017-02-28 06:34:47 -08001574 stats_.total_round_trip_time_ms = total_round_trip_time_ms_;
1575 stats_.current_round_trip_time_ms = current_round_trip_time_ms_;
zhihuang5ecf16c2016-06-01 17:09:15 -07001576 return stats_;
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001577}
1578
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001579void Connection::MaybeUpdateLocalCandidate(ConnectionRequest* request,
1580 StunMessage* response) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001581 // RFC 5245
1582 // The agent checks the mapped address from the STUN response. If the
1583 // transport address does not match any of the local candidates that the
1584 // agent knows about, the mapped address represents a new candidate -- a
1585 // peer reflexive candidate.
1586 const StunAddressAttribute* addr =
1587 response->GetAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
1588 if (!addr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001589 RTC_LOG(LS_WARNING)
1590 << "Connection::OnConnectionRequestResponse - "
1591 << "No MAPPED-ADDRESS or XOR-MAPPED-ADDRESS found in the "
1592 << "stun response message";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001593 return;
1594 }
1595
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001596 for (size_t i = 0; i < port_->Candidates().size(); ++i) {
1597 if (port_->Candidates()[i].address() == addr->GetAddress()) {
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001598 if (local_candidate_index_ != i) {
1599 LOG_J(LS_INFO, this) << "Updating local candidate type to srflx.";
1600 local_candidate_index_ = i;
1601 // SignalStateChange to force a re-sort in P2PTransportChannel as this
1602 // Connection's local candidate has changed.
1603 SignalStateChange(this);
1604 }
1605 return;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001606 }
1607 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001608
1609 // RFC 5245
1610 // Its priority is set equal to the value of the PRIORITY attribute
1611 // in the Binding request.
1612 const StunUInt32Attribute* priority_attr =
1613 request->msg()->GetUInt32(STUN_ATTR_PRIORITY);
1614 if (!priority_attr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001615 RTC_LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1616 << "No STUN_ATTR_PRIORITY found in the "
1617 << "stun response message";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001618 return;
1619 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001620 const uint32_t priority = priority_attr->value();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001621 std::string id = rtc::CreateRandomString(8);
1622
1623 Candidate new_local_candidate;
1624 new_local_candidate.set_id(id);
1625 new_local_candidate.set_component(local_candidate().component());
1626 new_local_candidate.set_type(PRFLX_PORT_TYPE);
1627 new_local_candidate.set_protocol(local_candidate().protocol());
1628 new_local_candidate.set_address(addr->GetAddress());
1629 new_local_candidate.set_priority(priority);
1630 new_local_candidate.set_username(local_candidate().username());
1631 new_local_candidate.set_password(local_candidate().password());
1632 new_local_candidate.set_network_name(local_candidate().network_name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001633 new_local_candidate.set_network_type(local_candidate().network_type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001634 new_local_candidate.set_related_address(local_candidate().address());
Taylor Brandstetterf7c15a92016-06-22 13:13:55 -07001635 new_local_candidate.set_generation(local_candidate().generation());
Honghai Zhang80f1db92016-01-27 11:54:45 -08001636 new_local_candidate.set_foundation(ComputeFoundation(
1637 PRFLX_PORT_TYPE, local_candidate().protocol(),
1638 local_candidate().relay_protocol(), local_candidate().address()));
honghaiza0c44ea2016-03-23 16:07:48 -07001639 new_local_candidate.set_network_id(local_candidate().network_id());
1640 new_local_candidate.set_network_cost(local_candidate().network_cost());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001641
1642 // Change the local candidate of this Connection to the new prflx candidate.
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001643 LOG_J(LS_INFO, this) << "Updating local candidate type to prflx.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001644 local_candidate_index_ = port_->AddPrflxCandidate(new_local_candidate);
1645
1646 // SignalStateChange to force a re-sort in P2PTransportChannel as this
1647 // Connection's local candidate has changed.
1648 SignalStateChange(this);
1649}
1650
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001651bool Connection::rtt_converged() const {
zhihuang435264a2016-06-21 11:28:38 -07001652 return rtt_samples_ > (RTT_RATIO + 1);
1653}
1654
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001655bool Connection::missing_responses(int64_t now) const {
zhihuang435264a2016-06-21 11:28:38 -07001656 if (pings_since_last_response_.empty()) {
1657 return false;
1658 }
1659
1660 int64_t waiting = now - pings_since_last_response_[0].sent_time;
1661 return waiting > 2 * rtt();
1662}
1663
deadbeef376e1232015-11-25 09:00:08 -08001664ProxyConnection::ProxyConnection(Port* port,
1665 size_t index,
1666 const Candidate& remote_candidate)
1667 : Connection(port, index, remote_candidate) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001668
1669int ProxyConnection::Send(const void* data, size_t size,
1670 const rtc::PacketOptions& options) {
zhihuang5ecf16c2016-06-01 17:09:15 -07001671 stats_.sent_total_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001672 int sent = port_->SendTo(data, size, remote_candidate_.address(),
1673 options, true);
1674 if (sent <= 0) {
nisseede5da42017-01-12 05:15:36 -08001675 RTC_DCHECK(sent < 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001676 error_ = port_->GetError();
zhihuang5ecf16c2016-06-01 17:09:15 -07001677 stats_.sent_discarded_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001678 } else {
Tim Psiaki63046262015-09-14 10:38:08 -07001679 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001680 }
1681 return sent;
1682}
1683
Steve Anton1cf1b7d2017-10-30 10:00:15 -07001684int ProxyConnection::GetError() {
1685 return error_;
1686}
1687
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001688} // namespace cricket