blob: 7410b20bf4c20bf53694175742c0c4dab4de96d2 [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "webrtc/p2p/base/port.h"
12
13#include <algorithm>
14#include <vector>
15
16#include "webrtc/p2p/base/common.h"
17#include "webrtc/p2p/base/portallocator.h"
18#include "webrtc/base/base64.h"
nissec80e7412017-01-11 05:56:46 -080019#include "webrtc/base/checks.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000020#include "webrtc/base/crc32.h"
21#include "webrtc/base/helpers.h"
22#include "webrtc/base/logging.h"
23#include "webrtc/base/messagedigest.h"
honghaize3c6c822016-02-17 13:00:28 -080024#include "webrtc/base/network.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000025#include "webrtc/base/stringencode.h"
26#include "webrtc/base/stringutils.h"
27
28namespace {
29
30// Determines whether we have seen at least the given maximum number of
31// pings fail to have a response.
32inline bool TooManyFailures(
Peter Thatcher1cf6f812015-05-15 10:40:45 -070033 const std::vector<cricket::Connection::SentPing>& pings_since_last_response,
Peter Boström0c4e06b2015-10-07 12:23:21 +020034 uint32_t maximum_failures,
honghaiz34b11eb2016-03-16 08:55:44 -070035 int rtt_estimate,
36 int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000037 // If we haven't sent that many pings, then we can't have failed that many.
38 if (pings_since_last_response.size() < maximum_failures)
39 return false;
40
41 // Check if the window in which we would expect a response to the ping has
42 // already elapsed.
honghaiz34b11eb2016-03-16 08:55:44 -070043 int64_t expected_response_time =
Peter Thatcher1cf6f812015-05-15 10:40:45 -070044 pings_since_last_response[maximum_failures - 1].sent_time + rtt_estimate;
45 return now > expected_response_time;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000046}
47
48// Determines whether we have gone too long without seeing any response.
49inline bool TooLongWithoutResponse(
Peter Thatcher1cf6f812015-05-15 10:40:45 -070050 const std::vector<cricket::Connection::SentPing>& pings_since_last_response,
honghaiz34b11eb2016-03-16 08:55:44 -070051 int64_t maximum_time,
52 int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000053 if (pings_since_last_response.size() == 0)
54 return false;
55
Peter Thatcher1cf6f812015-05-15 10:40:45 -070056 auto first = pings_since_last_response[0];
57 return now > (first.sent_time + maximum_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000058}
59
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000060// We will restrict RTT estimates (when used for determining state) to be
61// within a reasonable range.
honghaiz34b11eb2016-03-16 08:55:44 -070062const int MINIMUM_RTT = 100; // 0.1 seconds
skvlad51072462017-02-02 11:50:14 -080063const int MAXIMUM_RTT = 60000; // 60 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000064
65// When we don't have any RTT data, we have to pick something reasonable. We
66// use a large value just in case the connection is really slow.
skvlad51072462017-02-02 11:50:14 -080067const int DEFAULT_RTT = 3000; // 3 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000068
69// Computes our estimate of the RTT given the current estimate.
honghaiz34b11eb2016-03-16 08:55:44 -070070inline int ConservativeRTTEstimate(int rtt) {
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000071 return std::max(MINIMUM_RTT, std::min(MAXIMUM_RTT, 2 * rtt));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000072}
73
74// Weighting of the old rtt value to new data.
75const int RTT_RATIO = 3; // 3 : 1
76
pthatcher94a2f212017-02-08 14:42:22 -080077// The delay before we begin checking if this port is useless. We set
78// it to a little higher than a total STUN timeout.
79const int kPortTimeoutDelay = cricket::STUN_TOTAL_TIMEOUT + 5000;
Honghai Zhang351d77b2016-05-20 15:08:29 -070080} // namespace
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000081
82namespace cricket {
83
84// TODO(ronghuawu): Use "host", "srflx", "prflx" and "relay". But this requires
85// the signaling part be updated correspondingly as well.
86const char LOCAL_PORT_TYPE[] = "local";
87const char STUN_PORT_TYPE[] = "stun";
88const char PRFLX_PORT_TYPE[] = "prflx";
89const char RELAY_PORT_TYPE[] = "relay";
90
91const char UDP_PROTOCOL_NAME[] = "udp";
92const char TCP_PROTOCOL_NAME[] = "tcp";
93const char SSLTCP_PROTOCOL_NAME[] = "ssltcp";
hnsl277b2502016-12-13 05:17:23 -080094const char TLS_PROTOCOL_NAME[] = "tls";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000095
hnsl277b2502016-12-13 05:17:23 -080096static const char* const PROTO_NAMES[] = {UDP_PROTOCOL_NAME, TCP_PROTOCOL_NAME,
97 SSLTCP_PROTOCOL_NAME,
98 TLS_PROTOCOL_NAME};
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000099
100const char* ProtoToString(ProtocolType proto) {
101 return PROTO_NAMES[proto];
102}
103
104bool StringToProto(const char* value, ProtocolType* proto) {
105 for (size_t i = 0; i <= PROTO_LAST; ++i) {
106 if (_stricmp(PROTO_NAMES[i], value) == 0) {
107 *proto = static_cast<ProtocolType>(i);
108 return true;
109 }
110 }
111 return false;
112}
113
114// RFC 6544, TCP candidate encoding rules.
115const int DISCARD_PORT = 9;
116const char TCPTYPE_ACTIVE_STR[] = "active";
117const char TCPTYPE_PASSIVE_STR[] = "passive";
118const char TCPTYPE_SIMOPEN_STR[] = "so";
119
120// Foundation: An arbitrary string that is the same for two candidates
121// that have the same type, base IP address, protocol (UDP, TCP,
122// etc.), and STUN or TURN server. If any of these are different,
123// then the foundation will be different. Two candidate pairs with
124// the same foundation pairs are likely to have similar network
125// characteristics. Foundations are used in the frozen algorithm.
Honghai Zhang80f1db92016-01-27 11:54:45 -0800126static std::string ComputeFoundation(const std::string& type,
127 const std::string& protocol,
128 const std::string& relay_protocol,
129 const rtc::SocketAddress& base_address) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000130 std::ostringstream ost;
Honghai Zhang80f1db92016-01-27 11:54:45 -0800131 ost << type << base_address.ipaddr().ToString() << protocol << relay_protocol;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200132 return rtc::ToString<uint32_t>(rtc::ComputeCrc32(ost.str()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000133}
134
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000135Port::Port(rtc::Thread* thread,
Honghai Zhangd00c0572016-06-28 09:44:47 -0700136 const std::string& type,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000137 rtc::PacketSocketFactory* factory,
138 rtc::Network* network,
139 const rtc::IPAddress& ip,
140 const std::string& username_fragment,
141 const std::string& password)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000142 : thread_(thread),
143 factory_(factory),
Honghai Zhangd00c0572016-06-28 09:44:47 -0700144 type_(type),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000145 send_retransmit_count_attribute_(false),
146 network_(network),
147 ip_(ip),
148 min_port_(0),
149 max_port_(0),
150 component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
151 generation_(0),
152 ice_username_fragment_(username_fragment),
153 password_(password),
154 timeout_delay_(kPortTimeoutDelay),
155 enable_port_packets_(false),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000156 ice_role_(ICEROLE_UNKNOWN),
157 tiebreaker_(0),
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700158 shared_socket_(true) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000159 Construct();
160}
161
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000162Port::Port(rtc::Thread* thread,
163 const std::string& type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000164 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000165 rtc::Network* network,
166 const rtc::IPAddress& ip,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200167 uint16_t min_port,
168 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000169 const std::string& username_fragment,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000170 const std::string& password)
171 : thread_(thread),
172 factory_(factory),
173 type_(type),
174 send_retransmit_count_attribute_(false),
175 network_(network),
176 ip_(ip),
177 min_port_(min_port),
178 max_port_(max_port),
179 component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
180 generation_(0),
181 ice_username_fragment_(username_fragment),
182 password_(password),
183 timeout_delay_(kPortTimeoutDelay),
184 enable_port_packets_(false),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000185 ice_role_(ICEROLE_UNKNOWN),
186 tiebreaker_(0),
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700187 shared_socket_(false) {
nisseede5da42017-01-12 05:15:36 -0800188 RTC_DCHECK(factory_ != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000189 Construct();
190}
191
192void Port::Construct() {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700193 // TODO(pthatcher): Remove this old behavior once we're sure no one
194 // relies on it. If the username_fragment and password are empty,
195 // we should just create one.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000196 if (ice_username_fragment_.empty()) {
nisseede5da42017-01-12 05:15:36 -0800197 RTC_DCHECK(password_.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000198 ice_username_fragment_ = rtc::CreateRandomString(ICE_UFRAG_LENGTH);
199 password_ = rtc::CreateRandomString(ICE_PWD_LENGTH);
200 }
Honghai Zhang351d77b2016-05-20 15:08:29 -0700201 network_->SignalTypeChanged.connect(this, &Port::OnNetworkTypeChanged);
202 network_cost_ = network_->GetCost();
honghaize1a0c942016-02-16 14:54:56 -0800203
Honghai Zhanga74363c2016-07-28 18:06:15 -0700204 thread_->PostDelayed(RTC_FROM_HERE, timeout_delay_, this,
205 MSG_DESTROY_IF_DEAD);
Honghai Zhang351d77b2016-05-20 15:08:29 -0700206 LOG_J(LS_INFO, this) << "Port created with network cost " << network_cost_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000207}
208
209Port::~Port() {
210 // Delete all of the remaining connections. We copy the list up front
211 // because each deletion will cause it to be modified.
212
213 std::vector<Connection*> list;
214
215 AddressMap::iterator iter = connections_.begin();
216 while (iter != connections_.end()) {
217 list.push_back(iter->second);
218 ++iter;
219 }
220
Peter Boström0c4e06b2015-10-07 12:23:21 +0200221 for (uint32_t i = 0; i < list.size(); i++)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000222 delete list[i];
223}
224
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700225void Port::SetIceParameters(int component,
226 const std::string& username_fragment,
227 const std::string& password) {
228 component_ = component;
229 ice_username_fragment_ = username_fragment;
230 password_ = password;
231 for (Candidate& c : candidates_) {
232 c.set_component(component);
233 c.set_username(username_fragment);
234 c.set_password(password);
235 }
236}
237
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000238Connection* Port::GetConnection(const rtc::SocketAddress& remote_addr) {
239 AddressMap::const_iterator iter = connections_.find(remote_addr);
240 if (iter != connections_.end())
241 return iter->second;
242 else
243 return NULL;
244}
245
246void Port::AddAddress(const rtc::SocketAddress& address,
247 const rtc::SocketAddress& base_address,
248 const rtc::SocketAddress& related_address,
249 const std::string& protocol,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700250 const std::string& relay_protocol,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000251 const std::string& tcptype,
252 const std::string& type,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200253 uint32_t type_preference,
254 uint32_t relay_preference,
Peter Boström2758c662017-02-13 20:33:27 -0500255 bool final) {
256 AddAddress(address, base_address, related_address, protocol, relay_protocol,
257 tcptype, type, type_preference, relay_preference, "", final);
258}
259
260void Port::AddAddress(const rtc::SocketAddress& address,
261 const rtc::SocketAddress& base_address,
262 const rtc::SocketAddress& related_address,
263 const std::string& protocol,
264 const std::string& relay_protocol,
265 const std::string& tcptype,
266 const std::string& type,
267 uint32_t type_preference,
268 uint32_t relay_preference,
zhihuang26d99c22017-02-13 12:47:27 -0800269 const std::string& url,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000270 bool final) {
271 if (protocol == TCP_PROTOCOL_NAME && type == LOCAL_PORT_TYPE) {
nisseede5da42017-01-12 05:15:36 -0800272 RTC_DCHECK(!tcptype.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000273 }
274
honghaiza0c44ea2016-03-23 16:07:48 -0700275 std::string foundation =
276 ComputeFoundation(type, protocol, relay_protocol, base_address);
277 Candidate c(component_, protocol, address, 0U, username_fragment(), password_,
278 type, generation_, foundation, network_->id(), network_cost_);
279 c.set_priority(
280 c.GetPriority(type_preference, network_->preference(), relay_preference));
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700281 c.set_relay_protocol(relay_protocol);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000282 c.set_tcptype(tcptype);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000283 c.set_network_name(network_->name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +0000284 c.set_network_type(network_->type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000285 c.set_related_address(related_address);
zhihuang26d99c22017-02-13 12:47:27 -0800286 c.set_url(url);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000287 candidates_.push_back(c);
288 SignalCandidateReady(this, c);
289
290 if (final) {
291 SignalPortComplete(this);
292 }
293}
294
honghaiz36f50e82016-06-01 15:57:03 -0700295void Port::AddOrReplaceConnection(Connection* conn) {
296 auto ret = connections_.insert(
297 std::make_pair(conn->remote_candidate().address(), conn));
298 // If there is a different connection on the same remote address, replace
299 // it with the new one and destroy the old one.
300 if (ret.second == false && ret.first->second != conn) {
301 LOG_J(LS_WARNING, this)
302 << "A new connection was created on an existing remote address. "
303 << "New remote candidate: " << conn->remote_candidate().ToString();
304 ret.first->second->SignalDestroyed.disconnect(this);
305 ret.first->second->Destroy();
306 ret.first->second = conn;
307 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000308 conn->SignalDestroyed.connect(this, &Port::OnConnectionDestroyed);
309 SignalConnectionCreated(this, conn);
310}
311
312void Port::OnReadPacket(
313 const char* data, size_t size, const rtc::SocketAddress& addr,
314 ProtocolType proto) {
315 // If the user has enabled port packets, just hand this over.
316 if (enable_port_packets_) {
317 SignalReadPacket(this, data, size, addr);
318 return;
319 }
320
321 // If this is an authenticated STUN request, then signal unknown address and
322 // send back a proper binding response.
kwiberg3ec46792016-04-27 07:22:53 -0700323 std::unique_ptr<IceMessage> msg;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000324 std::string remote_username;
kwiberg6baec032016-03-15 11:09:39 -0700325 if (!GetStunMessage(data, size, addr, &msg, &remote_username)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000326 LOG_J(LS_ERROR, this) << "Received non-STUN packet from unknown address ("
327 << addr.ToSensitiveString() << ")";
328 } else if (!msg) {
329 // STUN message handled already
330 } else if (msg->type() == STUN_BINDING_REQUEST) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700331 LOG(LS_INFO) << "Received STUN ping "
332 << " id=" << rtc::hex_encode(msg->transaction_id())
333 << " from unknown address " << addr.ToSensitiveString();
334
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000335 // Check for role conflicts.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700336 if (!MaybeIceRoleConflict(addr, msg.get(), remote_username)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000337 LOG(LS_INFO) << "Received conflicting role from the peer.";
338 return;
339 }
340
341 SignalUnknownAddress(this, addr, proto, msg.get(), remote_username, false);
342 } else {
343 // NOTE(tschmelcher): STUN_BINDING_RESPONSE is benign. It occurs if we
344 // pruned a connection for this port while it had STUN requests in flight,
345 // because we then get back responses for them, which this code correctly
346 // does not handle.
347 if (msg->type() != STUN_BINDING_RESPONSE) {
348 LOG_J(LS_ERROR, this) << "Received unexpected STUN message type ("
349 << msg->type() << ") from unknown address ("
350 << addr.ToSensitiveString() << ")";
351 }
352 }
353}
354
355void Port::OnReadyToSend() {
356 AddressMap::iterator iter = connections_.begin();
357 for (; iter != connections_.end(); ++iter) {
358 iter->second->OnReadyToSend();
359 }
360}
361
362size_t Port::AddPrflxCandidate(const Candidate& local) {
363 candidates_.push_back(local);
364 return (candidates_.size() - 1);
365}
366
kwiberg6baec032016-03-15 11:09:39 -0700367bool Port::GetStunMessage(const char* data,
368 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000369 const rtc::SocketAddress& addr,
kwiberg3ec46792016-04-27 07:22:53 -0700370 std::unique_ptr<IceMessage>* out_msg,
kwiberg6baec032016-03-15 11:09:39 -0700371 std::string* out_username) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000372 // NOTE: This could clearly be optimized to avoid allocating any memory.
373 // However, at the data rates we'll be looking at on the client side,
374 // this probably isn't worth worrying about.
nisseede5da42017-01-12 05:15:36 -0800375 RTC_DCHECK(out_msg != NULL);
376 RTC_DCHECK(out_username != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000377 out_username->clear();
378
379 // Don't bother parsing the packet if we can tell it's not STUN.
380 // In ICE mode, all STUN packets will have a valid fingerprint.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700381 if (!StunMessage::ValidateFingerprint(data, size)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000382 return false;
383 }
384
385 // Parse the request message. If the packet is not a complete and correct
386 // STUN message, then ignore it.
kwiberg3ec46792016-04-27 07:22:53 -0700387 std::unique_ptr<IceMessage> stun_msg(new IceMessage());
jbauchf1f87202016-03-30 06:43:37 -0700388 rtc::ByteBufferReader buf(data, size);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000389 if (!stun_msg->Read(&buf) || (buf.Length() > 0)) {
390 return false;
391 }
392
393 if (stun_msg->type() == STUN_BINDING_REQUEST) {
394 // Check for the presence of USERNAME and MESSAGE-INTEGRITY (if ICE) first.
395 // If not present, fail with a 400 Bad Request.
396 if (!stun_msg->GetByteString(STUN_ATTR_USERNAME) ||
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700397 !stun_msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000398 LOG_J(LS_ERROR, this) << "Received STUN request without username/M-I "
399 << "from " << addr.ToSensitiveString();
400 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_BAD_REQUEST,
401 STUN_ERROR_REASON_BAD_REQUEST);
402 return true;
403 }
404
405 // If the username is bad or unknown, fail with a 401 Unauthorized.
406 std::string local_ufrag;
407 std::string remote_ufrag;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700408 if (!ParseStunUsername(stun_msg.get(), &local_ufrag, &remote_ufrag) ||
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000409 local_ufrag != username_fragment()) {
410 LOG_J(LS_ERROR, this) << "Received STUN request with bad local username "
411 << local_ufrag << " from "
412 << addr.ToSensitiveString();
413 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
414 STUN_ERROR_REASON_UNAUTHORIZED);
415 return true;
416 }
417
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000418 // If ICE, and the MESSAGE-INTEGRITY is bad, fail with a 401 Unauthorized
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700419 if (!stun_msg->ValidateMessageIntegrity(data, size, password_)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000420 LOG_J(LS_ERROR, this) << "Received STUN request with bad M-I "
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +0000421 << "from " << addr.ToSensitiveString()
422 << ", password_=" << password_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000423 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
424 STUN_ERROR_REASON_UNAUTHORIZED);
425 return true;
426 }
427 out_username->assign(remote_ufrag);
428 } else if ((stun_msg->type() == STUN_BINDING_RESPONSE) ||
429 (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE)) {
430 if (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE) {
431 if (const StunErrorCodeAttribute* error_code = stun_msg->GetErrorCode()) {
432 LOG_J(LS_ERROR, this) << "Received STUN binding error:"
433 << " class=" << error_code->eclass()
434 << " number=" << error_code->number()
435 << " reason='" << error_code->reason() << "'"
436 << " from " << addr.ToSensitiveString();
437 // Return message to allow error-specific processing
438 } else {
439 LOG_J(LS_ERROR, this) << "Received STUN binding error without a error "
440 << "code from " << addr.ToSensitiveString();
441 return true;
442 }
443 }
444 // NOTE: Username should not be used in verifying response messages.
445 out_username->clear();
446 } else if (stun_msg->type() == STUN_BINDING_INDICATION) {
447 LOG_J(LS_VERBOSE, this) << "Received STUN binding indication:"
448 << " from " << addr.ToSensitiveString();
449 out_username->clear();
450 // No stun attributes will be verified, if it's stun indication message.
451 // Returning from end of the this method.
452 } else {
453 LOG_J(LS_ERROR, this) << "Received STUN packet with invalid type ("
454 << stun_msg->type() << ") from "
455 << addr.ToSensitiveString();
456 return true;
457 }
458
459 // Return the STUN message found.
kwiberg6baec032016-03-15 11:09:39 -0700460 *out_msg = std::move(stun_msg);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000461 return true;
462}
463
464bool Port::IsCompatibleAddress(const rtc::SocketAddress& addr) {
465 int family = ip().family();
466 // We use single-stack sockets, so families must match.
467 if (addr.family() != family) {
468 return false;
469 }
470 // Link-local IPv6 ports can only connect to other link-local IPv6 ports.
Peter Thatcherb8b01432015-07-07 16:45:53 -0700471 if (family == AF_INET6 &&
472 (IPIsLinkLocal(ip()) != IPIsLinkLocal(addr.ipaddr()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000473 return false;
474 }
475 return true;
476}
477
478bool Port::ParseStunUsername(const StunMessage* stun_msg,
479 std::string* local_ufrag,
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700480 std::string* remote_ufrag) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000481 // The packet must include a username that either begins or ends with our
482 // fragment. It should begin with our fragment if it is a request and it
483 // should end with our fragment if it is a response.
484 local_ufrag->clear();
485 remote_ufrag->clear();
486 const StunByteStringAttribute* username_attr =
487 stun_msg->GetByteString(STUN_ATTR_USERNAME);
488 if (username_attr == NULL)
489 return false;
490
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700491 // RFRAG:LFRAG
492 const std::string username = username_attr->GetString();
493 size_t colon_pos = username.find(":");
494 if (colon_pos == std::string::npos) {
495 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000496 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000497
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700498 *local_ufrag = username.substr(0, colon_pos);
499 *remote_ufrag = username.substr(colon_pos + 1, username.size());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000500 return true;
501}
502
503bool Port::MaybeIceRoleConflict(
504 const rtc::SocketAddress& addr, IceMessage* stun_msg,
505 const std::string& remote_ufrag) {
506 // Validate ICE_CONTROLLING or ICE_CONTROLLED attributes.
507 bool ret = true;
508 IceRole remote_ice_role = ICEROLE_UNKNOWN;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200509 uint64_t remote_tiebreaker = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000510 const StunUInt64Attribute* stun_attr =
511 stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
512 if (stun_attr) {
513 remote_ice_role = ICEROLE_CONTROLLING;
514 remote_tiebreaker = stun_attr->value();
515 }
516
517 // If |remote_ufrag| is same as port local username fragment and
518 // tie breaker value received in the ping message matches port
519 // tiebreaker value this must be a loopback call.
520 // We will treat this as valid scenario.
521 if (remote_ice_role == ICEROLE_CONTROLLING &&
522 username_fragment() == remote_ufrag &&
523 remote_tiebreaker == IceTiebreaker()) {
524 return true;
525 }
526
527 stun_attr = stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
528 if (stun_attr) {
529 remote_ice_role = ICEROLE_CONTROLLED;
530 remote_tiebreaker = stun_attr->value();
531 }
532
533 switch (ice_role_) {
534 case ICEROLE_CONTROLLING:
535 if (ICEROLE_CONTROLLING == remote_ice_role) {
536 if (remote_tiebreaker >= tiebreaker_) {
537 SignalRoleConflict(this);
538 } else {
539 // Send Role Conflict (487) error response.
540 SendBindingErrorResponse(stun_msg, addr,
541 STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
542 ret = false;
543 }
544 }
545 break;
546 case ICEROLE_CONTROLLED:
547 if (ICEROLE_CONTROLLED == remote_ice_role) {
548 if (remote_tiebreaker < tiebreaker_) {
549 SignalRoleConflict(this);
550 } else {
551 // Send Role Conflict (487) error response.
552 SendBindingErrorResponse(stun_msg, addr,
553 STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
554 ret = false;
555 }
556 }
557 break;
558 default:
nissec80e7412017-01-11 05:56:46 -0800559 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000560 }
561 return ret;
562}
563
564void Port::CreateStunUsername(const std::string& remote_username,
565 std::string* stun_username_attr_str) const {
566 stun_username_attr_str->clear();
567 *stun_username_attr_str = remote_username;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700568 stun_username_attr_str->append(":");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000569 stun_username_attr_str->append(username_fragment());
570}
571
572void Port::SendBindingResponse(StunMessage* request,
573 const rtc::SocketAddress& addr) {
nisseede5da42017-01-12 05:15:36 -0800574 RTC_DCHECK(request->type() == STUN_BINDING_REQUEST);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000575
576 // Retrieve the username from the request.
577 const StunByteStringAttribute* username_attr =
578 request->GetByteString(STUN_ATTR_USERNAME);
nisseede5da42017-01-12 05:15:36 -0800579 RTC_DCHECK(username_attr != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000580 if (username_attr == NULL) {
581 // No valid username, skip the response.
582 return;
583 }
584
585 // Fill in the response message.
586 StunMessage response;
587 response.SetType(STUN_BINDING_RESPONSE);
588 response.SetTransactionID(request->transaction_id());
589 const StunUInt32Attribute* retransmit_attr =
590 request->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
591 if (retransmit_attr) {
592 // Inherit the incoming retransmit value in the response so the other side
593 // can see our view of lost pings.
594 response.AddAttribute(new StunUInt32Attribute(
595 STUN_ATTR_RETRANSMIT_COUNT, retransmit_attr->value()));
596
597 if (retransmit_attr->value() > CONNECTION_WRITE_CONNECT_FAILURES) {
598 LOG_J(LS_INFO, this)
599 << "Received a remote ping with high retransmit count: "
600 << retransmit_attr->value();
601 }
602 }
603
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700604 response.AddAttribute(
605 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, addr));
606 response.AddMessageIntegrity(password_);
607 response.AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000608
609 // Send the response message.
jbauchf1f87202016-03-30 06:43:37 -0700610 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000611 response.Write(&buf);
612 rtc::PacketOptions options(DefaultDscpValue());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700613 auto err = SendTo(buf.Data(), buf.Length(), addr, options, false);
614 if (err < 0) {
615 LOG_J(LS_ERROR, this)
616 << "Failed to send STUN ping response"
617 << ", to=" << addr.ToSensitiveString()
618 << ", err=" << err
619 << ", id=" << rtc::hex_encode(response.transaction_id());
620 } else {
621 // Log at LS_INFO if we send a stun ping response on an unwritable
622 // connection.
honghaiz9b5ee9c2015-11-11 13:19:17 -0800623 Connection* conn = GetConnection(addr);
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700624 rtc::LoggingSeverity sev = (conn && !conn->writable()) ?
625 rtc::LS_INFO : rtc::LS_VERBOSE;
626 LOG_JV(sev, this)
627 << "Sent STUN ping response"
628 << ", to=" << addr.ToSensitiveString()
629 << ", id=" << rtc::hex_encode(response.transaction_id());
zhihuang5ecf16c2016-06-01 17:09:15 -0700630
631 conn->stats_.sent_ping_responses++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000632 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000633}
634
635void Port::SendBindingErrorResponse(StunMessage* request,
636 const rtc::SocketAddress& addr,
637 int error_code, const std::string& reason) {
nisseede5da42017-01-12 05:15:36 -0800638 RTC_DCHECK(request->type() == STUN_BINDING_REQUEST);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000639
640 // Fill in the response message.
641 StunMessage response;
642 response.SetType(STUN_BINDING_ERROR_RESPONSE);
643 response.SetTransactionID(request->transaction_id());
644
645 // When doing GICE, we need to write out the error code incorrectly to
646 // maintain backwards compatiblility.
647 StunErrorCodeAttribute* error_attr = StunAttribute::CreateErrorCode();
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700648 error_attr->SetCode(error_code);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000649 error_attr->SetReason(reason);
650 response.AddAttribute(error_attr);
651
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700652 // Per Section 10.1.2, certain error cases don't get a MESSAGE-INTEGRITY,
653 // because we don't have enough information to determine the shared secret.
654 if (error_code != STUN_ERROR_BAD_REQUEST &&
655 error_code != STUN_ERROR_UNAUTHORIZED)
656 response.AddMessageIntegrity(password_);
657 response.AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000658
659 // Send the response message.
jbauchf1f87202016-03-30 06:43:37 -0700660 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000661 response.Write(&buf);
662 rtc::PacketOptions options(DefaultDscpValue());
663 SendTo(buf.Data(), buf.Length(), addr, options, false);
664 LOG_J(LS_INFO, this) << "Sending STUN binding error: reason=" << reason
665 << " to " << addr.ToSensitiveString();
666}
667
Honghai Zhanga74363c2016-07-28 18:06:15 -0700668void Port::KeepAliveUntilPruned() {
669 // If it is pruned, we won't bring it up again.
670 if (state_ == State::INIT) {
671 state_ = State::KEEP_ALIVE_UNTIL_PRUNED;
672 }
673}
674
675void Port::Prune() {
676 state_ = State::PRUNED;
677 thread_->Post(RTC_FROM_HERE, this, MSG_DESTROY_IF_DEAD);
678}
679
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000680void Port::OnMessage(rtc::Message *pmsg) {
nisseede5da42017-01-12 05:15:36 -0800681 RTC_DCHECK(pmsg->message_id == MSG_DESTROY_IF_DEAD);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700682 bool dead =
683 (state_ == State::INIT || state_ == State::PRUNED) &&
684 connections_.empty() &&
685 rtc::TimeMillis() - last_time_all_connections_removed_ >= timeout_delay_;
686 if (dead) {
honghaizd0b31432015-09-30 12:42:17 -0700687 Destroy();
688 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000689}
690
Honghai Zhang351d77b2016-05-20 15:08:29 -0700691void Port::OnNetworkTypeChanged(const rtc::Network* network) {
nisseede5da42017-01-12 05:15:36 -0800692 RTC_DCHECK(network == network_);
Honghai Zhang351d77b2016-05-20 15:08:29 -0700693
694 UpdateNetworkCost();
695}
696
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000697std::string Port::ToString() const {
698 std::stringstream ss;
honghaize3c6c822016-02-17 13:00:28 -0800699 ss << "Port[" << std::hex << this << std::dec << ":" << content_name_ << ":"
700 << component_ << ":" << generation_ << ":" << type_ << ":"
701 << network_->ToString() << "]";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000702 return ss.str();
703}
704
Honghai Zhang351d77b2016-05-20 15:08:29 -0700705// TODO(honghaiz): Make the network cost configurable from user setting.
706void Port::UpdateNetworkCost() {
707 uint16_t new_cost = network_->GetCost();
708 if (network_cost_ == new_cost) {
709 return;
710 }
711 LOG(LS_INFO) << "Network cost changed from " << network_cost_
712 << " to " << new_cost
713 << ". Number of candidates created: " << candidates_.size()
714 << ". Number of connections created: " << connections_.size();
715 network_cost_ = new_cost;
716 for (cricket::Candidate& candidate : candidates_) {
717 candidate.set_network_cost(network_cost_);
718 }
719 // Network cost change will affect the connection selection criteria.
720 // Signal the connection state change on each connection to force a
721 // re-sort in P2PTransportChannel.
722 for (auto kv : connections_) {
723 Connection* conn = kv.second;
724 conn->SignalStateChange(conn);
725 }
726}
727
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000728void Port::EnablePortPackets() {
729 enable_port_packets_ = true;
730}
731
732void Port::OnConnectionDestroyed(Connection* conn) {
733 AddressMap::iterator iter =
734 connections_.find(conn->remote_candidate().address());
nisseede5da42017-01-12 05:15:36 -0800735 RTC_DCHECK(iter != connections_.end());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000736 connections_.erase(iter);
honghaiz36f50e82016-06-01 15:57:03 -0700737 HandleConnectionDestroyed(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000738
Honghai Zhanga74363c2016-07-28 18:06:15 -0700739 // Ports time out after all connections fail if it is not marked as
740 // "keep alive until pruned."
honghaizd0b31432015-09-30 12:42:17 -0700741 // Note: If a new connection is added after this message is posted, but it
742 // fails and is removed before kPortTimeoutDelay, then this message will
Honghai Zhangb5db1ec2016-07-28 13:23:05 -0700743 // not cause the Port to be destroyed.
Honghai Zhanga74363c2016-07-28 18:06:15 -0700744 if (connections_.empty()) {
Honghai Zhangb5db1ec2016-07-28 13:23:05 -0700745 last_time_all_connections_removed_ = rtc::TimeMillis();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700746 thread_->PostDelayed(RTC_FROM_HERE, timeout_delay_, this,
747 MSG_DESTROY_IF_DEAD);
honghaizd0b31432015-09-30 12:42:17 -0700748 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000749}
750
751void Port::Destroy() {
nisseede5da42017-01-12 05:15:36 -0800752 RTC_DCHECK(connections_.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000753 LOG_J(LS_INFO, this) << "Port deleted";
754 SignalDestroyed(this);
755 delete this;
756}
757
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000758const std::string Port::username_fragment() const {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700759 return ice_username_fragment_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000760}
761
762// A ConnectionRequest is a simple STUN ping used to determine writability.
763class ConnectionRequest : public StunRequest {
764 public:
765 explicit ConnectionRequest(Connection* connection)
766 : StunRequest(new IceMessage()),
767 connection_(connection) {
768 }
769
770 virtual ~ConnectionRequest() {
771 }
772
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700773 void Prepare(StunMessage* request) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000774 request->SetType(STUN_BINDING_REQUEST);
775 std::string username;
776 connection_->port()->CreateStunUsername(
777 connection_->remote_candidate().username(), &username);
778 request->AddAttribute(
779 new StunByteStringAttribute(STUN_ATTR_USERNAME, username));
780
781 // connection_ already holds this ping, so subtract one from count.
782 if (connection_->port()->send_retransmit_count_attribute()) {
783 request->AddAttribute(new StunUInt32Attribute(
784 STUN_ATTR_RETRANSMIT_COUNT,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200785 static_cast<uint32_t>(connection_->pings_since_last_response_.size() -
786 1)));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000787 }
honghaiza0c44ea2016-03-23 16:07:48 -0700788 uint32_t network_info = connection_->port()->Network()->id();
789 network_info = (network_info << 16) | connection_->port()->network_cost();
790 request->AddAttribute(
791 new StunUInt32Attribute(STUN_ATTR_NETWORK_INFO, network_info));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000792
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700793 // Adding ICE_CONTROLLED or ICE_CONTROLLING attribute based on the role.
794 if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLING) {
795 request->AddAttribute(new StunUInt64Attribute(
796 STUN_ATTR_ICE_CONTROLLING, connection_->port()->IceTiebreaker()));
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700797 // We should have either USE_CANDIDATE attribute or ICE_NOMINATION
798 // attribute but not both. That was enforced in p2ptransportchannel.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700799 if (connection_->use_candidate_attr()) {
800 request->AddAttribute(new StunByteStringAttribute(
801 STUN_ATTR_USE_CANDIDATE));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000802 }
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700803 if (connection_->nomination() &&
804 connection_->nomination() != connection_->acked_nomination()) {
805 request->AddAttribute(new StunUInt32Attribute(
806 STUN_ATTR_NOMINATION, connection_->nomination()));
807 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700808 } else if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLED) {
809 request->AddAttribute(new StunUInt64Attribute(
810 STUN_ATTR_ICE_CONTROLLED, connection_->port()->IceTiebreaker()));
811 } else {
nissec80e7412017-01-11 05:56:46 -0800812 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000813 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700814
815 // Adding PRIORITY Attribute.
816 // Changing the type preference to Peer Reflexive and local preference
817 // and component id information is unchanged from the original priority.
818 // priority = (2^24)*(type preference) +
819 // (2^8)*(local preference) +
820 // (2^0)*(256 - component ID)
Taylor Brandstetter62351c92016-08-11 16:05:07 -0700821 uint32_t type_preference =
822 (connection_->local_candidate().protocol() == TCP_PROTOCOL_NAME)
823 ? ICE_TYPE_PREFERENCE_PRFLX_TCP
824 : ICE_TYPE_PREFERENCE_PRFLX;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200825 uint32_t prflx_priority =
Taylor Brandstetter62351c92016-08-11 16:05:07 -0700826 type_preference << 24 |
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700827 (connection_->local_candidate().priority() & 0x00FFFFFF);
828 request->AddAttribute(
829 new StunUInt32Attribute(STUN_ATTR_PRIORITY, prflx_priority));
830
831 // Adding Message Integrity attribute.
832 request->AddMessageIntegrity(connection_->remote_candidate().password());
833 // Adding Fingerprint.
834 request->AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000835 }
836
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700837 void OnResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000838 connection_->OnConnectionRequestResponse(this, response);
839 }
840
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700841 void OnErrorResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000842 connection_->OnConnectionRequestErrorResponse(this, response);
843 }
844
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700845 void OnTimeout() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000846 connection_->OnConnectionRequestTimeout(this);
847 }
848
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700849 void OnSent() override {
850 connection_->OnConnectionRequestSent(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000851 // Each request is sent only once. After a single delay , the request will
852 // time out.
853 timeout_ = true;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700854 }
855
856 int resend_delay() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000857 return CONNECTION_RESPONSE_TIMEOUT;
858 }
859
860 private:
861 Connection* connection_;
862};
863
864//
865// Connection
866//
867
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000868Connection::Connection(Port* port,
869 size_t index,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000870 const Candidate& remote_candidate)
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000871 : port_(port),
872 local_candidate_index_(index),
873 remote_candidate_(remote_candidate),
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700874 recv_rate_tracker_(100, 10u),
875 send_rate_tracker_(100, 10u),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000876 write_state_(STATE_WRITE_INIT),
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700877 receiving_(false),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000878 connected_(true),
879 pruned_(false),
880 use_candidate_attr_(false),
881 remote_ice_mode_(ICEMODE_FULL),
882 requests_(port->thread()),
883 rtt_(DEFAULT_RTT),
884 last_ping_sent_(0),
885 last_ping_received_(0),
886 last_data_received_(0),
887 last_ping_response_received_(0),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000888 reported_(false),
hbos06495bc2017-01-02 08:08:18 -0800889 state_(IceCandidatePairState::WAITING),
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700890 receiving_timeout_(WEAK_CONNECTION_RECEIVE_TIMEOUT),
nisse1bffc1d2016-05-02 08:18:55 -0700891 time_created_ms_(rtc::TimeMillis()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000892 // All of our connections start in WAITING state.
893 // TODO(mallinath) - Start connections from STATE_FROZEN.
894 // Wire up to send stun packets
895 requests_.SignalSendPacket.connect(this, &Connection::OnSendStunPacket);
896 LOG_J(LS_INFO, this) << "Connection created";
897}
898
899Connection::~Connection() {
900}
901
902const Candidate& Connection::local_candidate() const {
nisseede5da42017-01-12 05:15:36 -0800903 RTC_DCHECK(local_candidate_index_ < port_->Candidates().size());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000904 return port_->Candidates()[local_candidate_index_];
905}
906
Honghai Zhangcc411c02016-03-29 17:27:21 -0700907const Candidate& Connection::remote_candidate() const {
908 return remote_candidate_;
909}
910
Peter Boström0c4e06b2015-10-07 12:23:21 +0200911uint64_t Connection::priority() const {
912 uint64_t priority = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000913 // RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs
914 // Let G be the priority for the candidate provided by the controlling
915 // agent. Let D be the priority for the candidate provided by the
916 // controlled agent.
917 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
918 IceRole role = port_->GetIceRole();
919 if (role != ICEROLE_UNKNOWN) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200920 uint32_t g = 0;
921 uint32_t d = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000922 if (role == ICEROLE_CONTROLLING) {
923 g = local_candidate().priority();
924 d = remote_candidate_.priority();
925 } else {
926 g = remote_candidate_.priority();
927 d = local_candidate().priority();
928 }
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000929 priority = std::min(g, d);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000930 priority = priority << 32;
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000931 priority += 2 * std::max(g, d) + (g > d ? 1 : 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000932 }
933 return priority;
934}
935
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000936void Connection::set_write_state(WriteState value) {
937 WriteState old_value = write_state_;
938 write_state_ = value;
939 if (value != old_value) {
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +0000940 LOG_J(LS_VERBOSE, this) << "set_write_state from: " << old_value << " to "
941 << value;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000942 SignalStateChange(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000943 }
944}
945
honghaiz9ad0db52016-07-14 19:30:28 -0700946void Connection::UpdateReceiving(int64_t now) {
honghaize58d73d2016-10-24 16:38:26 -0700947 bool receiving =
948 last_received() > 0 && now <= last_received() + receiving_timeout_;
honghaiz9ad0db52016-07-14 19:30:28 -0700949 if (receiving_ == receiving) {
950 return;
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700951 }
honghaiz9ad0db52016-07-14 19:30:28 -0700952 LOG_J(LS_VERBOSE, this) << "set_receiving to " << receiving;
953 receiving_ = receiving;
954 receiving_unchanged_since_ = now;
955 SignalStateChange(this);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700956}
957
hbos06495bc2017-01-02 08:08:18 -0800958void Connection::set_state(IceCandidatePairState state) {
959 IceCandidatePairState old_state = state_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000960 state_ = state;
961 if (state != old_state) {
962 LOG_J(LS_VERBOSE, this) << "set_state";
963 }
964}
965
966void Connection::set_connected(bool value) {
967 bool old_value = connected_;
968 connected_ = value;
969 if (value != old_value) {
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700970 LOG_J(LS_VERBOSE, this) << "set_connected from: " << old_value << " to "
971 << value;
Taylor Brandstetterb825aee2016-06-29 13:07:16 -0700972 SignalStateChange(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000973 }
974}
975
976void Connection::set_use_candidate_attr(bool enable) {
977 use_candidate_attr_ = enable;
978}
979
980void Connection::OnSendStunPacket(const void* data, size_t size,
981 StunRequest* req) {
982 rtc::PacketOptions options(port_->DefaultDscpValue());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700983 auto err = port_->SendTo(
984 data, size, remote_candidate_.address(), options, false);
985 if (err < 0) {
986 LOG_J(LS_WARNING, this) << "Failed to send STUN ping "
987 << " err=" << err
988 << " id=" << rtc::hex_encode(req->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000989 }
990}
991
992void Connection::OnReadPacket(
993 const char* data, size_t size, const rtc::PacketTime& packet_time) {
kwiberg3ec46792016-04-27 07:22:53 -0700994 std::unique_ptr<IceMessage> msg;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000995 std::string remote_ufrag;
996 const rtc::SocketAddress& addr(remote_candidate_.address());
kwiberg6baec032016-03-15 11:09:39 -0700997 if (!port_->GetStunMessage(data, size, addr, &msg, &remote_ufrag)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000998 // The packet did not parse as a valid STUN message
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700999 // This is a data packet, pass it along.
nisse1bffc1d2016-05-02 08:18:55 -07001000 last_data_received_ = rtc::TimeMillis();
honghaiz9ad0db52016-07-14 19:30:28 -07001001 UpdateReceiving(last_data_received_);
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001002 recv_rate_tracker_.AddSamples(size);
1003 SignalReadPacket(this, data, size, packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001004
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001005 // If timed out sending writability checks, start up again
1006 if (!pruned_ && (write_state_ == STATE_WRITE_TIMEOUT)) {
1007 LOG(LS_WARNING) << "Received a data packet on a timed-out Connection. "
1008 << "Resetting state to STATE_WRITE_INIT.";
1009 set_write_state(STATE_WRITE_INIT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001010 }
1011 } else if (!msg) {
1012 // The packet was STUN, but failed a check and was handled internally.
1013 } else {
1014 // The packet is STUN and passed the Port checks.
1015 // Perform our own checks to ensure this packet is valid.
honghaizd0b31432015-09-30 12:42:17 -07001016 // If this is a STUN request, then update the receiving bit and respond.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001017 // If this is a STUN response, then update the writable bit.
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001018 // Log at LS_INFO if we receive a ping on an unwritable connection.
1019 rtc::LoggingSeverity sev = (!writable() ? rtc::LS_INFO : rtc::LS_VERBOSE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001020 switch (msg->type()) {
1021 case STUN_BINDING_REQUEST:
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001022 LOG_JV(sev, this) << "Received STUN ping"
1023 << ", id=" << rtc::hex_encode(msg->transaction_id());
1024
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001025 if (remote_ufrag == remote_candidate_.username()) {
honghaiz9b5ee9c2015-11-11 13:19:17 -08001026 HandleBindingRequest(msg.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001027 } else {
1028 // The packet had the right local username, but the remote username
1029 // was not the right one for the remote address.
1030 LOG_J(LS_ERROR, this)
1031 << "Received STUN request with bad remote username "
1032 << remote_ufrag;
1033 port_->SendBindingErrorResponse(msg.get(), addr,
1034 STUN_ERROR_UNAUTHORIZED,
1035 STUN_ERROR_REASON_UNAUTHORIZED);
1036
1037 }
1038 break;
1039
1040 // Response from remote peer. Does it match request sent?
1041 // This doesn't just check, it makes callbacks if transaction
1042 // id's match.
1043 case STUN_BINDING_RESPONSE:
1044 case STUN_BINDING_ERROR_RESPONSE:
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001045 if (msg->ValidateMessageIntegrity(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001046 data, size, remote_candidate().password())) {
1047 requests_.CheckResponse(msg.get());
1048 }
1049 // Otherwise silently discard the response message.
1050 break;
1051
honghaizd0b31432015-09-30 12:42:17 -07001052 // Remote end point sent an STUN indication instead of regular binding
1053 // request. In this case |last_ping_received_| will be updated but no
1054 // response will be sent.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001055 case STUN_BINDING_INDICATION:
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001056 ReceivedPing();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001057 break;
1058
1059 default:
nissec80e7412017-01-11 05:56:46 -08001060 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001061 break;
1062 }
1063 }
1064}
1065
honghaiz9b5ee9c2015-11-11 13:19:17 -08001066void Connection::HandleBindingRequest(IceMessage* msg) {
1067 // This connection should now be receiving.
1068 ReceivedPing();
1069
1070 const rtc::SocketAddress& remote_addr = remote_candidate_.address();
1071 const std::string& remote_ufrag = remote_candidate_.username();
1072 // Check for role conflicts.
1073 if (!port_->MaybeIceRoleConflict(remote_addr, msg, remote_ufrag)) {
1074 // Received conflicting role from the peer.
1075 LOG(LS_INFO) << "Received conflicting role from the peer.";
1076 return;
1077 }
1078
zhihuang5ecf16c2016-06-01 17:09:15 -07001079 stats_.recv_ping_requests++;
1080
honghaiz9b5ee9c2015-11-11 13:19:17 -08001081 // This is a validated stun request from remote peer.
1082 port_->SendBindingResponse(msg, remote_addr);
1083
1084 // If it timed out on writing check, start up again
1085 if (!pruned_ && write_state_ == STATE_WRITE_TIMEOUT) {
1086 set_write_state(STATE_WRITE_INIT);
1087 }
1088
1089 if (port_->GetIceRole() == ICEROLE_CONTROLLED) {
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001090 const StunUInt32Attribute* nomination_attr =
1091 msg->GetUInt32(STUN_ATTR_NOMINATION);
1092 uint32_t nomination = 0;
1093 if (nomination_attr) {
1094 nomination = nomination_attr->value();
1095 if (nomination == 0) {
1096 LOG(LS_ERROR) << "Invalid nomination: " << nomination;
1097 }
1098 } else {
1099 const StunByteStringAttribute* use_candidate_attr =
1100 msg->GetByteString(STUN_ATTR_USE_CANDIDATE);
1101 if (use_candidate_attr) {
1102 nomination = 1;
1103 }
1104 }
1105 // We don't un-nominate a connection, so we only keep a larger nomination.
1106 if (nomination > remote_nomination_) {
1107 set_remote_nomination(nomination);
honghaiz9b5ee9c2015-11-11 13:19:17 -08001108 SignalNominated(this);
1109 }
1110 }
Honghai Zhang351d77b2016-05-20 15:08:29 -07001111 // Set the remote cost if the network_info attribute is available.
1112 // Note: If packets are re-ordered, we may get incorrect network cost
1113 // temporarily, but it should get the correct value shortly after that.
1114 const StunUInt32Attribute* network_attr =
1115 msg->GetUInt32(STUN_ATTR_NETWORK_INFO);
1116 if (network_attr) {
1117 uint32_t network_info = network_attr->value();
1118 uint16_t network_cost = static_cast<uint16_t>(network_info);
1119 if (network_cost != remote_candidate_.network_cost()) {
1120 remote_candidate_.set_network_cost(network_cost);
1121 // Network cost change will affect the connection ranking, so signal
1122 // state change to force a re-sort in P2PTransportChannel.
1123 SignalStateChange(this);
1124 }
1125 }
honghaiz9b5ee9c2015-11-11 13:19:17 -08001126}
1127
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001128void Connection::OnReadyToSend() {
deadbeefdd7fb432016-09-30 15:16:48 -07001129 SignalReadyToSend(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001130}
1131
1132void Connection::Prune() {
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001133 if (!pruned_ || active()) {
Honghai Zhang1590c392016-05-24 13:15:02 -07001134 LOG_J(LS_INFO, this) << "Connection pruned";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001135 pruned_ = true;
1136 requests_.Clear();
1137 set_write_state(STATE_WRITE_TIMEOUT);
1138 }
1139}
1140
1141void Connection::Destroy() {
1142 LOG_J(LS_VERBOSE, this) << "Connection destroyed";
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001143 port_->thread()->Post(RTC_FROM_HERE, this, MSG_DELETE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001144}
1145
deadbeef376e1232015-11-25 09:00:08 -08001146void Connection::FailAndDestroy() {
hbos06495bc2017-01-02 08:08:18 -08001147 set_state(IceCandidatePairState::FAILED);
deadbeef376e1232015-11-25 09:00:08 -08001148 Destroy();
1149}
1150
honghaiz079a7a12016-06-22 16:26:29 -07001151void Connection::FailAndPrune() {
hbos06495bc2017-01-02 08:08:18 -08001152 set_state(IceCandidatePairState::FAILED);
honghaiz079a7a12016-06-22 16:26:29 -07001153 Prune();
1154}
1155
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001156void Connection::PrintPingsSinceLastResponse(std::string* s, size_t max) {
1157 std::ostringstream oss;
1158 oss << std::boolalpha;
1159 if (pings_since_last_response_.size() > max) {
1160 for (size_t i = 0; i < max; i++) {
1161 const SentPing& ping = pings_since_last_response_[i];
1162 oss << rtc::hex_encode(ping.id) << " ";
1163 }
1164 oss << "... " << (pings_since_last_response_.size() - max) << " more";
1165 } else {
1166 for (const SentPing& ping : pings_since_last_response_) {
1167 oss << rtc::hex_encode(ping.id) << " ";
1168 }
1169 }
1170 *s = oss.str();
1171}
1172
honghaiz34b11eb2016-03-16 08:55:44 -07001173void Connection::UpdateState(int64_t now) {
1174 int rtt = ConservativeRTTEstimate(rtt_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001175
Peter Thatcherb2d26232015-05-15 11:25:14 -07001176 if (LOG_CHECK_LEVEL(LS_VERBOSE)) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001177 std::string pings;
1178 PrintPingsSinceLastResponse(&pings, 5);
1179 LOG_J(LS_VERBOSE, this) << "UpdateState()"
1180 << ", ms since last received response="
1181 << now - last_ping_response_received_
1182 << ", ms since last received data="
1183 << now - last_data_received_
1184 << ", rtt=" << rtt
1185 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001186 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001187
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001188 // Check the writable state. (The order of these checks is important.)
1189 //
1190 // Before becoming unwritable, we allow for a fixed number of pings to fail
1191 // (i.e., receive no response). We also have to give the response time to
1192 // get back, so we include a conservative estimate of this.
1193 //
1194 // Before timing out writability, we give a fixed amount of time. This is to
1195 // allow for changes in network conditions.
1196
1197 if ((write_state_ == STATE_WRITABLE) &&
1198 TooManyFailures(pings_since_last_response_,
1199 CONNECTION_WRITE_CONNECT_FAILURES,
1200 rtt,
1201 now) &&
1202 TooLongWithoutResponse(pings_since_last_response_,
1203 CONNECTION_WRITE_CONNECT_TIMEOUT,
1204 now)) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001205 uint32_t max_pings = CONNECTION_WRITE_CONNECT_FAILURES;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001206 LOG_J(LS_INFO, this) << "Unwritable after " << max_pings
1207 << " ping failures and "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001208 << now - pings_since_last_response_[0].sent_time
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001209 << " ms without a response,"
1210 << " ms since last received ping="
1211 << now - last_ping_received_
1212 << " ms since last received data="
1213 << now - last_data_received_
1214 << " rtt=" << rtt;
1215 set_write_state(STATE_WRITE_UNRELIABLE);
1216 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001217 if ((write_state_ == STATE_WRITE_UNRELIABLE ||
1218 write_state_ == STATE_WRITE_INIT) &&
1219 TooLongWithoutResponse(pings_since_last_response_,
1220 CONNECTION_WRITE_TIMEOUT,
1221 now)) {
1222 LOG_J(LS_INFO, this) << "Timed out after "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001223 << now - pings_since_last_response_[0].sent_time
1224 << " ms without a response"
1225 << ", rtt=" << rtt;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001226 set_write_state(STATE_WRITE_TIMEOUT);
1227 }
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001228
honghaiz9ad0db52016-07-14 19:30:28 -07001229 // Update the receiving state.
1230 UpdateReceiving(now);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001231 if (dead(now)) {
1232 Destroy();
1233 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001234}
1235
honghaiz34b11eb2016-03-16 08:55:44 -07001236void Connection::Ping(int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001237 last_ping_sent_ = now;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001238 ConnectionRequest *req = new ConnectionRequest(this);
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001239 pings_since_last_response_.push_back(SentPing(req->id(), now, nomination_));
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001240 LOG_J(LS_VERBOSE, this) << "Sending STUN ping "
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001241 << ", id=" << rtc::hex_encode(req->id())
1242 << ", nomination=" << nomination_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001243 requests_.Send(req);
hbos06495bc2017-01-02 08:08:18 -08001244 state_ = IceCandidatePairState::IN_PROGRESS;
honghaiz524ecc22016-05-25 12:48:31 -07001245 num_pings_sent_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001246}
1247
1248void Connection::ReceivedPing() {
nisse1bffc1d2016-05-02 08:18:55 -07001249 last_ping_received_ = rtc::TimeMillis();
honghaiz9ad0db52016-07-14 19:30:28 -07001250 UpdateReceiving(last_ping_received_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001251}
1252
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001253void Connection::ReceivedPingResponse(int rtt, const std::string& request_id) {
hbosbf8d3e52017-02-28 06:34:47 -08001254 RTC_DCHECK_GE(rtt, 0);
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001255 // We've already validated that this is a STUN binding response with
1256 // the correct local and remote username for this connection.
1257 // So if we're not already, become writable. We may be bringing a pruned
1258 // connection back to life, but if we don't really want it, we can always
1259 // prune it again.
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001260 auto iter = std::find_if(
1261 pings_since_last_response_.begin(), pings_since_last_response_.end(),
1262 [request_id](const SentPing& ping) { return ping.id == request_id; });
1263 if (iter != pings_since_last_response_.end() &&
1264 iter->nomination > acked_nomination_) {
1265 acked_nomination_ = iter->nomination;
1266 }
1267
hbosbf8d3e52017-02-28 06:34:47 -08001268 total_round_trip_time_ms_ += rtt;
1269 current_round_trip_time_ms_ = rtc::Optional<uint32_t>(
1270 static_cast<uint32_t>(rtt));
1271
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001272 pings_since_last_response_.clear();
honghaiz9ad0db52016-07-14 19:30:28 -07001273 last_ping_response_received_ = rtc::TimeMillis();
1274 UpdateReceiving(last_ping_response_received_);
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001275 set_write_state(STATE_WRITABLE);
hbos06495bc2017-01-02 08:08:18 -08001276 set_state(IceCandidatePairState::SUCCEEDED);
skvladd0309122017-02-02 17:18:37 -08001277 if (rtt_samples_ > 0) {
1278 rtt_ = (RTT_RATIO * rtt_ + rtt) / (RTT_RATIO + 1);
1279 } else {
1280 rtt_ = rtt;
1281 }
zhihuang435264a2016-06-21 11:28:38 -07001282 rtt_samples_++;
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001283}
1284
honghaiz34b11eb2016-03-16 08:55:44 -07001285bool Connection::dead(int64_t now) const {
honghaiz37389b42016-01-04 21:57:33 -08001286 if (last_received() > 0) {
1287 // If it has ever received anything, we keep it alive until it hasn't
1288 // received anything for DEAD_CONNECTION_RECEIVE_TIMEOUT. This covers the
1289 // normal case of a successfully used connection that stops working. This
1290 // also allows a remote peer to continue pinging over a locally inactive
1291 // (pruned) connection.
1292 return (now > (last_received() + DEAD_CONNECTION_RECEIVE_TIMEOUT));
1293 }
1294
1295 if (active()) {
1296 // If it has never received anything, keep it alive as long as it is
1297 // actively pinging and not pruned. Otherwise, the connection might be
1298 // deleted before it has a chance to ping. This is the normal case for a
1299 // new connection that is pinging but hasn't received anything yet.
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001300 return false;
1301 }
1302
honghaiz37389b42016-01-04 21:57:33 -08001303 // If it has never received anything and is not actively pinging (pruned), we
1304 // keep it around for at least MIN_CONNECTION_LIFETIME to prevent connections
1305 // from being pruned too quickly during a network change event when two
1306 // networks would be up simultaneously but only for a brief period.
1307 return now > (time_created_ms_ + MIN_CONNECTION_LIFETIME);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001308}
1309
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001310bool Connection::stable(int64_t now) const {
zhihuang435264a2016-06-21 11:28:38 -07001311 // A connection is stable if it's RTT has converged and it isn't missing any
1312 // responses. We should send pings at a higher rate until the RTT converges
1313 // and whenever a ping response is missing (so that we can detect
1314 // unwritability faster)
1315 return rtt_converged() && !missing_responses(now);
1316}
1317
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +00001318std::string Connection::ToDebugId() const {
1319 std::stringstream ss;
1320 ss << std::hex << this;
1321 return ss.str();
1322}
1323
honghaize1a0c942016-02-16 14:54:56 -08001324uint32_t Connection::ComputeNetworkCost() const {
1325 // TODO(honghaiz): Will add rtt as part of the network cost.
Honghai Zhang351d77b2016-05-20 15:08:29 -07001326 return port()->network_cost() + remote_candidate_.network_cost();
honghaize1a0c942016-02-16 14:54:56 -08001327}
1328
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001329std::string Connection::ToString() const {
1330 const char CONNECT_STATE_ABBREV[2] = {
1331 '-', // not connected (false)
1332 'C', // connected (true)
1333 };
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001334 const char RECEIVE_STATE_ABBREV[2] = {
1335 '-', // not receiving (false)
1336 'R', // receiving (true)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001337 };
1338 const char WRITE_STATE_ABBREV[4] = {
1339 'W', // STATE_WRITABLE
1340 'w', // STATE_WRITE_UNRELIABLE
1341 '-', // STATE_WRITE_INIT
1342 'x', // STATE_WRITE_TIMEOUT
1343 };
1344 const std::string ICESTATE[4] = {
1345 "W", // STATE_WAITING
1346 "I", // STATE_INPROGRESS
1347 "S", // STATE_SUCCEEDED
1348 "F" // STATE_FAILED
1349 };
1350 const Candidate& local = local_candidate();
1351 const Candidate& remote = remote_candidate();
1352 std::stringstream ss;
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001353 ss << "Conn[" << ToDebugId() << ":" << port_->content_name() << ":"
1354 << local.id() << ":" << local.component() << ":" << local.generation()
1355 << ":" << local.type() << ":" << local.protocol() << ":"
1356 << local.address().ToSensitiveString() << "->" << remote.id() << ":"
1357 << remote.component() << ":" << remote.priority() << ":" << remote.type()
1358 << ":" << remote.protocol() << ":" << remote.address().ToSensitiveString()
1359 << "|" << CONNECT_STATE_ABBREV[connected()]
1360 << RECEIVE_STATE_ABBREV[receiving()] << WRITE_STATE_ABBREV[write_state()]
hbos06495bc2017-01-02 08:08:18 -08001361 << ICESTATE[static_cast<int>(state())] << "|" << remote_nomination() << "|"
1362 << nomination() << "|" << priority() << "|";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001363 if (rtt_ < DEFAULT_RTT) {
1364 ss << rtt_ << "]";
1365 } else {
1366 ss << "-]";
1367 }
1368 return ss.str();
1369}
1370
1371std::string Connection::ToSensitiveString() const {
1372 return ToString();
1373}
1374
1375void Connection::OnConnectionRequestResponse(ConnectionRequest* request,
1376 StunMessage* response) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001377 // Log at LS_INFO if we receive a ping response on an unwritable
1378 // connection.
1379 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1380
honghaiz34b11eb2016-03-16 08:55:44 -07001381 int rtt = request->Elapsed();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001382
Peter Thatcherb2d26232015-05-15 11:25:14 -07001383 if (LOG_CHECK_LEVEL_V(sev)) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001384 std::string pings;
1385 PrintPingsSinceLastResponse(&pings, 5);
1386 LOG_JV(sev, this) << "Received STUN ping response"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001387 << ", id=" << rtc::hex_encode(request->id())
1388 << ", code=0" // Makes logging easier to parse.
1389 << ", rtt=" << rtt
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001390 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001391 }
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001392 ReceivedPingResponse(rtt, request->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001393
zhihuang5ecf16c2016-06-01 17:09:15 -07001394 stats_.recv_ping_responses++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001395
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001396 MaybeUpdateLocalCandidate(request, response);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001397}
1398
1399void Connection::OnConnectionRequestErrorResponse(ConnectionRequest* request,
1400 StunMessage* response) {
1401 const StunErrorCodeAttribute* error_attr = response->GetErrorCode();
1402 int error_code = STUN_ERROR_GLOBAL_FAILURE;
1403 if (error_attr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001404 error_code = error_attr->code();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001405 }
1406
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001407 LOG_J(LS_INFO, this) << "Received STUN error response"
1408 << " id=" << rtc::hex_encode(request->id())
1409 << " code=" << error_code
1410 << " rtt=" << request->Elapsed();
1411
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001412 if (error_code == STUN_ERROR_UNKNOWN_ATTRIBUTE ||
1413 error_code == STUN_ERROR_SERVER_ERROR ||
1414 error_code == STUN_ERROR_UNAUTHORIZED) {
1415 // Recoverable error, retry
1416 } else if (error_code == STUN_ERROR_STALE_CREDENTIALS) {
1417 // Race failure, retry
1418 } else if (error_code == STUN_ERROR_ROLE_CONFLICT) {
1419 HandleRoleConflictFromPeer();
1420 } else {
1421 // This is not a valid connection.
1422 LOG_J(LS_ERROR, this) << "Received STUN error response, code="
1423 << error_code << "; killing connection";
deadbeef376e1232015-11-25 09:00:08 -08001424 FailAndDestroy();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001425 }
1426}
1427
1428void Connection::OnConnectionRequestTimeout(ConnectionRequest* request) {
1429 // Log at LS_INFO if we miss a ping on a writable connection.
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001430 rtc::LoggingSeverity sev = writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1431 LOG_JV(sev, this) << "Timing-out STUN ping "
1432 << rtc::hex_encode(request->id())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001433 << " after " << request->Elapsed() << " ms";
1434}
1435
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001436void Connection::OnConnectionRequestSent(ConnectionRequest* request) {
1437 // Log at LS_INFO if we send a ping on an unwritable connection.
1438 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1439 LOG_JV(sev, this) << "Sent STUN ping"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001440 << ", id=" << rtc::hex_encode(request->id())
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001441 << ", use_candidate=" << use_candidate_attr()
1442 << ", nomination=" << nomination();
zhihuang5ecf16c2016-06-01 17:09:15 -07001443 stats_.sent_ping_requests_total++;
1444 if (stats_.recv_ping_responses == 0) {
1445 stats_.sent_ping_requests_before_first_response++;
1446 }
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001447}
1448
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001449void Connection::HandleRoleConflictFromPeer() {
1450 port_->SignalRoleConflict(port_);
1451}
1452
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001453void Connection::MaybeSetRemoteIceParametersAndGeneration(
1454 const IceParameters& ice_params,
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001455 int generation) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001456 if (remote_candidate_.username() == ice_params.ufrag &&
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001457 remote_candidate_.password().empty()) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001458 remote_candidate_.set_password(ice_params.pwd);
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001459 }
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001460 // TODO(deadbeef): A value of '0' for the generation is used for both
1461 // generation 0 and "generation unknown". It should be changed to an
1462 // rtc::Optional to fix this.
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001463 if (remote_candidate_.username() == ice_params.ufrag &&
1464 remote_candidate_.password() == ice_params.pwd &&
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001465 remote_candidate_.generation() == 0) {
1466 remote_candidate_.set_generation(generation);
1467 }
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001468}
1469
1470void Connection::MaybeUpdatePeerReflexiveCandidate(
1471 const Candidate& new_candidate) {
1472 if (remote_candidate_.type() == PRFLX_PORT_TYPE &&
1473 new_candidate.type() != PRFLX_PORT_TYPE &&
1474 remote_candidate_.protocol() == new_candidate.protocol() &&
1475 remote_candidate_.address() == new_candidate.address() &&
1476 remote_candidate_.username() == new_candidate.username() &&
1477 remote_candidate_.password() == new_candidate.password() &&
1478 remote_candidate_.generation() == new_candidate.generation()) {
1479 remote_candidate_ = new_candidate;
1480 }
1481}
1482
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001483void Connection::OnMessage(rtc::Message *pmsg) {
nisseede5da42017-01-12 05:15:36 -08001484 RTC_DCHECK(pmsg->message_id == MSG_DELETE);
honghaiz18f9da02016-06-01 23:53:01 -07001485 LOG(LS_INFO) << "Connection deleted with number of pings sent: "
1486 << num_pings_sent_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001487 SignalDestroyed(this);
1488 delete this;
1489}
1490
honghaiz34b11eb2016-03-16 08:55:44 -07001491int64_t Connection::last_received() const {
Peter Thatcher54360512015-07-08 11:08:35 -07001492 return std::max(last_data_received_,
1493 std::max(last_ping_received_, last_ping_response_received_));
1494}
1495
zhihuang5ecf16c2016-06-01 17:09:15 -07001496ConnectionInfo Connection::stats() {
1497 stats_.recv_bytes_second = round(recv_rate_tracker_.ComputeRate());
1498 stats_.recv_total_bytes = recv_rate_tracker_.TotalSampleCount();
1499 stats_.sent_bytes_second = round(send_rate_tracker_.ComputeRate());
1500 stats_.sent_total_bytes = send_rate_tracker_.TotalSampleCount();
hbos06495bc2017-01-02 08:08:18 -08001501 stats_.receiving = receiving_;
1502 stats_.writable = write_state_ == STATE_WRITABLE;
1503 stats_.timeout = write_state_ == STATE_WRITE_TIMEOUT;
1504 stats_.new_connection = !reported_;
1505 stats_.rtt = rtt_;
1506 stats_.local_candidate = local_candidate();
1507 stats_.remote_candidate = remote_candidate();
1508 stats_.key = this;
1509 stats_.state = state_;
1510 stats_.priority = priority();
hbos92eaec62017-02-27 01:38:08 -08001511 stats_.nominated = nominated();
hbosbf8d3e52017-02-28 06:34:47 -08001512 stats_.total_round_trip_time_ms = total_round_trip_time_ms_;
1513 stats_.current_round_trip_time_ms = current_round_trip_time_ms_;
zhihuang5ecf16c2016-06-01 17:09:15 -07001514 return stats_;
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001515}
1516
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001517void Connection::MaybeUpdateLocalCandidate(ConnectionRequest* request,
1518 StunMessage* response) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001519 // RFC 5245
1520 // The agent checks the mapped address from the STUN response. If the
1521 // transport address does not match any of the local candidates that the
1522 // agent knows about, the mapped address represents a new candidate -- a
1523 // peer reflexive candidate.
1524 const StunAddressAttribute* addr =
1525 response->GetAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
1526 if (!addr) {
1527 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1528 << "No MAPPED-ADDRESS or XOR-MAPPED-ADDRESS found in the "
1529 << "stun response message";
1530 return;
1531 }
1532
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001533 for (size_t i = 0; i < port_->Candidates().size(); ++i) {
1534 if (port_->Candidates()[i].address() == addr->GetAddress()) {
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001535 if (local_candidate_index_ != i) {
1536 LOG_J(LS_INFO, this) << "Updating local candidate type to srflx.";
1537 local_candidate_index_ = i;
1538 // SignalStateChange to force a re-sort in P2PTransportChannel as this
1539 // Connection's local candidate has changed.
1540 SignalStateChange(this);
1541 }
1542 return;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001543 }
1544 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001545
1546 // RFC 5245
1547 // Its priority is set equal to the value of the PRIORITY attribute
1548 // in the Binding request.
1549 const StunUInt32Attribute* priority_attr =
1550 request->msg()->GetUInt32(STUN_ATTR_PRIORITY);
1551 if (!priority_attr) {
1552 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1553 << "No STUN_ATTR_PRIORITY found in the "
1554 << "stun response message";
1555 return;
1556 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001557 const uint32_t priority = priority_attr->value();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001558 std::string id = rtc::CreateRandomString(8);
1559
1560 Candidate new_local_candidate;
1561 new_local_candidate.set_id(id);
1562 new_local_candidate.set_component(local_candidate().component());
1563 new_local_candidate.set_type(PRFLX_PORT_TYPE);
1564 new_local_candidate.set_protocol(local_candidate().protocol());
1565 new_local_candidate.set_address(addr->GetAddress());
1566 new_local_candidate.set_priority(priority);
1567 new_local_candidate.set_username(local_candidate().username());
1568 new_local_candidate.set_password(local_candidate().password());
1569 new_local_candidate.set_network_name(local_candidate().network_name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001570 new_local_candidate.set_network_type(local_candidate().network_type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001571 new_local_candidate.set_related_address(local_candidate().address());
Taylor Brandstetterf7c15a92016-06-22 13:13:55 -07001572 new_local_candidate.set_generation(local_candidate().generation());
Honghai Zhang80f1db92016-01-27 11:54:45 -08001573 new_local_candidate.set_foundation(ComputeFoundation(
1574 PRFLX_PORT_TYPE, local_candidate().protocol(),
1575 local_candidate().relay_protocol(), local_candidate().address()));
honghaiza0c44ea2016-03-23 16:07:48 -07001576 new_local_candidate.set_network_id(local_candidate().network_id());
1577 new_local_candidate.set_network_cost(local_candidate().network_cost());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001578
1579 // Change the local candidate of this Connection to the new prflx candidate.
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001580 LOG_J(LS_INFO, this) << "Updating local candidate type to prflx.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001581 local_candidate_index_ = port_->AddPrflxCandidate(new_local_candidate);
1582
1583 // SignalStateChange to force a re-sort in P2PTransportChannel as this
1584 // Connection's local candidate has changed.
1585 SignalStateChange(this);
1586}
1587
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001588bool Connection::rtt_converged() const {
zhihuang435264a2016-06-21 11:28:38 -07001589 return rtt_samples_ > (RTT_RATIO + 1);
1590}
1591
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001592bool Connection::missing_responses(int64_t now) const {
zhihuang435264a2016-06-21 11:28:38 -07001593 if (pings_since_last_response_.empty()) {
1594 return false;
1595 }
1596
1597 int64_t waiting = now - pings_since_last_response_[0].sent_time;
1598 return waiting > 2 * rtt();
1599}
1600
deadbeef376e1232015-11-25 09:00:08 -08001601ProxyConnection::ProxyConnection(Port* port,
1602 size_t index,
1603 const Candidate& remote_candidate)
1604 : Connection(port, index, remote_candidate) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001605
1606int ProxyConnection::Send(const void* data, size_t size,
1607 const rtc::PacketOptions& options) {
zhihuang5ecf16c2016-06-01 17:09:15 -07001608 stats_.sent_total_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001609 int sent = port_->SendTo(data, size, remote_candidate_.address(),
1610 options, true);
1611 if (sent <= 0) {
nisseede5da42017-01-12 05:15:36 -08001612 RTC_DCHECK(sent < 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001613 error_ = port_->GetError();
zhihuang5ecf16c2016-06-01 17:09:15 -07001614 stats_.sent_discarded_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001615 } else {
Tim Psiaki63046262015-09-14 10:38:08 -07001616 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001617 }
1618 return sent;
1619}
1620
1621} // namespace cricket