blob: b9ead32b543525ae571e46b72d1ab392c2d5afda [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"
19#include "webrtc/base/crc32.h"
20#include "webrtc/base/helpers.h"
21#include "webrtc/base/logging.h"
22#include "webrtc/base/messagedigest.h"
honghaize3c6c822016-02-17 13:00:28 -080023#include "webrtc/base/network.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000024#include "webrtc/base/stringencode.h"
25#include "webrtc/base/stringutils.h"
26
27namespace {
28
29// Determines whether we have seen at least the given maximum number of
30// pings fail to have a response.
31inline bool TooManyFailures(
Peter Thatcher1cf6f812015-05-15 10:40:45 -070032 const std::vector<cricket::Connection::SentPing>& pings_since_last_response,
Peter Boström0c4e06b2015-10-07 12:23:21 +020033 uint32_t maximum_failures,
honghaiz34b11eb2016-03-16 08:55:44 -070034 int rtt_estimate,
35 int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000036 // If we haven't sent that many pings, then we can't have failed that many.
37 if (pings_since_last_response.size() < maximum_failures)
38 return false;
39
40 // Check if the window in which we would expect a response to the ping has
41 // already elapsed.
honghaiz34b11eb2016-03-16 08:55:44 -070042 int64_t expected_response_time =
Peter Thatcher1cf6f812015-05-15 10:40:45 -070043 pings_since_last_response[maximum_failures - 1].sent_time + rtt_estimate;
44 return now > expected_response_time;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000045}
46
47// Determines whether we have gone too long without seeing any response.
48inline bool TooLongWithoutResponse(
Peter Thatcher1cf6f812015-05-15 10:40:45 -070049 const std::vector<cricket::Connection::SentPing>& pings_since_last_response,
honghaiz34b11eb2016-03-16 08:55:44 -070050 int64_t maximum_time,
51 int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000052 if (pings_since_last_response.size() == 0)
53 return false;
54
Peter Thatcher1cf6f812015-05-15 10:40:45 -070055 auto first = pings_since_last_response[0];
56 return now > (first.sent_time + maximum_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000057}
58
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000059// We will restrict RTT estimates (when used for determining state) to be
60// within a reasonable range.
honghaiz34b11eb2016-03-16 08:55:44 -070061const int MINIMUM_RTT = 100; // 0.1 seconds
62const int MAXIMUM_RTT = 3000; // 3 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000063
64// When we don't have any RTT data, we have to pick something reasonable. We
65// use a large value just in case the connection is really slow.
honghaiz34b11eb2016-03-16 08:55:44 -070066const int DEFAULT_RTT = MAXIMUM_RTT;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000067
68// Computes our estimate of the RTT given the current estimate.
honghaiz34b11eb2016-03-16 08:55:44 -070069inline int ConservativeRTTEstimate(int rtt) {
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000070 return std::max(MINIMUM_RTT, std::min(MAXIMUM_RTT, 2 * rtt));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000071}
72
73// Weighting of the old rtt value to new data.
74const int RTT_RATIO = 3; // 3 : 1
75
76// The delay before we begin checking if this port is useless.
77const int kPortTimeoutDelay = 30 * 1000; // 30 seconds
Honghai Zhang351d77b2016-05-20 15:08:29 -070078} // namespace
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000079
80namespace cricket {
81
82// TODO(ronghuawu): Use "host", "srflx", "prflx" and "relay". But this requires
83// the signaling part be updated correspondingly as well.
84const char LOCAL_PORT_TYPE[] = "local";
85const char STUN_PORT_TYPE[] = "stun";
86const char PRFLX_PORT_TYPE[] = "prflx";
87const char RELAY_PORT_TYPE[] = "relay";
88
89const char UDP_PROTOCOL_NAME[] = "udp";
90const char TCP_PROTOCOL_NAME[] = "tcp";
91const char SSLTCP_PROTOCOL_NAME[] = "ssltcp";
92
93static const char* const PROTO_NAMES[] = { UDP_PROTOCOL_NAME,
94 TCP_PROTOCOL_NAME,
95 SSLTCP_PROTOCOL_NAME };
96
97const char* ProtoToString(ProtocolType proto) {
98 return PROTO_NAMES[proto];
99}
100
101bool StringToProto(const char* value, ProtocolType* proto) {
102 for (size_t i = 0; i <= PROTO_LAST; ++i) {
103 if (_stricmp(PROTO_NAMES[i], value) == 0) {
104 *proto = static_cast<ProtocolType>(i);
105 return true;
106 }
107 }
108 return false;
109}
110
111// RFC 6544, TCP candidate encoding rules.
112const int DISCARD_PORT = 9;
113const char TCPTYPE_ACTIVE_STR[] = "active";
114const char TCPTYPE_PASSIVE_STR[] = "passive";
115const char TCPTYPE_SIMOPEN_STR[] = "so";
116
117// Foundation: An arbitrary string that is the same for two candidates
118// that have the same type, base IP address, protocol (UDP, TCP,
119// etc.), and STUN or TURN server. If any of these are different,
120// then the foundation will be different. Two candidate pairs with
121// the same foundation pairs are likely to have similar network
122// characteristics. Foundations are used in the frozen algorithm.
Honghai Zhang80f1db92016-01-27 11:54:45 -0800123static std::string ComputeFoundation(const std::string& type,
124 const std::string& protocol,
125 const std::string& relay_protocol,
126 const rtc::SocketAddress& base_address) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000127 std::ostringstream ost;
Honghai Zhang80f1db92016-01-27 11:54:45 -0800128 ost << type << base_address.ipaddr().ToString() << protocol << relay_protocol;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200129 return rtc::ToString<uint32_t>(rtc::ComputeCrc32(ost.str()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000130}
131
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000132Port::Port(rtc::Thread* thread,
Honghai Zhangd00c0572016-06-28 09:44:47 -0700133 const std::string& type,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000134 rtc::PacketSocketFactory* factory,
135 rtc::Network* network,
136 const rtc::IPAddress& ip,
137 const std::string& username_fragment,
138 const std::string& password)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000139 : thread_(thread),
140 factory_(factory),
Honghai Zhangd00c0572016-06-28 09:44:47 -0700141 type_(type),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000142 send_retransmit_count_attribute_(false),
143 network_(network),
144 ip_(ip),
145 min_port_(0),
146 max_port_(0),
147 component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
148 generation_(0),
149 ice_username_fragment_(username_fragment),
150 password_(password),
151 timeout_delay_(kPortTimeoutDelay),
152 enable_port_packets_(false),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000153 ice_role_(ICEROLE_UNKNOWN),
154 tiebreaker_(0),
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700155 shared_socket_(true) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000156 Construct();
157}
158
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000159Port::Port(rtc::Thread* thread,
160 const std::string& type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000161 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000162 rtc::Network* network,
163 const rtc::IPAddress& ip,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200164 uint16_t min_port,
165 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000166 const std::string& username_fragment,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000167 const std::string& password)
168 : thread_(thread),
169 factory_(factory),
170 type_(type),
171 send_retransmit_count_attribute_(false),
172 network_(network),
173 ip_(ip),
174 min_port_(min_port),
175 max_port_(max_port),
176 component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
177 generation_(0),
178 ice_username_fragment_(username_fragment),
179 password_(password),
180 timeout_delay_(kPortTimeoutDelay),
181 enable_port_packets_(false),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000182 ice_role_(ICEROLE_UNKNOWN),
183 tiebreaker_(0),
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700184 shared_socket_(false) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000185 ASSERT(factory_ != NULL);
186 Construct();
187}
188
189void Port::Construct() {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700190 // TODO(pthatcher): Remove this old behavior once we're sure no one
191 // relies on it. If the username_fragment and password are empty,
192 // we should just create one.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000193 if (ice_username_fragment_.empty()) {
194 ASSERT(password_.empty());
195 ice_username_fragment_ = rtc::CreateRandomString(ICE_UFRAG_LENGTH);
196 password_ = rtc::CreateRandomString(ICE_PWD_LENGTH);
197 }
Honghai Zhang351d77b2016-05-20 15:08:29 -0700198 network_->SignalTypeChanged.connect(this, &Port::OnNetworkTypeChanged);
199 network_cost_ = network_->GetCost();
honghaize1a0c942016-02-16 14:54:56 -0800200
Honghai Zhanga74363c2016-07-28 18:06:15 -0700201 thread_->PostDelayed(RTC_FROM_HERE, timeout_delay_, this,
202 MSG_DESTROY_IF_DEAD);
Honghai Zhang351d77b2016-05-20 15:08:29 -0700203 LOG_J(LS_INFO, this) << "Port created with network cost " << network_cost_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000204}
205
206Port::~Port() {
207 // Delete all of the remaining connections. We copy the list up front
208 // because each deletion will cause it to be modified.
209
210 std::vector<Connection*> list;
211
212 AddressMap::iterator iter = connections_.begin();
213 while (iter != connections_.end()) {
214 list.push_back(iter->second);
215 ++iter;
216 }
217
Peter Boström0c4e06b2015-10-07 12:23:21 +0200218 for (uint32_t i = 0; i < list.size(); i++)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000219 delete list[i];
220}
221
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700222void Port::SetIceParameters(int component,
223 const std::string& username_fragment,
224 const std::string& password) {
225 component_ = component;
226 ice_username_fragment_ = username_fragment;
227 password_ = password;
228 for (Candidate& c : candidates_) {
229 c.set_component(component);
230 c.set_username(username_fragment);
231 c.set_password(password);
232 }
233}
234
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000235Connection* Port::GetConnection(const rtc::SocketAddress& remote_addr) {
236 AddressMap::const_iterator iter = connections_.find(remote_addr);
237 if (iter != connections_.end())
238 return iter->second;
239 else
240 return NULL;
241}
242
243void Port::AddAddress(const rtc::SocketAddress& address,
244 const rtc::SocketAddress& base_address,
245 const rtc::SocketAddress& related_address,
246 const std::string& protocol,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700247 const std::string& relay_protocol,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000248 const std::string& tcptype,
249 const std::string& type,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200250 uint32_t type_preference,
251 uint32_t relay_preference,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000252 bool final) {
253 if (protocol == TCP_PROTOCOL_NAME && type == LOCAL_PORT_TYPE) {
254 ASSERT(!tcptype.empty());
255 }
256
honghaiza0c44ea2016-03-23 16:07:48 -0700257 std::string foundation =
258 ComputeFoundation(type, protocol, relay_protocol, base_address);
259 Candidate c(component_, protocol, address, 0U, username_fragment(), password_,
260 type, generation_, foundation, network_->id(), network_cost_);
261 c.set_priority(
262 c.GetPriority(type_preference, network_->preference(), relay_preference));
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700263 c.set_relay_protocol(relay_protocol);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000264 c.set_tcptype(tcptype);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000265 c.set_network_name(network_->name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +0000266 c.set_network_type(network_->type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000267 c.set_related_address(related_address);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000268 candidates_.push_back(c);
269 SignalCandidateReady(this, c);
270
271 if (final) {
272 SignalPortComplete(this);
273 }
274}
275
honghaiz36f50e82016-06-01 15:57:03 -0700276void Port::AddOrReplaceConnection(Connection* conn) {
277 auto ret = connections_.insert(
278 std::make_pair(conn->remote_candidate().address(), conn));
279 // If there is a different connection on the same remote address, replace
280 // it with the new one and destroy the old one.
281 if (ret.second == false && ret.first->second != conn) {
282 LOG_J(LS_WARNING, this)
283 << "A new connection was created on an existing remote address. "
284 << "New remote candidate: " << conn->remote_candidate().ToString();
285 ret.first->second->SignalDestroyed.disconnect(this);
286 ret.first->second->Destroy();
287 ret.first->second = conn;
288 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000289 conn->SignalDestroyed.connect(this, &Port::OnConnectionDestroyed);
290 SignalConnectionCreated(this, conn);
291}
292
293void Port::OnReadPacket(
294 const char* data, size_t size, const rtc::SocketAddress& addr,
295 ProtocolType proto) {
296 // If the user has enabled port packets, just hand this over.
297 if (enable_port_packets_) {
298 SignalReadPacket(this, data, size, addr);
299 return;
300 }
301
302 // If this is an authenticated STUN request, then signal unknown address and
303 // send back a proper binding response.
kwiberg3ec46792016-04-27 07:22:53 -0700304 std::unique_ptr<IceMessage> msg;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000305 std::string remote_username;
kwiberg6baec032016-03-15 11:09:39 -0700306 if (!GetStunMessage(data, size, addr, &msg, &remote_username)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000307 LOG_J(LS_ERROR, this) << "Received non-STUN packet from unknown address ("
308 << addr.ToSensitiveString() << ")";
309 } else if (!msg) {
310 // STUN message handled already
311 } else if (msg->type() == STUN_BINDING_REQUEST) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700312 LOG(LS_INFO) << "Received STUN ping "
313 << " id=" << rtc::hex_encode(msg->transaction_id())
314 << " from unknown address " << addr.ToSensitiveString();
315
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000316 // Check for role conflicts.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700317 if (!MaybeIceRoleConflict(addr, msg.get(), remote_username)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000318 LOG(LS_INFO) << "Received conflicting role from the peer.";
319 return;
320 }
321
322 SignalUnknownAddress(this, addr, proto, msg.get(), remote_username, false);
323 } else {
324 // NOTE(tschmelcher): STUN_BINDING_RESPONSE is benign. It occurs if we
325 // pruned a connection for this port while it had STUN requests in flight,
326 // because we then get back responses for them, which this code correctly
327 // does not handle.
328 if (msg->type() != STUN_BINDING_RESPONSE) {
329 LOG_J(LS_ERROR, this) << "Received unexpected STUN message type ("
330 << msg->type() << ") from unknown address ("
331 << addr.ToSensitiveString() << ")";
332 }
333 }
334}
335
336void Port::OnReadyToSend() {
337 AddressMap::iterator iter = connections_.begin();
338 for (; iter != connections_.end(); ++iter) {
339 iter->second->OnReadyToSend();
340 }
341}
342
343size_t Port::AddPrflxCandidate(const Candidate& local) {
344 candidates_.push_back(local);
345 return (candidates_.size() - 1);
346}
347
kwiberg6baec032016-03-15 11:09:39 -0700348bool Port::GetStunMessage(const char* data,
349 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000350 const rtc::SocketAddress& addr,
kwiberg3ec46792016-04-27 07:22:53 -0700351 std::unique_ptr<IceMessage>* out_msg,
kwiberg6baec032016-03-15 11:09:39 -0700352 std::string* out_username) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000353 // NOTE: This could clearly be optimized to avoid allocating any memory.
354 // However, at the data rates we'll be looking at on the client side,
355 // this probably isn't worth worrying about.
356 ASSERT(out_msg != NULL);
357 ASSERT(out_username != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000358 out_username->clear();
359
360 // Don't bother parsing the packet if we can tell it's not STUN.
361 // In ICE mode, all STUN packets will have a valid fingerprint.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700362 if (!StunMessage::ValidateFingerprint(data, size)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000363 return false;
364 }
365
366 // Parse the request message. If the packet is not a complete and correct
367 // STUN message, then ignore it.
kwiberg3ec46792016-04-27 07:22:53 -0700368 std::unique_ptr<IceMessage> stun_msg(new IceMessage());
jbauchf1f87202016-03-30 06:43:37 -0700369 rtc::ByteBufferReader buf(data, size);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000370 if (!stun_msg->Read(&buf) || (buf.Length() > 0)) {
371 return false;
372 }
373
374 if (stun_msg->type() == STUN_BINDING_REQUEST) {
375 // Check for the presence of USERNAME and MESSAGE-INTEGRITY (if ICE) first.
376 // If not present, fail with a 400 Bad Request.
377 if (!stun_msg->GetByteString(STUN_ATTR_USERNAME) ||
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700378 !stun_msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000379 LOG_J(LS_ERROR, this) << "Received STUN request without username/M-I "
380 << "from " << addr.ToSensitiveString();
381 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_BAD_REQUEST,
382 STUN_ERROR_REASON_BAD_REQUEST);
383 return true;
384 }
385
386 // If the username is bad or unknown, fail with a 401 Unauthorized.
387 std::string local_ufrag;
388 std::string remote_ufrag;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700389 if (!ParseStunUsername(stun_msg.get(), &local_ufrag, &remote_ufrag) ||
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000390 local_ufrag != username_fragment()) {
391 LOG_J(LS_ERROR, this) << "Received STUN request with bad local username "
392 << local_ufrag << " from "
393 << addr.ToSensitiveString();
394 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
395 STUN_ERROR_REASON_UNAUTHORIZED);
396 return true;
397 }
398
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000399 // If ICE, and the MESSAGE-INTEGRITY is bad, fail with a 401 Unauthorized
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700400 if (!stun_msg->ValidateMessageIntegrity(data, size, password_)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000401 LOG_J(LS_ERROR, this) << "Received STUN request with bad M-I "
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +0000402 << "from " << addr.ToSensitiveString()
403 << ", password_=" << password_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000404 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
405 STUN_ERROR_REASON_UNAUTHORIZED);
406 return true;
407 }
408 out_username->assign(remote_ufrag);
409 } else if ((stun_msg->type() == STUN_BINDING_RESPONSE) ||
410 (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE)) {
411 if (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE) {
412 if (const StunErrorCodeAttribute* error_code = stun_msg->GetErrorCode()) {
413 LOG_J(LS_ERROR, this) << "Received STUN binding error:"
414 << " class=" << error_code->eclass()
415 << " number=" << error_code->number()
416 << " reason='" << error_code->reason() << "'"
417 << " from " << addr.ToSensitiveString();
418 // Return message to allow error-specific processing
419 } else {
420 LOG_J(LS_ERROR, this) << "Received STUN binding error without a error "
421 << "code from " << addr.ToSensitiveString();
422 return true;
423 }
424 }
425 // NOTE: Username should not be used in verifying response messages.
426 out_username->clear();
427 } else if (stun_msg->type() == STUN_BINDING_INDICATION) {
428 LOG_J(LS_VERBOSE, this) << "Received STUN binding indication:"
429 << " from " << addr.ToSensitiveString();
430 out_username->clear();
431 // No stun attributes will be verified, if it's stun indication message.
432 // Returning from end of the this method.
433 } else {
434 LOG_J(LS_ERROR, this) << "Received STUN packet with invalid type ("
435 << stun_msg->type() << ") from "
436 << addr.ToSensitiveString();
437 return true;
438 }
439
440 // Return the STUN message found.
kwiberg6baec032016-03-15 11:09:39 -0700441 *out_msg = std::move(stun_msg);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000442 return true;
443}
444
445bool Port::IsCompatibleAddress(const rtc::SocketAddress& addr) {
446 int family = ip().family();
447 // We use single-stack sockets, so families must match.
448 if (addr.family() != family) {
449 return false;
450 }
451 // Link-local IPv6 ports can only connect to other link-local IPv6 ports.
Peter Thatcherb8b01432015-07-07 16:45:53 -0700452 if (family == AF_INET6 &&
453 (IPIsLinkLocal(ip()) != IPIsLinkLocal(addr.ipaddr()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000454 return false;
455 }
456 return true;
457}
458
459bool Port::ParseStunUsername(const StunMessage* stun_msg,
460 std::string* local_ufrag,
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700461 std::string* remote_ufrag) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000462 // The packet must include a username that either begins or ends with our
463 // fragment. It should begin with our fragment if it is a request and it
464 // should end with our fragment if it is a response.
465 local_ufrag->clear();
466 remote_ufrag->clear();
467 const StunByteStringAttribute* username_attr =
468 stun_msg->GetByteString(STUN_ATTR_USERNAME);
469 if (username_attr == NULL)
470 return false;
471
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700472 // RFRAG:LFRAG
473 const std::string username = username_attr->GetString();
474 size_t colon_pos = username.find(":");
475 if (colon_pos == std::string::npos) {
476 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000477 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000478
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700479 *local_ufrag = username.substr(0, colon_pos);
480 *remote_ufrag = username.substr(colon_pos + 1, username.size());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000481 return true;
482}
483
484bool Port::MaybeIceRoleConflict(
485 const rtc::SocketAddress& addr, IceMessage* stun_msg,
486 const std::string& remote_ufrag) {
487 // Validate ICE_CONTROLLING or ICE_CONTROLLED attributes.
488 bool ret = true;
489 IceRole remote_ice_role = ICEROLE_UNKNOWN;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200490 uint64_t remote_tiebreaker = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000491 const StunUInt64Attribute* stun_attr =
492 stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
493 if (stun_attr) {
494 remote_ice_role = ICEROLE_CONTROLLING;
495 remote_tiebreaker = stun_attr->value();
496 }
497
498 // If |remote_ufrag| is same as port local username fragment and
499 // tie breaker value received in the ping message matches port
500 // tiebreaker value this must be a loopback call.
501 // We will treat this as valid scenario.
502 if (remote_ice_role == ICEROLE_CONTROLLING &&
503 username_fragment() == remote_ufrag &&
504 remote_tiebreaker == IceTiebreaker()) {
505 return true;
506 }
507
508 stun_attr = stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
509 if (stun_attr) {
510 remote_ice_role = ICEROLE_CONTROLLED;
511 remote_tiebreaker = stun_attr->value();
512 }
513
514 switch (ice_role_) {
515 case ICEROLE_CONTROLLING:
516 if (ICEROLE_CONTROLLING == remote_ice_role) {
517 if (remote_tiebreaker >= tiebreaker_) {
518 SignalRoleConflict(this);
519 } else {
520 // Send Role Conflict (487) error response.
521 SendBindingErrorResponse(stun_msg, addr,
522 STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
523 ret = false;
524 }
525 }
526 break;
527 case ICEROLE_CONTROLLED:
528 if (ICEROLE_CONTROLLED == remote_ice_role) {
529 if (remote_tiebreaker < tiebreaker_) {
530 SignalRoleConflict(this);
531 } else {
532 // Send Role Conflict (487) error response.
533 SendBindingErrorResponse(stun_msg, addr,
534 STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
535 ret = false;
536 }
537 }
538 break;
539 default:
540 ASSERT(false);
541 }
542 return ret;
543}
544
545void Port::CreateStunUsername(const std::string& remote_username,
546 std::string* stun_username_attr_str) const {
547 stun_username_attr_str->clear();
548 *stun_username_attr_str = remote_username;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700549 stun_username_attr_str->append(":");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000550 stun_username_attr_str->append(username_fragment());
551}
552
553void Port::SendBindingResponse(StunMessage* request,
554 const rtc::SocketAddress& addr) {
555 ASSERT(request->type() == STUN_BINDING_REQUEST);
556
557 // Retrieve the username from the request.
558 const StunByteStringAttribute* username_attr =
559 request->GetByteString(STUN_ATTR_USERNAME);
560 ASSERT(username_attr != NULL);
561 if (username_attr == NULL) {
562 // No valid username, skip the response.
563 return;
564 }
565
566 // Fill in the response message.
567 StunMessage response;
568 response.SetType(STUN_BINDING_RESPONSE);
569 response.SetTransactionID(request->transaction_id());
570 const StunUInt32Attribute* retransmit_attr =
571 request->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
572 if (retransmit_attr) {
573 // Inherit the incoming retransmit value in the response so the other side
574 // can see our view of lost pings.
575 response.AddAttribute(new StunUInt32Attribute(
576 STUN_ATTR_RETRANSMIT_COUNT, retransmit_attr->value()));
577
578 if (retransmit_attr->value() > CONNECTION_WRITE_CONNECT_FAILURES) {
579 LOG_J(LS_INFO, this)
580 << "Received a remote ping with high retransmit count: "
581 << retransmit_attr->value();
582 }
583 }
584
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700585 response.AddAttribute(
586 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, addr));
587 response.AddMessageIntegrity(password_);
588 response.AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000589
590 // Send the response message.
jbauchf1f87202016-03-30 06:43:37 -0700591 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000592 response.Write(&buf);
593 rtc::PacketOptions options(DefaultDscpValue());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700594 auto err = SendTo(buf.Data(), buf.Length(), addr, options, false);
595 if (err < 0) {
596 LOG_J(LS_ERROR, this)
597 << "Failed to send STUN ping response"
598 << ", to=" << addr.ToSensitiveString()
599 << ", err=" << err
600 << ", id=" << rtc::hex_encode(response.transaction_id());
601 } else {
602 // Log at LS_INFO if we send a stun ping response on an unwritable
603 // connection.
honghaiz9b5ee9c2015-11-11 13:19:17 -0800604 Connection* conn = GetConnection(addr);
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700605 rtc::LoggingSeverity sev = (conn && !conn->writable()) ?
606 rtc::LS_INFO : rtc::LS_VERBOSE;
607 LOG_JV(sev, this)
608 << "Sent STUN ping response"
609 << ", to=" << addr.ToSensitiveString()
610 << ", id=" << rtc::hex_encode(response.transaction_id());
zhihuang5ecf16c2016-06-01 17:09:15 -0700611
612 conn->stats_.sent_ping_responses++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000613 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000614}
615
616void Port::SendBindingErrorResponse(StunMessage* request,
617 const rtc::SocketAddress& addr,
618 int error_code, const std::string& reason) {
619 ASSERT(request->type() == STUN_BINDING_REQUEST);
620
621 // Fill in the response message.
622 StunMessage response;
623 response.SetType(STUN_BINDING_ERROR_RESPONSE);
624 response.SetTransactionID(request->transaction_id());
625
626 // When doing GICE, we need to write out the error code incorrectly to
627 // maintain backwards compatiblility.
628 StunErrorCodeAttribute* error_attr = StunAttribute::CreateErrorCode();
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700629 error_attr->SetCode(error_code);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000630 error_attr->SetReason(reason);
631 response.AddAttribute(error_attr);
632
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700633 // Per Section 10.1.2, certain error cases don't get a MESSAGE-INTEGRITY,
634 // because we don't have enough information to determine the shared secret.
635 if (error_code != STUN_ERROR_BAD_REQUEST &&
636 error_code != STUN_ERROR_UNAUTHORIZED)
637 response.AddMessageIntegrity(password_);
638 response.AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000639
640 // Send the response message.
jbauchf1f87202016-03-30 06:43:37 -0700641 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000642 response.Write(&buf);
643 rtc::PacketOptions options(DefaultDscpValue());
644 SendTo(buf.Data(), buf.Length(), addr, options, false);
645 LOG_J(LS_INFO, this) << "Sending STUN binding error: reason=" << reason
646 << " to " << addr.ToSensitiveString();
647}
648
Honghai Zhanga74363c2016-07-28 18:06:15 -0700649void Port::KeepAliveUntilPruned() {
650 // If it is pruned, we won't bring it up again.
651 if (state_ == State::INIT) {
652 state_ = State::KEEP_ALIVE_UNTIL_PRUNED;
653 }
654}
655
656void Port::Prune() {
657 state_ = State::PRUNED;
658 thread_->Post(RTC_FROM_HERE, this, MSG_DESTROY_IF_DEAD);
659}
660
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000661void Port::OnMessage(rtc::Message *pmsg) {
Honghai Zhanga74363c2016-07-28 18:06:15 -0700662 ASSERT(pmsg->message_id == MSG_DESTROY_IF_DEAD);
663 bool dead =
664 (state_ == State::INIT || state_ == State::PRUNED) &&
665 connections_.empty() &&
666 rtc::TimeMillis() - last_time_all_connections_removed_ >= timeout_delay_;
667 if (dead) {
honghaizd0b31432015-09-30 12:42:17 -0700668 Destroy();
669 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000670}
671
Honghai Zhang351d77b2016-05-20 15:08:29 -0700672void Port::OnNetworkTypeChanged(const rtc::Network* network) {
673 ASSERT(network == network_);
674
675 UpdateNetworkCost();
676}
677
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000678std::string Port::ToString() const {
679 std::stringstream ss;
honghaize3c6c822016-02-17 13:00:28 -0800680 ss << "Port[" << std::hex << this << std::dec << ":" << content_name_ << ":"
681 << component_ << ":" << generation_ << ":" << type_ << ":"
682 << network_->ToString() << "]";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000683 return ss.str();
684}
685
Honghai Zhang351d77b2016-05-20 15:08:29 -0700686// TODO(honghaiz): Make the network cost configurable from user setting.
687void Port::UpdateNetworkCost() {
688 uint16_t new_cost = network_->GetCost();
689 if (network_cost_ == new_cost) {
690 return;
691 }
692 LOG(LS_INFO) << "Network cost changed from " << network_cost_
693 << " to " << new_cost
694 << ". Number of candidates created: " << candidates_.size()
695 << ". Number of connections created: " << connections_.size();
696 network_cost_ = new_cost;
697 for (cricket::Candidate& candidate : candidates_) {
698 candidate.set_network_cost(network_cost_);
699 }
700 // Network cost change will affect the connection selection criteria.
701 // Signal the connection state change on each connection to force a
702 // re-sort in P2PTransportChannel.
703 for (auto kv : connections_) {
704 Connection* conn = kv.second;
705 conn->SignalStateChange(conn);
706 }
707}
708
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000709void Port::EnablePortPackets() {
710 enable_port_packets_ = true;
711}
712
713void Port::OnConnectionDestroyed(Connection* conn) {
714 AddressMap::iterator iter =
715 connections_.find(conn->remote_candidate().address());
716 ASSERT(iter != connections_.end());
717 connections_.erase(iter);
honghaiz36f50e82016-06-01 15:57:03 -0700718 HandleConnectionDestroyed(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000719
Honghai Zhanga74363c2016-07-28 18:06:15 -0700720 // Ports time out after all connections fail if it is not marked as
721 // "keep alive until pruned."
honghaizd0b31432015-09-30 12:42:17 -0700722 // Note: If a new connection is added after this message is posted, but it
723 // fails and is removed before kPortTimeoutDelay, then this message will
Honghai Zhangb5db1ec2016-07-28 13:23:05 -0700724 // not cause the Port to be destroyed.
Honghai Zhanga74363c2016-07-28 18:06:15 -0700725 if (connections_.empty()) {
Honghai Zhangb5db1ec2016-07-28 13:23:05 -0700726 last_time_all_connections_removed_ = rtc::TimeMillis();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700727 thread_->PostDelayed(RTC_FROM_HERE, timeout_delay_, this,
728 MSG_DESTROY_IF_DEAD);
honghaizd0b31432015-09-30 12:42:17 -0700729 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000730}
731
732void Port::Destroy() {
733 ASSERT(connections_.empty());
734 LOG_J(LS_INFO, this) << "Port deleted";
735 SignalDestroyed(this);
736 delete this;
737}
738
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000739const std::string Port::username_fragment() const {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700740 return ice_username_fragment_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000741}
742
743// A ConnectionRequest is a simple STUN ping used to determine writability.
744class ConnectionRequest : public StunRequest {
745 public:
746 explicit ConnectionRequest(Connection* connection)
747 : StunRequest(new IceMessage()),
748 connection_(connection) {
749 }
750
751 virtual ~ConnectionRequest() {
752 }
753
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700754 void Prepare(StunMessage* request) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000755 request->SetType(STUN_BINDING_REQUEST);
756 std::string username;
757 connection_->port()->CreateStunUsername(
758 connection_->remote_candidate().username(), &username);
759 request->AddAttribute(
760 new StunByteStringAttribute(STUN_ATTR_USERNAME, username));
761
762 // connection_ already holds this ping, so subtract one from count.
763 if (connection_->port()->send_retransmit_count_attribute()) {
764 request->AddAttribute(new StunUInt32Attribute(
765 STUN_ATTR_RETRANSMIT_COUNT,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200766 static_cast<uint32_t>(connection_->pings_since_last_response_.size() -
767 1)));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000768 }
honghaiza0c44ea2016-03-23 16:07:48 -0700769 uint32_t network_info = connection_->port()->Network()->id();
770 network_info = (network_info << 16) | connection_->port()->network_cost();
771 request->AddAttribute(
772 new StunUInt32Attribute(STUN_ATTR_NETWORK_INFO, network_info));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000773
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700774 // Adding ICE_CONTROLLED or ICE_CONTROLLING attribute based on the role.
775 if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLING) {
776 request->AddAttribute(new StunUInt64Attribute(
777 STUN_ATTR_ICE_CONTROLLING, connection_->port()->IceTiebreaker()));
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700778 // We should have either USE_CANDIDATE attribute or ICE_NOMINATION
779 // attribute but not both. That was enforced in p2ptransportchannel.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700780 if (connection_->use_candidate_attr()) {
781 request->AddAttribute(new StunByteStringAttribute(
782 STUN_ATTR_USE_CANDIDATE));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000783 }
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700784 if (connection_->nomination() &&
785 connection_->nomination() != connection_->acked_nomination()) {
786 request->AddAttribute(new StunUInt32Attribute(
787 STUN_ATTR_NOMINATION, connection_->nomination()));
788 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700789 } else if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLED) {
790 request->AddAttribute(new StunUInt64Attribute(
791 STUN_ATTR_ICE_CONTROLLED, connection_->port()->IceTiebreaker()));
792 } else {
793 ASSERT(false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000794 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700795
796 // Adding PRIORITY Attribute.
797 // Changing the type preference to Peer Reflexive and local preference
798 // and component id information is unchanged from the original priority.
799 // priority = (2^24)*(type preference) +
800 // (2^8)*(local preference) +
801 // (2^0)*(256 - component ID)
Taylor Brandstetter62351c92016-08-11 16:05:07 -0700802 uint32_t type_preference =
803 (connection_->local_candidate().protocol() == TCP_PROTOCOL_NAME)
804 ? ICE_TYPE_PREFERENCE_PRFLX_TCP
805 : ICE_TYPE_PREFERENCE_PRFLX;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200806 uint32_t prflx_priority =
Taylor Brandstetter62351c92016-08-11 16:05:07 -0700807 type_preference << 24 |
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700808 (connection_->local_candidate().priority() & 0x00FFFFFF);
809 request->AddAttribute(
810 new StunUInt32Attribute(STUN_ATTR_PRIORITY, prflx_priority));
811
812 // Adding Message Integrity attribute.
813 request->AddMessageIntegrity(connection_->remote_candidate().password());
814 // Adding Fingerprint.
815 request->AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000816 }
817
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700818 void OnResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000819 connection_->OnConnectionRequestResponse(this, response);
820 }
821
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700822 void OnErrorResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000823 connection_->OnConnectionRequestErrorResponse(this, response);
824 }
825
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700826 void OnTimeout() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000827 connection_->OnConnectionRequestTimeout(this);
828 }
829
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700830 void OnSent() override {
831 connection_->OnConnectionRequestSent(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000832 // Each request is sent only once. After a single delay , the request will
833 // time out.
834 timeout_ = true;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700835 }
836
837 int resend_delay() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000838 return CONNECTION_RESPONSE_TIMEOUT;
839 }
840
841 private:
842 Connection* connection_;
843};
844
845//
846// Connection
847//
848
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000849Connection::Connection(Port* port,
850 size_t index,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000851 const Candidate& remote_candidate)
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000852 : port_(port),
853 local_candidate_index_(index),
854 remote_candidate_(remote_candidate),
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700855 recv_rate_tracker_(100, 10u),
856 send_rate_tracker_(100, 10u),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000857 write_state_(STATE_WRITE_INIT),
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700858 receiving_(false),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000859 connected_(true),
860 pruned_(false),
861 use_candidate_attr_(false),
862 remote_ice_mode_(ICEMODE_FULL),
863 requests_(port->thread()),
864 rtt_(DEFAULT_RTT),
865 last_ping_sent_(0),
866 last_ping_received_(0),
867 last_data_received_(0),
868 last_ping_response_received_(0),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000869 reported_(false),
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700870 state_(STATE_WAITING),
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700871 receiving_timeout_(WEAK_CONNECTION_RECEIVE_TIMEOUT),
nisse1bffc1d2016-05-02 08:18:55 -0700872 time_created_ms_(rtc::TimeMillis()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000873 // All of our connections start in WAITING state.
874 // TODO(mallinath) - Start connections from STATE_FROZEN.
875 // Wire up to send stun packets
876 requests_.SignalSendPacket.connect(this, &Connection::OnSendStunPacket);
877 LOG_J(LS_INFO, this) << "Connection created";
878}
879
880Connection::~Connection() {
881}
882
883const Candidate& Connection::local_candidate() const {
884 ASSERT(local_candidate_index_ < port_->Candidates().size());
885 return port_->Candidates()[local_candidate_index_];
886}
887
Honghai Zhangcc411c02016-03-29 17:27:21 -0700888const Candidate& Connection::remote_candidate() const {
889 return remote_candidate_;
890}
891
Peter Boström0c4e06b2015-10-07 12:23:21 +0200892uint64_t Connection::priority() const {
893 uint64_t priority = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000894 // RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs
895 // Let G be the priority for the candidate provided by the controlling
896 // agent. Let D be the priority for the candidate provided by the
897 // controlled agent.
898 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
899 IceRole role = port_->GetIceRole();
900 if (role != ICEROLE_UNKNOWN) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200901 uint32_t g = 0;
902 uint32_t d = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000903 if (role == ICEROLE_CONTROLLING) {
904 g = local_candidate().priority();
905 d = remote_candidate_.priority();
906 } else {
907 g = remote_candidate_.priority();
908 d = local_candidate().priority();
909 }
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000910 priority = std::min(g, d);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000911 priority = priority << 32;
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000912 priority += 2 * std::max(g, d) + (g > d ? 1 : 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000913 }
914 return priority;
915}
916
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000917void Connection::set_write_state(WriteState value) {
918 WriteState old_value = write_state_;
919 write_state_ = value;
920 if (value != old_value) {
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +0000921 LOG_J(LS_VERBOSE, this) << "set_write_state from: " << old_value << " to "
922 << value;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000923 SignalStateChange(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000924 }
925}
926
honghaiz9ad0db52016-07-14 19:30:28 -0700927void Connection::UpdateReceiving(int64_t now) {
honghaize58d73d2016-10-24 16:38:26 -0700928 bool receiving =
929 last_received() > 0 && now <= last_received() + receiving_timeout_;
honghaiz9ad0db52016-07-14 19:30:28 -0700930 if (receiving_ == receiving) {
931 return;
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700932 }
honghaiz9ad0db52016-07-14 19:30:28 -0700933 LOG_J(LS_VERBOSE, this) << "set_receiving to " << receiving;
934 receiving_ = receiving;
935 receiving_unchanged_since_ = now;
936 SignalStateChange(this);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700937}
938
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000939void Connection::set_state(State state) {
940 State old_state = state_;
941 state_ = state;
942 if (state != old_state) {
943 LOG_J(LS_VERBOSE, this) << "set_state";
944 }
945}
946
947void Connection::set_connected(bool value) {
948 bool old_value = connected_;
949 connected_ = value;
950 if (value != old_value) {
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700951 LOG_J(LS_VERBOSE, this) << "set_connected from: " << old_value << " to "
952 << value;
Taylor Brandstetterb825aee2016-06-29 13:07:16 -0700953 SignalStateChange(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000954 }
955}
956
957void Connection::set_use_candidate_attr(bool enable) {
958 use_candidate_attr_ = enable;
959}
960
961void Connection::OnSendStunPacket(const void* data, size_t size,
962 StunRequest* req) {
963 rtc::PacketOptions options(port_->DefaultDscpValue());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700964 auto err = port_->SendTo(
965 data, size, remote_candidate_.address(), options, false);
966 if (err < 0) {
967 LOG_J(LS_WARNING, this) << "Failed to send STUN ping "
968 << " err=" << err
969 << " id=" << rtc::hex_encode(req->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000970 }
971}
972
973void Connection::OnReadPacket(
974 const char* data, size_t size, const rtc::PacketTime& packet_time) {
kwiberg3ec46792016-04-27 07:22:53 -0700975 std::unique_ptr<IceMessage> msg;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000976 std::string remote_ufrag;
977 const rtc::SocketAddress& addr(remote_candidate_.address());
kwiberg6baec032016-03-15 11:09:39 -0700978 if (!port_->GetStunMessage(data, size, addr, &msg, &remote_ufrag)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000979 // The packet did not parse as a valid STUN message
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700980 // This is a data packet, pass it along.
nisse1bffc1d2016-05-02 08:18:55 -0700981 last_data_received_ = rtc::TimeMillis();
honghaiz9ad0db52016-07-14 19:30:28 -0700982 UpdateReceiving(last_data_received_);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700983 recv_rate_tracker_.AddSamples(size);
984 SignalReadPacket(this, data, size, packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000985
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700986 // If timed out sending writability checks, start up again
987 if (!pruned_ && (write_state_ == STATE_WRITE_TIMEOUT)) {
988 LOG(LS_WARNING) << "Received a data packet on a timed-out Connection. "
989 << "Resetting state to STATE_WRITE_INIT.";
990 set_write_state(STATE_WRITE_INIT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000991 }
992 } else if (!msg) {
993 // The packet was STUN, but failed a check and was handled internally.
994 } else {
995 // The packet is STUN and passed the Port checks.
996 // Perform our own checks to ensure this packet is valid.
honghaizd0b31432015-09-30 12:42:17 -0700997 // If this is a STUN request, then update the receiving bit and respond.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000998 // If this is a STUN response, then update the writable bit.
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700999 // Log at LS_INFO if we receive a ping on an unwritable connection.
1000 rtc::LoggingSeverity sev = (!writable() ? rtc::LS_INFO : rtc::LS_VERBOSE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001001 switch (msg->type()) {
1002 case STUN_BINDING_REQUEST:
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001003 LOG_JV(sev, this) << "Received STUN ping"
1004 << ", id=" << rtc::hex_encode(msg->transaction_id());
1005
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001006 if (remote_ufrag == remote_candidate_.username()) {
honghaiz9b5ee9c2015-11-11 13:19:17 -08001007 HandleBindingRequest(msg.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001008 } else {
1009 // The packet had the right local username, but the remote username
1010 // was not the right one for the remote address.
1011 LOG_J(LS_ERROR, this)
1012 << "Received STUN request with bad remote username "
1013 << remote_ufrag;
1014 port_->SendBindingErrorResponse(msg.get(), addr,
1015 STUN_ERROR_UNAUTHORIZED,
1016 STUN_ERROR_REASON_UNAUTHORIZED);
1017
1018 }
1019 break;
1020
1021 // Response from remote peer. Does it match request sent?
1022 // This doesn't just check, it makes callbacks if transaction
1023 // id's match.
1024 case STUN_BINDING_RESPONSE:
1025 case STUN_BINDING_ERROR_RESPONSE:
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001026 if (msg->ValidateMessageIntegrity(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001027 data, size, remote_candidate().password())) {
1028 requests_.CheckResponse(msg.get());
1029 }
1030 // Otherwise silently discard the response message.
1031 break;
1032
honghaizd0b31432015-09-30 12:42:17 -07001033 // Remote end point sent an STUN indication instead of regular binding
1034 // request. In this case |last_ping_received_| will be updated but no
1035 // response will be sent.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001036 case STUN_BINDING_INDICATION:
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001037 ReceivedPing();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001038 break;
1039
1040 default:
1041 ASSERT(false);
1042 break;
1043 }
1044 }
1045}
1046
honghaiz9b5ee9c2015-11-11 13:19:17 -08001047void Connection::HandleBindingRequest(IceMessage* msg) {
1048 // This connection should now be receiving.
1049 ReceivedPing();
1050
1051 const rtc::SocketAddress& remote_addr = remote_candidate_.address();
1052 const std::string& remote_ufrag = remote_candidate_.username();
1053 // Check for role conflicts.
1054 if (!port_->MaybeIceRoleConflict(remote_addr, msg, remote_ufrag)) {
1055 // Received conflicting role from the peer.
1056 LOG(LS_INFO) << "Received conflicting role from the peer.";
1057 return;
1058 }
1059
zhihuang5ecf16c2016-06-01 17:09:15 -07001060 stats_.recv_ping_requests++;
1061
honghaiz9b5ee9c2015-11-11 13:19:17 -08001062 // This is a validated stun request from remote peer.
1063 port_->SendBindingResponse(msg, remote_addr);
1064
1065 // If it timed out on writing check, start up again
1066 if (!pruned_ && write_state_ == STATE_WRITE_TIMEOUT) {
1067 set_write_state(STATE_WRITE_INIT);
1068 }
1069
1070 if (port_->GetIceRole() == ICEROLE_CONTROLLED) {
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001071 const StunUInt32Attribute* nomination_attr =
1072 msg->GetUInt32(STUN_ATTR_NOMINATION);
1073 uint32_t nomination = 0;
1074 if (nomination_attr) {
1075 nomination = nomination_attr->value();
1076 if (nomination == 0) {
1077 LOG(LS_ERROR) << "Invalid nomination: " << nomination;
1078 }
1079 } else {
1080 const StunByteStringAttribute* use_candidate_attr =
1081 msg->GetByteString(STUN_ATTR_USE_CANDIDATE);
1082 if (use_candidate_attr) {
1083 nomination = 1;
1084 }
1085 }
1086 // We don't un-nominate a connection, so we only keep a larger nomination.
1087 if (nomination > remote_nomination_) {
1088 set_remote_nomination(nomination);
honghaiz9b5ee9c2015-11-11 13:19:17 -08001089 SignalNominated(this);
1090 }
1091 }
Honghai Zhang351d77b2016-05-20 15:08:29 -07001092 // Set the remote cost if the network_info attribute is available.
1093 // Note: If packets are re-ordered, we may get incorrect network cost
1094 // temporarily, but it should get the correct value shortly after that.
1095 const StunUInt32Attribute* network_attr =
1096 msg->GetUInt32(STUN_ATTR_NETWORK_INFO);
1097 if (network_attr) {
1098 uint32_t network_info = network_attr->value();
1099 uint16_t network_cost = static_cast<uint16_t>(network_info);
1100 if (network_cost != remote_candidate_.network_cost()) {
1101 remote_candidate_.set_network_cost(network_cost);
1102 // Network cost change will affect the connection ranking, so signal
1103 // state change to force a re-sort in P2PTransportChannel.
1104 SignalStateChange(this);
1105 }
1106 }
honghaiz9b5ee9c2015-11-11 13:19:17 -08001107}
1108
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001109void Connection::OnReadyToSend() {
deadbeefdd7fb432016-09-30 15:16:48 -07001110 SignalReadyToSend(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001111}
1112
1113void Connection::Prune() {
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001114 if (!pruned_ || active()) {
Honghai Zhang1590c392016-05-24 13:15:02 -07001115 LOG_J(LS_INFO, this) << "Connection pruned";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001116 pruned_ = true;
1117 requests_.Clear();
1118 set_write_state(STATE_WRITE_TIMEOUT);
1119 }
1120}
1121
1122void Connection::Destroy() {
1123 LOG_J(LS_VERBOSE, this) << "Connection destroyed";
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001124 port_->thread()->Post(RTC_FROM_HERE, this, MSG_DELETE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001125}
1126
deadbeef376e1232015-11-25 09:00:08 -08001127void Connection::FailAndDestroy() {
1128 set_state(Connection::STATE_FAILED);
1129 Destroy();
1130}
1131
honghaiz079a7a12016-06-22 16:26:29 -07001132void Connection::FailAndPrune() {
1133 set_state(Connection::STATE_FAILED);
1134 Prune();
1135}
1136
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001137void Connection::PrintPingsSinceLastResponse(std::string* s, size_t max) {
1138 std::ostringstream oss;
1139 oss << std::boolalpha;
1140 if (pings_since_last_response_.size() > max) {
1141 for (size_t i = 0; i < max; i++) {
1142 const SentPing& ping = pings_since_last_response_[i];
1143 oss << rtc::hex_encode(ping.id) << " ";
1144 }
1145 oss << "... " << (pings_since_last_response_.size() - max) << " more";
1146 } else {
1147 for (const SentPing& ping : pings_since_last_response_) {
1148 oss << rtc::hex_encode(ping.id) << " ";
1149 }
1150 }
1151 *s = oss.str();
1152}
1153
honghaiz34b11eb2016-03-16 08:55:44 -07001154void Connection::UpdateState(int64_t now) {
1155 int rtt = ConservativeRTTEstimate(rtt_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001156
Peter Thatcherb2d26232015-05-15 11:25:14 -07001157 if (LOG_CHECK_LEVEL(LS_VERBOSE)) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001158 std::string pings;
1159 PrintPingsSinceLastResponse(&pings, 5);
1160 LOG_J(LS_VERBOSE, this) << "UpdateState()"
1161 << ", ms since last received response="
1162 << now - last_ping_response_received_
1163 << ", ms since last received data="
1164 << now - last_data_received_
1165 << ", rtt=" << rtt
1166 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001167 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001168
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001169 // Check the writable state. (The order of these checks is important.)
1170 //
1171 // Before becoming unwritable, we allow for a fixed number of pings to fail
1172 // (i.e., receive no response). We also have to give the response time to
1173 // get back, so we include a conservative estimate of this.
1174 //
1175 // Before timing out writability, we give a fixed amount of time. This is to
1176 // allow for changes in network conditions.
1177
1178 if ((write_state_ == STATE_WRITABLE) &&
1179 TooManyFailures(pings_since_last_response_,
1180 CONNECTION_WRITE_CONNECT_FAILURES,
1181 rtt,
1182 now) &&
1183 TooLongWithoutResponse(pings_since_last_response_,
1184 CONNECTION_WRITE_CONNECT_TIMEOUT,
1185 now)) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001186 uint32_t max_pings = CONNECTION_WRITE_CONNECT_FAILURES;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001187 LOG_J(LS_INFO, this) << "Unwritable after " << max_pings
1188 << " ping failures and "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001189 << now - pings_since_last_response_[0].sent_time
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001190 << " ms without a response,"
1191 << " ms since last received ping="
1192 << now - last_ping_received_
1193 << " ms since last received data="
1194 << now - last_data_received_
1195 << " rtt=" << rtt;
1196 set_write_state(STATE_WRITE_UNRELIABLE);
1197 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001198 if ((write_state_ == STATE_WRITE_UNRELIABLE ||
1199 write_state_ == STATE_WRITE_INIT) &&
1200 TooLongWithoutResponse(pings_since_last_response_,
1201 CONNECTION_WRITE_TIMEOUT,
1202 now)) {
1203 LOG_J(LS_INFO, this) << "Timed out after "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001204 << now - pings_since_last_response_[0].sent_time
1205 << " ms without a response"
1206 << ", rtt=" << rtt;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001207 set_write_state(STATE_WRITE_TIMEOUT);
1208 }
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001209
honghaiz9ad0db52016-07-14 19:30:28 -07001210 // Update the receiving state.
1211 UpdateReceiving(now);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001212 if (dead(now)) {
1213 Destroy();
1214 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001215}
1216
honghaiz34b11eb2016-03-16 08:55:44 -07001217void Connection::Ping(int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001218 last_ping_sent_ = now;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001219 ConnectionRequest *req = new ConnectionRequest(this);
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001220 pings_since_last_response_.push_back(SentPing(req->id(), now, nomination_));
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001221 LOG_J(LS_VERBOSE, this) << "Sending STUN ping "
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001222 << ", id=" << rtc::hex_encode(req->id())
1223 << ", nomination=" << nomination_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001224 requests_.Send(req);
1225 state_ = STATE_INPROGRESS;
honghaiz524ecc22016-05-25 12:48:31 -07001226 num_pings_sent_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001227}
1228
1229void Connection::ReceivedPing() {
nisse1bffc1d2016-05-02 08:18:55 -07001230 last_ping_received_ = rtc::TimeMillis();
honghaiz9ad0db52016-07-14 19:30:28 -07001231 UpdateReceiving(last_ping_received_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001232}
1233
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001234void Connection::ReceivedPingResponse(int rtt, const std::string& request_id) {
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001235 // We've already validated that this is a STUN binding response with
1236 // the correct local and remote username for this connection.
1237 // So if we're not already, become writable. We may be bringing a pruned
1238 // connection back to life, but if we don't really want it, we can always
1239 // prune it again.
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001240 auto iter = std::find_if(
1241 pings_since_last_response_.begin(), pings_since_last_response_.end(),
1242 [request_id](const SentPing& ping) { return ping.id == request_id; });
1243 if (iter != pings_since_last_response_.end() &&
1244 iter->nomination > acked_nomination_) {
1245 acked_nomination_ = iter->nomination;
1246 }
1247
1248 pings_since_last_response_.clear();
honghaiz9ad0db52016-07-14 19:30:28 -07001249 last_ping_response_received_ = rtc::TimeMillis();
1250 UpdateReceiving(last_ping_response_received_);
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001251 set_write_state(STATE_WRITABLE);
1252 set_state(STATE_SUCCEEDED);
zhihuang435264a2016-06-21 11:28:38 -07001253 rtt_samples_++;
1254 rtt_ = (RTT_RATIO * rtt_ + rtt) / (RTT_RATIO + 1);
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001255}
1256
honghaiz34b11eb2016-03-16 08:55:44 -07001257bool Connection::dead(int64_t now) const {
honghaiz37389b42016-01-04 21:57:33 -08001258 if (last_received() > 0) {
1259 // If it has ever received anything, we keep it alive until it hasn't
1260 // received anything for DEAD_CONNECTION_RECEIVE_TIMEOUT. This covers the
1261 // normal case of a successfully used connection that stops working. This
1262 // also allows a remote peer to continue pinging over a locally inactive
1263 // (pruned) connection.
1264 return (now > (last_received() + DEAD_CONNECTION_RECEIVE_TIMEOUT));
1265 }
1266
1267 if (active()) {
1268 // If it has never received anything, keep it alive as long as it is
1269 // actively pinging and not pruned. Otherwise, the connection might be
1270 // deleted before it has a chance to ping. This is the normal case for a
1271 // new connection that is pinging but hasn't received anything yet.
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001272 return false;
1273 }
1274
honghaiz37389b42016-01-04 21:57:33 -08001275 // If it has never received anything and is not actively pinging (pruned), we
1276 // keep it around for at least MIN_CONNECTION_LIFETIME to prevent connections
1277 // from being pruned too quickly during a network change event when two
1278 // networks would be up simultaneously but only for a brief period.
1279 return now > (time_created_ms_ + MIN_CONNECTION_LIFETIME);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001280}
1281
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001282bool Connection::stable(int64_t now) const {
zhihuang435264a2016-06-21 11:28:38 -07001283 // A connection is stable if it's RTT has converged and it isn't missing any
1284 // responses. We should send pings at a higher rate until the RTT converges
1285 // and whenever a ping response is missing (so that we can detect
1286 // unwritability faster)
1287 return rtt_converged() && !missing_responses(now);
1288}
1289
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +00001290std::string Connection::ToDebugId() const {
1291 std::stringstream ss;
1292 ss << std::hex << this;
1293 return ss.str();
1294}
1295
honghaize1a0c942016-02-16 14:54:56 -08001296uint32_t Connection::ComputeNetworkCost() const {
1297 // TODO(honghaiz): Will add rtt as part of the network cost.
Honghai Zhang351d77b2016-05-20 15:08:29 -07001298 return port()->network_cost() + remote_candidate_.network_cost();
honghaize1a0c942016-02-16 14:54:56 -08001299}
1300
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001301std::string Connection::ToString() const {
1302 const char CONNECT_STATE_ABBREV[2] = {
1303 '-', // not connected (false)
1304 'C', // connected (true)
1305 };
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001306 const char RECEIVE_STATE_ABBREV[2] = {
1307 '-', // not receiving (false)
1308 'R', // receiving (true)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001309 };
1310 const char WRITE_STATE_ABBREV[4] = {
1311 'W', // STATE_WRITABLE
1312 'w', // STATE_WRITE_UNRELIABLE
1313 '-', // STATE_WRITE_INIT
1314 'x', // STATE_WRITE_TIMEOUT
1315 };
1316 const std::string ICESTATE[4] = {
1317 "W", // STATE_WAITING
1318 "I", // STATE_INPROGRESS
1319 "S", // STATE_SUCCEEDED
1320 "F" // STATE_FAILED
1321 };
1322 const Candidate& local = local_candidate();
1323 const Candidate& remote = remote_candidate();
1324 std::stringstream ss;
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001325 ss << "Conn[" << ToDebugId() << ":" << port_->content_name() << ":"
1326 << local.id() << ":" << local.component() << ":" << local.generation()
1327 << ":" << local.type() << ":" << local.protocol() << ":"
1328 << local.address().ToSensitiveString() << "->" << remote.id() << ":"
1329 << remote.component() << ":" << remote.priority() << ":" << remote.type()
1330 << ":" << remote.protocol() << ":" << remote.address().ToSensitiveString()
1331 << "|" << CONNECT_STATE_ABBREV[connected()]
1332 << RECEIVE_STATE_ABBREV[receiving()] << WRITE_STATE_ABBREV[write_state()]
1333 << ICESTATE[state()] << "|" << remote_nomination() << "|" << nomination()
1334 << "|" << priority() << "|";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001335 if (rtt_ < DEFAULT_RTT) {
1336 ss << rtt_ << "]";
1337 } else {
1338 ss << "-]";
1339 }
1340 return ss.str();
1341}
1342
1343std::string Connection::ToSensitiveString() const {
1344 return ToString();
1345}
1346
1347void Connection::OnConnectionRequestResponse(ConnectionRequest* request,
1348 StunMessage* response) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001349 // Log at LS_INFO if we receive a ping response on an unwritable
1350 // connection.
1351 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1352
honghaiz34b11eb2016-03-16 08:55:44 -07001353 int rtt = request->Elapsed();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001354
Peter Thatcherb2d26232015-05-15 11:25:14 -07001355 if (LOG_CHECK_LEVEL_V(sev)) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001356 std::string pings;
1357 PrintPingsSinceLastResponse(&pings, 5);
1358 LOG_JV(sev, this) << "Received STUN ping response"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001359 << ", id=" << rtc::hex_encode(request->id())
1360 << ", code=0" // Makes logging easier to parse.
1361 << ", rtt=" << rtt
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001362 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001363 }
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001364 ReceivedPingResponse(rtt, request->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001365
zhihuang5ecf16c2016-06-01 17:09:15 -07001366 stats_.recv_ping_responses++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001367
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001368 MaybeUpdateLocalCandidate(request, response);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001369}
1370
1371void Connection::OnConnectionRequestErrorResponse(ConnectionRequest* request,
1372 StunMessage* response) {
1373 const StunErrorCodeAttribute* error_attr = response->GetErrorCode();
1374 int error_code = STUN_ERROR_GLOBAL_FAILURE;
1375 if (error_attr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001376 error_code = error_attr->code();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001377 }
1378
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001379 LOG_J(LS_INFO, this) << "Received STUN error response"
1380 << " id=" << rtc::hex_encode(request->id())
1381 << " code=" << error_code
1382 << " rtt=" << request->Elapsed();
1383
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001384 if (error_code == STUN_ERROR_UNKNOWN_ATTRIBUTE ||
1385 error_code == STUN_ERROR_SERVER_ERROR ||
1386 error_code == STUN_ERROR_UNAUTHORIZED) {
1387 // Recoverable error, retry
1388 } else if (error_code == STUN_ERROR_STALE_CREDENTIALS) {
1389 // Race failure, retry
1390 } else if (error_code == STUN_ERROR_ROLE_CONFLICT) {
1391 HandleRoleConflictFromPeer();
1392 } else {
1393 // This is not a valid connection.
1394 LOG_J(LS_ERROR, this) << "Received STUN error response, code="
1395 << error_code << "; killing connection";
deadbeef376e1232015-11-25 09:00:08 -08001396 FailAndDestroy();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001397 }
1398}
1399
1400void Connection::OnConnectionRequestTimeout(ConnectionRequest* request) {
1401 // Log at LS_INFO if we miss a ping on a writable connection.
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001402 rtc::LoggingSeverity sev = writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1403 LOG_JV(sev, this) << "Timing-out STUN ping "
1404 << rtc::hex_encode(request->id())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001405 << " after " << request->Elapsed() << " ms";
1406}
1407
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001408void Connection::OnConnectionRequestSent(ConnectionRequest* request) {
1409 // Log at LS_INFO if we send a ping on an unwritable connection.
1410 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1411 LOG_JV(sev, this) << "Sent STUN ping"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001412 << ", id=" << rtc::hex_encode(request->id())
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001413 << ", use_candidate=" << use_candidate_attr()
1414 << ", nomination=" << nomination();
zhihuang5ecf16c2016-06-01 17:09:15 -07001415 stats_.sent_ping_requests_total++;
1416 if (stats_.recv_ping_responses == 0) {
1417 stats_.sent_ping_requests_before_first_response++;
1418 }
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001419}
1420
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001421void Connection::HandleRoleConflictFromPeer() {
1422 port_->SignalRoleConflict(port_);
1423}
1424
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001425void Connection::MaybeSetRemoteIceParametersAndGeneration(
1426 const IceParameters& ice_params,
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001427 int generation) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001428 if (remote_candidate_.username() == ice_params.ufrag &&
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001429 remote_candidate_.password().empty()) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001430 remote_candidate_.set_password(ice_params.pwd);
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001431 }
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001432 // TODO(deadbeef): A value of '0' for the generation is used for both
1433 // generation 0 and "generation unknown". It should be changed to an
1434 // rtc::Optional to fix this.
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001435 if (remote_candidate_.username() == ice_params.ufrag &&
1436 remote_candidate_.password() == ice_params.pwd &&
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001437 remote_candidate_.generation() == 0) {
1438 remote_candidate_.set_generation(generation);
1439 }
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001440}
1441
1442void Connection::MaybeUpdatePeerReflexiveCandidate(
1443 const Candidate& new_candidate) {
1444 if (remote_candidate_.type() == PRFLX_PORT_TYPE &&
1445 new_candidate.type() != PRFLX_PORT_TYPE &&
1446 remote_candidate_.protocol() == new_candidate.protocol() &&
1447 remote_candidate_.address() == new_candidate.address() &&
1448 remote_candidate_.username() == new_candidate.username() &&
1449 remote_candidate_.password() == new_candidate.password() &&
1450 remote_candidate_.generation() == new_candidate.generation()) {
1451 remote_candidate_ = new_candidate;
1452 }
1453}
1454
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001455void Connection::OnMessage(rtc::Message *pmsg) {
1456 ASSERT(pmsg->message_id == MSG_DELETE);
honghaiz18f9da02016-06-01 23:53:01 -07001457 LOG(LS_INFO) << "Connection deleted with number of pings sent: "
1458 << num_pings_sent_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001459 SignalDestroyed(this);
1460 delete this;
1461}
1462
honghaiz34b11eb2016-03-16 08:55:44 -07001463int64_t Connection::last_received() const {
Peter Thatcher54360512015-07-08 11:08:35 -07001464 return std::max(last_data_received_,
1465 std::max(last_ping_received_, last_ping_response_received_));
1466}
1467
zhihuang5ecf16c2016-06-01 17:09:15 -07001468ConnectionInfo Connection::stats() {
1469 stats_.recv_bytes_second = round(recv_rate_tracker_.ComputeRate());
1470 stats_.recv_total_bytes = recv_rate_tracker_.TotalSampleCount();
1471 stats_.sent_bytes_second = round(send_rate_tracker_.ComputeRate());
1472 stats_.sent_total_bytes = send_rate_tracker_.TotalSampleCount();
1473 return stats_;
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001474}
1475
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001476void Connection::MaybeUpdateLocalCandidate(ConnectionRequest* request,
1477 StunMessage* response) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001478 // RFC 5245
1479 // The agent checks the mapped address from the STUN response. If the
1480 // transport address does not match any of the local candidates that the
1481 // agent knows about, the mapped address represents a new candidate -- a
1482 // peer reflexive candidate.
1483 const StunAddressAttribute* addr =
1484 response->GetAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
1485 if (!addr) {
1486 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1487 << "No MAPPED-ADDRESS or XOR-MAPPED-ADDRESS found in the "
1488 << "stun response message";
1489 return;
1490 }
1491
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001492 for (size_t i = 0; i < port_->Candidates().size(); ++i) {
1493 if (port_->Candidates()[i].address() == addr->GetAddress()) {
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001494 if (local_candidate_index_ != i) {
1495 LOG_J(LS_INFO, this) << "Updating local candidate type to srflx.";
1496 local_candidate_index_ = i;
1497 // SignalStateChange to force a re-sort in P2PTransportChannel as this
1498 // Connection's local candidate has changed.
1499 SignalStateChange(this);
1500 }
1501 return;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001502 }
1503 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001504
1505 // RFC 5245
1506 // Its priority is set equal to the value of the PRIORITY attribute
1507 // in the Binding request.
1508 const StunUInt32Attribute* priority_attr =
1509 request->msg()->GetUInt32(STUN_ATTR_PRIORITY);
1510 if (!priority_attr) {
1511 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1512 << "No STUN_ATTR_PRIORITY found in the "
1513 << "stun response message";
1514 return;
1515 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001516 const uint32_t priority = priority_attr->value();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001517 std::string id = rtc::CreateRandomString(8);
1518
1519 Candidate new_local_candidate;
1520 new_local_candidate.set_id(id);
1521 new_local_candidate.set_component(local_candidate().component());
1522 new_local_candidate.set_type(PRFLX_PORT_TYPE);
1523 new_local_candidate.set_protocol(local_candidate().protocol());
1524 new_local_candidate.set_address(addr->GetAddress());
1525 new_local_candidate.set_priority(priority);
1526 new_local_candidate.set_username(local_candidate().username());
1527 new_local_candidate.set_password(local_candidate().password());
1528 new_local_candidate.set_network_name(local_candidate().network_name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001529 new_local_candidate.set_network_type(local_candidate().network_type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001530 new_local_candidate.set_related_address(local_candidate().address());
Taylor Brandstetterf7c15a92016-06-22 13:13:55 -07001531 new_local_candidate.set_generation(local_candidate().generation());
Honghai Zhang80f1db92016-01-27 11:54:45 -08001532 new_local_candidate.set_foundation(ComputeFoundation(
1533 PRFLX_PORT_TYPE, local_candidate().protocol(),
1534 local_candidate().relay_protocol(), local_candidate().address()));
honghaiza0c44ea2016-03-23 16:07:48 -07001535 new_local_candidate.set_network_id(local_candidate().network_id());
1536 new_local_candidate.set_network_cost(local_candidate().network_cost());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001537
1538 // Change the local candidate of this Connection to the new prflx candidate.
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001539 LOG_J(LS_INFO, this) << "Updating local candidate type to prflx.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001540 local_candidate_index_ = port_->AddPrflxCandidate(new_local_candidate);
1541
1542 // SignalStateChange to force a re-sort in P2PTransportChannel as this
1543 // Connection's local candidate has changed.
1544 SignalStateChange(this);
1545}
1546
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001547bool Connection::rtt_converged() const {
zhihuang435264a2016-06-21 11:28:38 -07001548 return rtt_samples_ > (RTT_RATIO + 1);
1549}
1550
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001551bool Connection::missing_responses(int64_t now) const {
zhihuang435264a2016-06-21 11:28:38 -07001552 if (pings_since_last_response_.empty()) {
1553 return false;
1554 }
1555
1556 int64_t waiting = now - pings_since_last_response_[0].sent_time;
1557 return waiting > 2 * rtt();
1558}
1559
deadbeef376e1232015-11-25 09:00:08 -08001560ProxyConnection::ProxyConnection(Port* port,
1561 size_t index,
1562 const Candidate& remote_candidate)
1563 : Connection(port, index, remote_candidate) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001564
1565int ProxyConnection::Send(const void* data, size_t size,
1566 const rtc::PacketOptions& options) {
zhihuang5ecf16c2016-06-01 17:09:15 -07001567 stats_.sent_total_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001568 int sent = port_->SendTo(data, size, remote_candidate_.address(),
1569 options, true);
1570 if (sent <= 0) {
1571 ASSERT(sent < 0);
1572 error_ = port_->GetError();
zhihuang5ecf16c2016-06-01 17:09:15 -07001573 stats_.sent_discarded_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001574 } else {
Tim Psiaki63046262015-09-14 10:38:08 -07001575 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001576 }
1577 return sent;
1578}
1579
1580} // namespace cricket