blob: eb63436dc8d83806e60d12aab074a5bf0094e4ee [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";
hnsl277b2502016-12-13 05:17:23 -080092const char TLS_PROTOCOL_NAME[] = "tls";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000093
hnsl277b2502016-12-13 05:17:23 -080094static const char* const PROTO_NAMES[] = {UDP_PROTOCOL_NAME, TCP_PROTOCOL_NAME,
95 SSLTCP_PROTOCOL_NAME,
96 TLS_PROTOCOL_NAME};
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000097
98const char* ProtoToString(ProtocolType proto) {
99 return PROTO_NAMES[proto];
100}
101
102bool StringToProto(const char* value, ProtocolType* proto) {
103 for (size_t i = 0; i <= PROTO_LAST; ++i) {
104 if (_stricmp(PROTO_NAMES[i], value) == 0) {
105 *proto = static_cast<ProtocolType>(i);
106 return true;
107 }
108 }
109 return false;
110}
111
112// RFC 6544, TCP candidate encoding rules.
113const int DISCARD_PORT = 9;
114const char TCPTYPE_ACTIVE_STR[] = "active";
115const char TCPTYPE_PASSIVE_STR[] = "passive";
116const char TCPTYPE_SIMOPEN_STR[] = "so";
117
118// Foundation: An arbitrary string that is the same for two candidates
119// that have the same type, base IP address, protocol (UDP, TCP,
120// etc.), and STUN or TURN server. If any of these are different,
121// then the foundation will be different. Two candidate pairs with
122// the same foundation pairs are likely to have similar network
123// characteristics. Foundations are used in the frozen algorithm.
Honghai Zhang80f1db92016-01-27 11:54:45 -0800124static std::string ComputeFoundation(const std::string& type,
125 const std::string& protocol,
126 const std::string& relay_protocol,
127 const rtc::SocketAddress& base_address) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000128 std::ostringstream ost;
Honghai Zhang80f1db92016-01-27 11:54:45 -0800129 ost << type << base_address.ipaddr().ToString() << protocol << relay_protocol;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200130 return rtc::ToString<uint32_t>(rtc::ComputeCrc32(ost.str()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000131}
132
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000133Port::Port(rtc::Thread* thread,
Honghai Zhangd00c0572016-06-28 09:44:47 -0700134 const std::string& type,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000135 rtc::PacketSocketFactory* factory,
136 rtc::Network* network,
137 const rtc::IPAddress& ip,
138 const std::string& username_fragment,
139 const std::string& password)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000140 : thread_(thread),
141 factory_(factory),
Honghai Zhangd00c0572016-06-28 09:44:47 -0700142 type_(type),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000143 send_retransmit_count_attribute_(false),
144 network_(network),
145 ip_(ip),
146 min_port_(0),
147 max_port_(0),
148 component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
149 generation_(0),
150 ice_username_fragment_(username_fragment),
151 password_(password),
152 timeout_delay_(kPortTimeoutDelay),
153 enable_port_packets_(false),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000154 ice_role_(ICEROLE_UNKNOWN),
155 tiebreaker_(0),
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700156 shared_socket_(true) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000157 Construct();
158}
159
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000160Port::Port(rtc::Thread* thread,
161 const std::string& type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000162 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000163 rtc::Network* network,
164 const rtc::IPAddress& ip,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200165 uint16_t min_port,
166 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000167 const std::string& username_fragment,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000168 const std::string& password)
169 : thread_(thread),
170 factory_(factory),
171 type_(type),
172 send_retransmit_count_attribute_(false),
173 network_(network),
174 ip_(ip),
175 min_port_(min_port),
176 max_port_(max_port),
177 component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
178 generation_(0),
179 ice_username_fragment_(username_fragment),
180 password_(password),
181 timeout_delay_(kPortTimeoutDelay),
182 enable_port_packets_(false),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000183 ice_role_(ICEROLE_UNKNOWN),
184 tiebreaker_(0),
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700185 shared_socket_(false) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000186 ASSERT(factory_ != NULL);
187 Construct();
188}
189
190void Port::Construct() {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700191 // TODO(pthatcher): Remove this old behavior once we're sure no one
192 // relies on it. If the username_fragment and password are empty,
193 // we should just create one.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000194 if (ice_username_fragment_.empty()) {
195 ASSERT(password_.empty());
196 ice_username_fragment_ = rtc::CreateRandomString(ICE_UFRAG_LENGTH);
197 password_ = rtc::CreateRandomString(ICE_PWD_LENGTH);
198 }
Honghai Zhang351d77b2016-05-20 15:08:29 -0700199 network_->SignalTypeChanged.connect(this, &Port::OnNetworkTypeChanged);
200 network_cost_ = network_->GetCost();
honghaize1a0c942016-02-16 14:54:56 -0800201
Honghai Zhanga74363c2016-07-28 18:06:15 -0700202 thread_->PostDelayed(RTC_FROM_HERE, timeout_delay_, this,
203 MSG_DESTROY_IF_DEAD);
Honghai Zhang351d77b2016-05-20 15:08:29 -0700204 LOG_J(LS_INFO, this) << "Port created with network cost " << network_cost_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000205}
206
207Port::~Port() {
208 // Delete all of the remaining connections. We copy the list up front
209 // because each deletion will cause it to be modified.
210
211 std::vector<Connection*> list;
212
213 AddressMap::iterator iter = connections_.begin();
214 while (iter != connections_.end()) {
215 list.push_back(iter->second);
216 ++iter;
217 }
218
Peter Boström0c4e06b2015-10-07 12:23:21 +0200219 for (uint32_t i = 0; i < list.size(); i++)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000220 delete list[i];
221}
222
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700223void Port::SetIceParameters(int component,
224 const std::string& username_fragment,
225 const std::string& password) {
226 component_ = component;
227 ice_username_fragment_ = username_fragment;
228 password_ = password;
229 for (Candidate& c : candidates_) {
230 c.set_component(component);
231 c.set_username(username_fragment);
232 c.set_password(password);
233 }
234}
235
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000236Connection* Port::GetConnection(const rtc::SocketAddress& remote_addr) {
237 AddressMap::const_iterator iter = connections_.find(remote_addr);
238 if (iter != connections_.end())
239 return iter->second;
240 else
241 return NULL;
242}
243
244void Port::AddAddress(const rtc::SocketAddress& address,
245 const rtc::SocketAddress& base_address,
246 const rtc::SocketAddress& related_address,
247 const std::string& protocol,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700248 const std::string& relay_protocol,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000249 const std::string& tcptype,
250 const std::string& type,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200251 uint32_t type_preference,
252 uint32_t relay_preference,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000253 bool final) {
254 if (protocol == TCP_PROTOCOL_NAME && type == LOCAL_PORT_TYPE) {
255 ASSERT(!tcptype.empty());
256 }
257
honghaiza0c44ea2016-03-23 16:07:48 -0700258 std::string foundation =
259 ComputeFoundation(type, protocol, relay_protocol, base_address);
260 Candidate c(component_, protocol, address, 0U, username_fragment(), password_,
261 type, generation_, foundation, network_->id(), network_cost_);
262 c.set_priority(
263 c.GetPriority(type_preference, network_->preference(), relay_preference));
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700264 c.set_relay_protocol(relay_protocol);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000265 c.set_tcptype(tcptype);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000266 c.set_network_name(network_->name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +0000267 c.set_network_type(network_->type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000268 c.set_related_address(related_address);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000269 candidates_.push_back(c);
270 SignalCandidateReady(this, c);
271
272 if (final) {
273 SignalPortComplete(this);
274 }
275}
276
honghaiz36f50e82016-06-01 15:57:03 -0700277void Port::AddOrReplaceConnection(Connection* conn) {
278 auto ret = connections_.insert(
279 std::make_pair(conn->remote_candidate().address(), conn));
280 // If there is a different connection on the same remote address, replace
281 // it with the new one and destroy the old one.
282 if (ret.second == false && ret.first->second != conn) {
283 LOG_J(LS_WARNING, this)
284 << "A new connection was created on an existing remote address. "
285 << "New remote candidate: " << conn->remote_candidate().ToString();
286 ret.first->second->SignalDestroyed.disconnect(this);
287 ret.first->second->Destroy();
288 ret.first->second = conn;
289 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000290 conn->SignalDestroyed.connect(this, &Port::OnConnectionDestroyed);
291 SignalConnectionCreated(this, conn);
292}
293
294void Port::OnReadPacket(
295 const char* data, size_t size, const rtc::SocketAddress& addr,
296 ProtocolType proto) {
297 // If the user has enabled port packets, just hand this over.
298 if (enable_port_packets_) {
299 SignalReadPacket(this, data, size, addr);
300 return;
301 }
302
303 // If this is an authenticated STUN request, then signal unknown address and
304 // send back a proper binding response.
kwiberg3ec46792016-04-27 07:22:53 -0700305 std::unique_ptr<IceMessage> msg;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000306 std::string remote_username;
kwiberg6baec032016-03-15 11:09:39 -0700307 if (!GetStunMessage(data, size, addr, &msg, &remote_username)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000308 LOG_J(LS_ERROR, this) << "Received non-STUN packet from unknown address ("
309 << addr.ToSensitiveString() << ")";
310 } else if (!msg) {
311 // STUN message handled already
312 } else if (msg->type() == STUN_BINDING_REQUEST) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700313 LOG(LS_INFO) << "Received STUN ping "
314 << " id=" << rtc::hex_encode(msg->transaction_id())
315 << " from unknown address " << addr.ToSensitiveString();
316
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000317 // Check for role conflicts.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700318 if (!MaybeIceRoleConflict(addr, msg.get(), remote_username)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000319 LOG(LS_INFO) << "Received conflicting role from the peer.";
320 return;
321 }
322
323 SignalUnknownAddress(this, addr, proto, msg.get(), remote_username, false);
324 } else {
325 // NOTE(tschmelcher): STUN_BINDING_RESPONSE is benign. It occurs if we
326 // pruned a connection for this port while it had STUN requests in flight,
327 // because we then get back responses for them, which this code correctly
328 // does not handle.
329 if (msg->type() != STUN_BINDING_RESPONSE) {
330 LOG_J(LS_ERROR, this) << "Received unexpected STUN message type ("
331 << msg->type() << ") from unknown address ("
332 << addr.ToSensitiveString() << ")";
333 }
334 }
335}
336
337void Port::OnReadyToSend() {
338 AddressMap::iterator iter = connections_.begin();
339 for (; iter != connections_.end(); ++iter) {
340 iter->second->OnReadyToSend();
341 }
342}
343
344size_t Port::AddPrflxCandidate(const Candidate& local) {
345 candidates_.push_back(local);
346 return (candidates_.size() - 1);
347}
348
kwiberg6baec032016-03-15 11:09:39 -0700349bool Port::GetStunMessage(const char* data,
350 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000351 const rtc::SocketAddress& addr,
kwiberg3ec46792016-04-27 07:22:53 -0700352 std::unique_ptr<IceMessage>* out_msg,
kwiberg6baec032016-03-15 11:09:39 -0700353 std::string* out_username) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000354 // NOTE: This could clearly be optimized to avoid allocating any memory.
355 // However, at the data rates we'll be looking at on the client side,
356 // this probably isn't worth worrying about.
357 ASSERT(out_msg != NULL);
358 ASSERT(out_username != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000359 out_username->clear();
360
361 // Don't bother parsing the packet if we can tell it's not STUN.
362 // In ICE mode, all STUN packets will have a valid fingerprint.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700363 if (!StunMessage::ValidateFingerprint(data, size)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000364 return false;
365 }
366
367 // Parse the request message. If the packet is not a complete and correct
368 // STUN message, then ignore it.
kwiberg3ec46792016-04-27 07:22:53 -0700369 std::unique_ptr<IceMessage> stun_msg(new IceMessage());
jbauchf1f87202016-03-30 06:43:37 -0700370 rtc::ByteBufferReader buf(data, size);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000371 if (!stun_msg->Read(&buf) || (buf.Length() > 0)) {
372 return false;
373 }
374
375 if (stun_msg->type() == STUN_BINDING_REQUEST) {
376 // Check for the presence of USERNAME and MESSAGE-INTEGRITY (if ICE) first.
377 // If not present, fail with a 400 Bad Request.
378 if (!stun_msg->GetByteString(STUN_ATTR_USERNAME) ||
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700379 !stun_msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000380 LOG_J(LS_ERROR, this) << "Received STUN request without username/M-I "
381 << "from " << addr.ToSensitiveString();
382 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_BAD_REQUEST,
383 STUN_ERROR_REASON_BAD_REQUEST);
384 return true;
385 }
386
387 // If the username is bad or unknown, fail with a 401 Unauthorized.
388 std::string local_ufrag;
389 std::string remote_ufrag;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700390 if (!ParseStunUsername(stun_msg.get(), &local_ufrag, &remote_ufrag) ||
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000391 local_ufrag != username_fragment()) {
392 LOG_J(LS_ERROR, this) << "Received STUN request with bad local username "
393 << local_ufrag << " from "
394 << addr.ToSensitiveString();
395 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
396 STUN_ERROR_REASON_UNAUTHORIZED);
397 return true;
398 }
399
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000400 // If ICE, and the MESSAGE-INTEGRITY is bad, fail with a 401 Unauthorized
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700401 if (!stun_msg->ValidateMessageIntegrity(data, size, password_)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000402 LOG_J(LS_ERROR, this) << "Received STUN request with bad M-I "
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +0000403 << "from " << addr.ToSensitiveString()
404 << ", password_=" << password_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000405 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
406 STUN_ERROR_REASON_UNAUTHORIZED);
407 return true;
408 }
409 out_username->assign(remote_ufrag);
410 } else if ((stun_msg->type() == STUN_BINDING_RESPONSE) ||
411 (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE)) {
412 if (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE) {
413 if (const StunErrorCodeAttribute* error_code = stun_msg->GetErrorCode()) {
414 LOG_J(LS_ERROR, this) << "Received STUN binding error:"
415 << " class=" << error_code->eclass()
416 << " number=" << error_code->number()
417 << " reason='" << error_code->reason() << "'"
418 << " from " << addr.ToSensitiveString();
419 // Return message to allow error-specific processing
420 } else {
421 LOG_J(LS_ERROR, this) << "Received STUN binding error without a error "
422 << "code from " << addr.ToSensitiveString();
423 return true;
424 }
425 }
426 // NOTE: Username should not be used in verifying response messages.
427 out_username->clear();
428 } else if (stun_msg->type() == STUN_BINDING_INDICATION) {
429 LOG_J(LS_VERBOSE, this) << "Received STUN binding indication:"
430 << " from " << addr.ToSensitiveString();
431 out_username->clear();
432 // No stun attributes will be verified, if it's stun indication message.
433 // Returning from end of the this method.
434 } else {
435 LOG_J(LS_ERROR, this) << "Received STUN packet with invalid type ("
436 << stun_msg->type() << ") from "
437 << addr.ToSensitiveString();
438 return true;
439 }
440
441 // Return the STUN message found.
kwiberg6baec032016-03-15 11:09:39 -0700442 *out_msg = std::move(stun_msg);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000443 return true;
444}
445
446bool Port::IsCompatibleAddress(const rtc::SocketAddress& addr) {
447 int family = ip().family();
448 // We use single-stack sockets, so families must match.
449 if (addr.family() != family) {
450 return false;
451 }
452 // Link-local IPv6 ports can only connect to other link-local IPv6 ports.
Peter Thatcherb8b01432015-07-07 16:45:53 -0700453 if (family == AF_INET6 &&
454 (IPIsLinkLocal(ip()) != IPIsLinkLocal(addr.ipaddr()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000455 return false;
456 }
457 return true;
458}
459
460bool Port::ParseStunUsername(const StunMessage* stun_msg,
461 std::string* local_ufrag,
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700462 std::string* remote_ufrag) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000463 // The packet must include a username that either begins or ends with our
464 // fragment. It should begin with our fragment if it is a request and it
465 // should end with our fragment if it is a response.
466 local_ufrag->clear();
467 remote_ufrag->clear();
468 const StunByteStringAttribute* username_attr =
469 stun_msg->GetByteString(STUN_ATTR_USERNAME);
470 if (username_attr == NULL)
471 return false;
472
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700473 // RFRAG:LFRAG
474 const std::string username = username_attr->GetString();
475 size_t colon_pos = username.find(":");
476 if (colon_pos == std::string::npos) {
477 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000478 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000479
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700480 *local_ufrag = username.substr(0, colon_pos);
481 *remote_ufrag = username.substr(colon_pos + 1, username.size());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000482 return true;
483}
484
485bool Port::MaybeIceRoleConflict(
486 const rtc::SocketAddress& addr, IceMessage* stun_msg,
487 const std::string& remote_ufrag) {
488 // Validate ICE_CONTROLLING or ICE_CONTROLLED attributes.
489 bool ret = true;
490 IceRole remote_ice_role = ICEROLE_UNKNOWN;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200491 uint64_t remote_tiebreaker = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000492 const StunUInt64Attribute* stun_attr =
493 stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
494 if (stun_attr) {
495 remote_ice_role = ICEROLE_CONTROLLING;
496 remote_tiebreaker = stun_attr->value();
497 }
498
499 // If |remote_ufrag| is same as port local username fragment and
500 // tie breaker value received in the ping message matches port
501 // tiebreaker value this must be a loopback call.
502 // We will treat this as valid scenario.
503 if (remote_ice_role == ICEROLE_CONTROLLING &&
504 username_fragment() == remote_ufrag &&
505 remote_tiebreaker == IceTiebreaker()) {
506 return true;
507 }
508
509 stun_attr = stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
510 if (stun_attr) {
511 remote_ice_role = ICEROLE_CONTROLLED;
512 remote_tiebreaker = stun_attr->value();
513 }
514
515 switch (ice_role_) {
516 case ICEROLE_CONTROLLING:
517 if (ICEROLE_CONTROLLING == remote_ice_role) {
518 if (remote_tiebreaker >= tiebreaker_) {
519 SignalRoleConflict(this);
520 } else {
521 // Send Role Conflict (487) error response.
522 SendBindingErrorResponse(stun_msg, addr,
523 STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
524 ret = false;
525 }
526 }
527 break;
528 case ICEROLE_CONTROLLED:
529 if (ICEROLE_CONTROLLED == remote_ice_role) {
530 if (remote_tiebreaker < tiebreaker_) {
531 SignalRoleConflict(this);
532 } else {
533 // Send Role Conflict (487) error response.
534 SendBindingErrorResponse(stun_msg, addr,
535 STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
536 ret = false;
537 }
538 }
539 break;
540 default:
541 ASSERT(false);
542 }
543 return ret;
544}
545
546void Port::CreateStunUsername(const std::string& remote_username,
547 std::string* stun_username_attr_str) const {
548 stun_username_attr_str->clear();
549 *stun_username_attr_str = remote_username;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700550 stun_username_attr_str->append(":");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000551 stun_username_attr_str->append(username_fragment());
552}
553
554void Port::SendBindingResponse(StunMessage* request,
555 const rtc::SocketAddress& addr) {
556 ASSERT(request->type() == STUN_BINDING_REQUEST);
557
558 // Retrieve the username from the request.
559 const StunByteStringAttribute* username_attr =
560 request->GetByteString(STUN_ATTR_USERNAME);
561 ASSERT(username_attr != NULL);
562 if (username_attr == NULL) {
563 // No valid username, skip the response.
564 return;
565 }
566
567 // Fill in the response message.
568 StunMessage response;
569 response.SetType(STUN_BINDING_RESPONSE);
570 response.SetTransactionID(request->transaction_id());
571 const StunUInt32Attribute* retransmit_attr =
572 request->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
573 if (retransmit_attr) {
574 // Inherit the incoming retransmit value in the response so the other side
575 // can see our view of lost pings.
576 response.AddAttribute(new StunUInt32Attribute(
577 STUN_ATTR_RETRANSMIT_COUNT, retransmit_attr->value()));
578
579 if (retransmit_attr->value() > CONNECTION_WRITE_CONNECT_FAILURES) {
580 LOG_J(LS_INFO, this)
581 << "Received a remote ping with high retransmit count: "
582 << retransmit_attr->value();
583 }
584 }
585
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700586 response.AddAttribute(
587 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, addr));
588 response.AddMessageIntegrity(password_);
589 response.AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000590
591 // Send the response message.
jbauchf1f87202016-03-30 06:43:37 -0700592 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000593 response.Write(&buf);
594 rtc::PacketOptions options(DefaultDscpValue());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700595 auto err = SendTo(buf.Data(), buf.Length(), addr, options, false);
596 if (err < 0) {
597 LOG_J(LS_ERROR, this)
598 << "Failed to send STUN ping response"
599 << ", to=" << addr.ToSensitiveString()
600 << ", err=" << err
601 << ", id=" << rtc::hex_encode(response.transaction_id());
602 } else {
603 // Log at LS_INFO if we send a stun ping response on an unwritable
604 // connection.
honghaiz9b5ee9c2015-11-11 13:19:17 -0800605 Connection* conn = GetConnection(addr);
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700606 rtc::LoggingSeverity sev = (conn && !conn->writable()) ?
607 rtc::LS_INFO : rtc::LS_VERBOSE;
608 LOG_JV(sev, this)
609 << "Sent STUN ping response"
610 << ", to=" << addr.ToSensitiveString()
611 << ", id=" << rtc::hex_encode(response.transaction_id());
zhihuang5ecf16c2016-06-01 17:09:15 -0700612
613 conn->stats_.sent_ping_responses++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000614 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000615}
616
617void Port::SendBindingErrorResponse(StunMessage* request,
618 const rtc::SocketAddress& addr,
619 int error_code, const std::string& reason) {
620 ASSERT(request->type() == STUN_BINDING_REQUEST);
621
622 // Fill in the response message.
623 StunMessage response;
624 response.SetType(STUN_BINDING_ERROR_RESPONSE);
625 response.SetTransactionID(request->transaction_id());
626
627 // When doing GICE, we need to write out the error code incorrectly to
628 // maintain backwards compatiblility.
629 StunErrorCodeAttribute* error_attr = StunAttribute::CreateErrorCode();
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700630 error_attr->SetCode(error_code);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000631 error_attr->SetReason(reason);
632 response.AddAttribute(error_attr);
633
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700634 // Per Section 10.1.2, certain error cases don't get a MESSAGE-INTEGRITY,
635 // because we don't have enough information to determine the shared secret.
636 if (error_code != STUN_ERROR_BAD_REQUEST &&
637 error_code != STUN_ERROR_UNAUTHORIZED)
638 response.AddMessageIntegrity(password_);
639 response.AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000640
641 // Send the response message.
jbauchf1f87202016-03-30 06:43:37 -0700642 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000643 response.Write(&buf);
644 rtc::PacketOptions options(DefaultDscpValue());
645 SendTo(buf.Data(), buf.Length(), addr, options, false);
646 LOG_J(LS_INFO, this) << "Sending STUN binding error: reason=" << reason
647 << " to " << addr.ToSensitiveString();
648}
649
Honghai Zhanga74363c2016-07-28 18:06:15 -0700650void Port::KeepAliveUntilPruned() {
651 // If it is pruned, we won't bring it up again.
652 if (state_ == State::INIT) {
653 state_ = State::KEEP_ALIVE_UNTIL_PRUNED;
654 }
655}
656
657void Port::Prune() {
658 state_ = State::PRUNED;
659 thread_->Post(RTC_FROM_HERE, this, MSG_DESTROY_IF_DEAD);
660}
661
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000662void Port::OnMessage(rtc::Message *pmsg) {
Honghai Zhanga74363c2016-07-28 18:06:15 -0700663 ASSERT(pmsg->message_id == MSG_DESTROY_IF_DEAD);
664 bool dead =
665 (state_ == State::INIT || state_ == State::PRUNED) &&
666 connections_.empty() &&
667 rtc::TimeMillis() - last_time_all_connections_removed_ >= timeout_delay_;
668 if (dead) {
honghaizd0b31432015-09-30 12:42:17 -0700669 Destroy();
670 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000671}
672
Honghai Zhang351d77b2016-05-20 15:08:29 -0700673void Port::OnNetworkTypeChanged(const rtc::Network* network) {
674 ASSERT(network == network_);
675
676 UpdateNetworkCost();
677}
678
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000679std::string Port::ToString() const {
680 std::stringstream ss;
honghaize3c6c822016-02-17 13:00:28 -0800681 ss << "Port[" << std::hex << this << std::dec << ":" << content_name_ << ":"
682 << component_ << ":" << generation_ << ":" << type_ << ":"
683 << network_->ToString() << "]";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000684 return ss.str();
685}
686
Honghai Zhang351d77b2016-05-20 15:08:29 -0700687// TODO(honghaiz): Make the network cost configurable from user setting.
688void Port::UpdateNetworkCost() {
689 uint16_t new_cost = network_->GetCost();
690 if (network_cost_ == new_cost) {
691 return;
692 }
693 LOG(LS_INFO) << "Network cost changed from " << network_cost_
694 << " to " << new_cost
695 << ". Number of candidates created: " << candidates_.size()
696 << ". Number of connections created: " << connections_.size();
697 network_cost_ = new_cost;
698 for (cricket::Candidate& candidate : candidates_) {
699 candidate.set_network_cost(network_cost_);
700 }
701 // Network cost change will affect the connection selection criteria.
702 // Signal the connection state change on each connection to force a
703 // re-sort in P2PTransportChannel.
704 for (auto kv : connections_) {
705 Connection* conn = kv.second;
706 conn->SignalStateChange(conn);
707 }
708}
709
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000710void Port::EnablePortPackets() {
711 enable_port_packets_ = true;
712}
713
714void Port::OnConnectionDestroyed(Connection* conn) {
715 AddressMap::iterator iter =
716 connections_.find(conn->remote_candidate().address());
717 ASSERT(iter != connections_.end());
718 connections_.erase(iter);
honghaiz36f50e82016-06-01 15:57:03 -0700719 HandleConnectionDestroyed(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000720
Honghai Zhanga74363c2016-07-28 18:06:15 -0700721 // Ports time out after all connections fail if it is not marked as
722 // "keep alive until pruned."
honghaizd0b31432015-09-30 12:42:17 -0700723 // Note: If a new connection is added after this message is posted, but it
724 // fails and is removed before kPortTimeoutDelay, then this message will
Honghai Zhangb5db1ec2016-07-28 13:23:05 -0700725 // not cause the Port to be destroyed.
Honghai Zhanga74363c2016-07-28 18:06:15 -0700726 if (connections_.empty()) {
Honghai Zhangb5db1ec2016-07-28 13:23:05 -0700727 last_time_all_connections_removed_ = rtc::TimeMillis();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700728 thread_->PostDelayed(RTC_FROM_HERE, timeout_delay_, this,
729 MSG_DESTROY_IF_DEAD);
honghaizd0b31432015-09-30 12:42:17 -0700730 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000731}
732
733void Port::Destroy() {
734 ASSERT(connections_.empty());
735 LOG_J(LS_INFO, this) << "Port deleted";
736 SignalDestroyed(this);
737 delete this;
738}
739
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000740const std::string Port::username_fragment() const {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700741 return ice_username_fragment_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000742}
743
744// A ConnectionRequest is a simple STUN ping used to determine writability.
745class ConnectionRequest : public StunRequest {
746 public:
747 explicit ConnectionRequest(Connection* connection)
748 : StunRequest(new IceMessage()),
749 connection_(connection) {
750 }
751
752 virtual ~ConnectionRequest() {
753 }
754
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700755 void Prepare(StunMessage* request) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000756 request->SetType(STUN_BINDING_REQUEST);
757 std::string username;
758 connection_->port()->CreateStunUsername(
759 connection_->remote_candidate().username(), &username);
760 request->AddAttribute(
761 new StunByteStringAttribute(STUN_ATTR_USERNAME, username));
762
763 // connection_ already holds this ping, so subtract one from count.
764 if (connection_->port()->send_retransmit_count_attribute()) {
765 request->AddAttribute(new StunUInt32Attribute(
766 STUN_ATTR_RETRANSMIT_COUNT,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200767 static_cast<uint32_t>(connection_->pings_since_last_response_.size() -
768 1)));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000769 }
honghaiza0c44ea2016-03-23 16:07:48 -0700770 uint32_t network_info = connection_->port()->Network()->id();
771 network_info = (network_info << 16) | connection_->port()->network_cost();
772 request->AddAttribute(
773 new StunUInt32Attribute(STUN_ATTR_NETWORK_INFO, network_info));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000774
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700775 // Adding ICE_CONTROLLED or ICE_CONTROLLING attribute based on the role.
776 if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLING) {
777 request->AddAttribute(new StunUInt64Attribute(
778 STUN_ATTR_ICE_CONTROLLING, connection_->port()->IceTiebreaker()));
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700779 // We should have either USE_CANDIDATE attribute or ICE_NOMINATION
780 // attribute but not both. That was enforced in p2ptransportchannel.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700781 if (connection_->use_candidate_attr()) {
782 request->AddAttribute(new StunByteStringAttribute(
783 STUN_ATTR_USE_CANDIDATE));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000784 }
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700785 if (connection_->nomination() &&
786 connection_->nomination() != connection_->acked_nomination()) {
787 request->AddAttribute(new StunUInt32Attribute(
788 STUN_ATTR_NOMINATION, connection_->nomination()));
789 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700790 } else if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLED) {
791 request->AddAttribute(new StunUInt64Attribute(
792 STUN_ATTR_ICE_CONTROLLED, connection_->port()->IceTiebreaker()));
793 } else {
794 ASSERT(false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000795 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700796
797 // Adding PRIORITY Attribute.
798 // Changing the type preference to Peer Reflexive and local preference
799 // and component id information is unchanged from the original priority.
800 // priority = (2^24)*(type preference) +
801 // (2^8)*(local preference) +
802 // (2^0)*(256 - component ID)
Taylor Brandstetter62351c92016-08-11 16:05:07 -0700803 uint32_t type_preference =
804 (connection_->local_candidate().protocol() == TCP_PROTOCOL_NAME)
805 ? ICE_TYPE_PREFERENCE_PRFLX_TCP
806 : ICE_TYPE_PREFERENCE_PRFLX;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200807 uint32_t prflx_priority =
Taylor Brandstetter62351c92016-08-11 16:05:07 -0700808 type_preference << 24 |
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700809 (connection_->local_candidate().priority() & 0x00FFFFFF);
810 request->AddAttribute(
811 new StunUInt32Attribute(STUN_ATTR_PRIORITY, prflx_priority));
812
813 // Adding Message Integrity attribute.
814 request->AddMessageIntegrity(connection_->remote_candidate().password());
815 // Adding Fingerprint.
816 request->AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000817 }
818
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700819 void OnResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000820 connection_->OnConnectionRequestResponse(this, response);
821 }
822
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700823 void OnErrorResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000824 connection_->OnConnectionRequestErrorResponse(this, response);
825 }
826
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700827 void OnTimeout() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000828 connection_->OnConnectionRequestTimeout(this);
829 }
830
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700831 void OnSent() override {
832 connection_->OnConnectionRequestSent(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000833 // Each request is sent only once. After a single delay , the request will
834 // time out.
835 timeout_ = true;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700836 }
837
838 int resend_delay() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000839 return CONNECTION_RESPONSE_TIMEOUT;
840 }
841
842 private:
843 Connection* connection_;
844};
845
846//
847// Connection
848//
849
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000850Connection::Connection(Port* port,
851 size_t index,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000852 const Candidate& remote_candidate)
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000853 : port_(port),
854 local_candidate_index_(index),
855 remote_candidate_(remote_candidate),
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700856 recv_rate_tracker_(100, 10u),
857 send_rate_tracker_(100, 10u),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000858 write_state_(STATE_WRITE_INIT),
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700859 receiving_(false),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000860 connected_(true),
861 pruned_(false),
862 use_candidate_attr_(false),
863 remote_ice_mode_(ICEMODE_FULL),
864 requests_(port->thread()),
865 rtt_(DEFAULT_RTT),
866 last_ping_sent_(0),
867 last_ping_received_(0),
868 last_data_received_(0),
869 last_ping_response_received_(0),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000870 reported_(false),
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700871 state_(STATE_WAITING),
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700872 receiving_timeout_(WEAK_CONNECTION_RECEIVE_TIMEOUT),
nisse1bffc1d2016-05-02 08:18:55 -0700873 time_created_ms_(rtc::TimeMillis()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000874 // All of our connections start in WAITING state.
875 // TODO(mallinath) - Start connections from STATE_FROZEN.
876 // Wire up to send stun packets
877 requests_.SignalSendPacket.connect(this, &Connection::OnSendStunPacket);
878 LOG_J(LS_INFO, this) << "Connection created";
879}
880
881Connection::~Connection() {
882}
883
884const Candidate& Connection::local_candidate() const {
885 ASSERT(local_candidate_index_ < port_->Candidates().size());
886 return port_->Candidates()[local_candidate_index_];
887}
888
Honghai Zhangcc411c02016-03-29 17:27:21 -0700889const Candidate& Connection::remote_candidate() const {
890 return remote_candidate_;
891}
892
Peter Boström0c4e06b2015-10-07 12:23:21 +0200893uint64_t Connection::priority() const {
894 uint64_t priority = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000895 // RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs
896 // Let G be the priority for the candidate provided by the controlling
897 // agent. Let D be the priority for the candidate provided by the
898 // controlled agent.
899 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
900 IceRole role = port_->GetIceRole();
901 if (role != ICEROLE_UNKNOWN) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200902 uint32_t g = 0;
903 uint32_t d = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000904 if (role == ICEROLE_CONTROLLING) {
905 g = local_candidate().priority();
906 d = remote_candidate_.priority();
907 } else {
908 g = remote_candidate_.priority();
909 d = local_candidate().priority();
910 }
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000911 priority = std::min(g, d);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000912 priority = priority << 32;
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000913 priority += 2 * std::max(g, d) + (g > d ? 1 : 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000914 }
915 return priority;
916}
917
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000918void Connection::set_write_state(WriteState value) {
919 WriteState old_value = write_state_;
920 write_state_ = value;
921 if (value != old_value) {
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +0000922 LOG_J(LS_VERBOSE, this) << "set_write_state from: " << old_value << " to "
923 << value;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000924 SignalStateChange(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000925 }
926}
927
honghaiz9ad0db52016-07-14 19:30:28 -0700928void Connection::UpdateReceiving(int64_t now) {
honghaize58d73d2016-10-24 16:38:26 -0700929 bool receiving =
930 last_received() > 0 && now <= last_received() + receiving_timeout_;
honghaiz9ad0db52016-07-14 19:30:28 -0700931 if (receiving_ == receiving) {
932 return;
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700933 }
honghaiz9ad0db52016-07-14 19:30:28 -0700934 LOG_J(LS_VERBOSE, this) << "set_receiving to " << receiving;
935 receiving_ = receiving;
936 receiving_unchanged_since_ = now;
937 SignalStateChange(this);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700938}
939
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000940void Connection::set_state(State state) {
941 State old_state = state_;
942 state_ = state;
943 if (state != old_state) {
944 LOG_J(LS_VERBOSE, this) << "set_state";
945 }
946}
947
948void Connection::set_connected(bool value) {
949 bool old_value = connected_;
950 connected_ = value;
951 if (value != old_value) {
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700952 LOG_J(LS_VERBOSE, this) << "set_connected from: " << old_value << " to "
953 << value;
Taylor Brandstetterb825aee2016-06-29 13:07:16 -0700954 SignalStateChange(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000955 }
956}
957
958void Connection::set_use_candidate_attr(bool enable) {
959 use_candidate_attr_ = enable;
960}
961
962void Connection::OnSendStunPacket(const void* data, size_t size,
963 StunRequest* req) {
964 rtc::PacketOptions options(port_->DefaultDscpValue());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700965 auto err = port_->SendTo(
966 data, size, remote_candidate_.address(), options, false);
967 if (err < 0) {
968 LOG_J(LS_WARNING, this) << "Failed to send STUN ping "
969 << " err=" << err
970 << " id=" << rtc::hex_encode(req->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000971 }
972}
973
974void Connection::OnReadPacket(
975 const char* data, size_t size, const rtc::PacketTime& packet_time) {
kwiberg3ec46792016-04-27 07:22:53 -0700976 std::unique_ptr<IceMessage> msg;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000977 std::string remote_ufrag;
978 const rtc::SocketAddress& addr(remote_candidate_.address());
kwiberg6baec032016-03-15 11:09:39 -0700979 if (!port_->GetStunMessage(data, size, addr, &msg, &remote_ufrag)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000980 // The packet did not parse as a valid STUN message
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700981 // This is a data packet, pass it along.
nisse1bffc1d2016-05-02 08:18:55 -0700982 last_data_received_ = rtc::TimeMillis();
honghaiz9ad0db52016-07-14 19:30:28 -0700983 UpdateReceiving(last_data_received_);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700984 recv_rate_tracker_.AddSamples(size);
985 SignalReadPacket(this, data, size, packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000986
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700987 // If timed out sending writability checks, start up again
988 if (!pruned_ && (write_state_ == STATE_WRITE_TIMEOUT)) {
989 LOG(LS_WARNING) << "Received a data packet on a timed-out Connection. "
990 << "Resetting state to STATE_WRITE_INIT.";
991 set_write_state(STATE_WRITE_INIT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000992 }
993 } else if (!msg) {
994 // The packet was STUN, but failed a check and was handled internally.
995 } else {
996 // The packet is STUN and passed the Port checks.
997 // Perform our own checks to ensure this packet is valid.
honghaizd0b31432015-09-30 12:42:17 -0700998 // If this is a STUN request, then update the receiving bit and respond.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000999 // If this is a STUN response, then update the writable bit.
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001000 // Log at LS_INFO if we receive a ping on an unwritable connection.
1001 rtc::LoggingSeverity sev = (!writable() ? rtc::LS_INFO : rtc::LS_VERBOSE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001002 switch (msg->type()) {
1003 case STUN_BINDING_REQUEST:
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001004 LOG_JV(sev, this) << "Received STUN ping"
1005 << ", id=" << rtc::hex_encode(msg->transaction_id());
1006
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001007 if (remote_ufrag == remote_candidate_.username()) {
honghaiz9b5ee9c2015-11-11 13:19:17 -08001008 HandleBindingRequest(msg.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001009 } else {
1010 // The packet had the right local username, but the remote username
1011 // was not the right one for the remote address.
1012 LOG_J(LS_ERROR, this)
1013 << "Received STUN request with bad remote username "
1014 << remote_ufrag;
1015 port_->SendBindingErrorResponse(msg.get(), addr,
1016 STUN_ERROR_UNAUTHORIZED,
1017 STUN_ERROR_REASON_UNAUTHORIZED);
1018
1019 }
1020 break;
1021
1022 // Response from remote peer. Does it match request sent?
1023 // This doesn't just check, it makes callbacks if transaction
1024 // id's match.
1025 case STUN_BINDING_RESPONSE:
1026 case STUN_BINDING_ERROR_RESPONSE:
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001027 if (msg->ValidateMessageIntegrity(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001028 data, size, remote_candidate().password())) {
1029 requests_.CheckResponse(msg.get());
1030 }
1031 // Otherwise silently discard the response message.
1032 break;
1033
honghaizd0b31432015-09-30 12:42:17 -07001034 // Remote end point sent an STUN indication instead of regular binding
1035 // request. In this case |last_ping_received_| will be updated but no
1036 // response will be sent.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001037 case STUN_BINDING_INDICATION:
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001038 ReceivedPing();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001039 break;
1040
1041 default:
1042 ASSERT(false);
1043 break;
1044 }
1045 }
1046}
1047
honghaiz9b5ee9c2015-11-11 13:19:17 -08001048void Connection::HandleBindingRequest(IceMessage* msg) {
1049 // This connection should now be receiving.
1050 ReceivedPing();
1051
1052 const rtc::SocketAddress& remote_addr = remote_candidate_.address();
1053 const std::string& remote_ufrag = remote_candidate_.username();
1054 // Check for role conflicts.
1055 if (!port_->MaybeIceRoleConflict(remote_addr, msg, remote_ufrag)) {
1056 // Received conflicting role from the peer.
1057 LOG(LS_INFO) << "Received conflicting role from the peer.";
1058 return;
1059 }
1060
zhihuang5ecf16c2016-06-01 17:09:15 -07001061 stats_.recv_ping_requests++;
1062
honghaiz9b5ee9c2015-11-11 13:19:17 -08001063 // This is a validated stun request from remote peer.
1064 port_->SendBindingResponse(msg, remote_addr);
1065
1066 // If it timed out on writing check, start up again
1067 if (!pruned_ && write_state_ == STATE_WRITE_TIMEOUT) {
1068 set_write_state(STATE_WRITE_INIT);
1069 }
1070
1071 if (port_->GetIceRole() == ICEROLE_CONTROLLED) {
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001072 const StunUInt32Attribute* nomination_attr =
1073 msg->GetUInt32(STUN_ATTR_NOMINATION);
1074 uint32_t nomination = 0;
1075 if (nomination_attr) {
1076 nomination = nomination_attr->value();
1077 if (nomination == 0) {
1078 LOG(LS_ERROR) << "Invalid nomination: " << nomination;
1079 }
1080 } else {
1081 const StunByteStringAttribute* use_candidate_attr =
1082 msg->GetByteString(STUN_ATTR_USE_CANDIDATE);
1083 if (use_candidate_attr) {
1084 nomination = 1;
1085 }
1086 }
1087 // We don't un-nominate a connection, so we only keep a larger nomination.
1088 if (nomination > remote_nomination_) {
1089 set_remote_nomination(nomination);
honghaiz9b5ee9c2015-11-11 13:19:17 -08001090 SignalNominated(this);
1091 }
1092 }
Honghai Zhang351d77b2016-05-20 15:08:29 -07001093 // Set the remote cost if the network_info attribute is available.
1094 // Note: If packets are re-ordered, we may get incorrect network cost
1095 // temporarily, but it should get the correct value shortly after that.
1096 const StunUInt32Attribute* network_attr =
1097 msg->GetUInt32(STUN_ATTR_NETWORK_INFO);
1098 if (network_attr) {
1099 uint32_t network_info = network_attr->value();
1100 uint16_t network_cost = static_cast<uint16_t>(network_info);
1101 if (network_cost != remote_candidate_.network_cost()) {
1102 remote_candidate_.set_network_cost(network_cost);
1103 // Network cost change will affect the connection ranking, so signal
1104 // state change to force a re-sort in P2PTransportChannel.
1105 SignalStateChange(this);
1106 }
1107 }
honghaiz9b5ee9c2015-11-11 13:19:17 -08001108}
1109
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001110void Connection::OnReadyToSend() {
deadbeefdd7fb432016-09-30 15:16:48 -07001111 SignalReadyToSend(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001112}
1113
1114void Connection::Prune() {
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001115 if (!pruned_ || active()) {
Honghai Zhang1590c392016-05-24 13:15:02 -07001116 LOG_J(LS_INFO, this) << "Connection pruned";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001117 pruned_ = true;
1118 requests_.Clear();
1119 set_write_state(STATE_WRITE_TIMEOUT);
1120 }
1121}
1122
1123void Connection::Destroy() {
1124 LOG_J(LS_VERBOSE, this) << "Connection destroyed";
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001125 port_->thread()->Post(RTC_FROM_HERE, this, MSG_DELETE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001126}
1127
deadbeef376e1232015-11-25 09:00:08 -08001128void Connection::FailAndDestroy() {
1129 set_state(Connection::STATE_FAILED);
1130 Destroy();
1131}
1132
honghaiz079a7a12016-06-22 16:26:29 -07001133void Connection::FailAndPrune() {
1134 set_state(Connection::STATE_FAILED);
1135 Prune();
1136}
1137
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001138void Connection::PrintPingsSinceLastResponse(std::string* s, size_t max) {
1139 std::ostringstream oss;
1140 oss << std::boolalpha;
1141 if (pings_since_last_response_.size() > max) {
1142 for (size_t i = 0; i < max; i++) {
1143 const SentPing& ping = pings_since_last_response_[i];
1144 oss << rtc::hex_encode(ping.id) << " ";
1145 }
1146 oss << "... " << (pings_since_last_response_.size() - max) << " more";
1147 } else {
1148 for (const SentPing& ping : pings_since_last_response_) {
1149 oss << rtc::hex_encode(ping.id) << " ";
1150 }
1151 }
1152 *s = oss.str();
1153}
1154
honghaiz34b11eb2016-03-16 08:55:44 -07001155void Connection::UpdateState(int64_t now) {
1156 int rtt = ConservativeRTTEstimate(rtt_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001157
Peter Thatcherb2d26232015-05-15 11:25:14 -07001158 if (LOG_CHECK_LEVEL(LS_VERBOSE)) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001159 std::string pings;
1160 PrintPingsSinceLastResponse(&pings, 5);
1161 LOG_J(LS_VERBOSE, this) << "UpdateState()"
1162 << ", ms since last received response="
1163 << now - last_ping_response_received_
1164 << ", ms since last received data="
1165 << now - last_data_received_
1166 << ", rtt=" << rtt
1167 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001168 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001169
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001170 // Check the writable state. (The order of these checks is important.)
1171 //
1172 // Before becoming unwritable, we allow for a fixed number of pings to fail
1173 // (i.e., receive no response). We also have to give the response time to
1174 // get back, so we include a conservative estimate of this.
1175 //
1176 // Before timing out writability, we give a fixed amount of time. This is to
1177 // allow for changes in network conditions.
1178
1179 if ((write_state_ == STATE_WRITABLE) &&
1180 TooManyFailures(pings_since_last_response_,
1181 CONNECTION_WRITE_CONNECT_FAILURES,
1182 rtt,
1183 now) &&
1184 TooLongWithoutResponse(pings_since_last_response_,
1185 CONNECTION_WRITE_CONNECT_TIMEOUT,
1186 now)) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001187 uint32_t max_pings = CONNECTION_WRITE_CONNECT_FAILURES;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001188 LOG_J(LS_INFO, this) << "Unwritable after " << max_pings
1189 << " ping failures and "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001190 << now - pings_since_last_response_[0].sent_time
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001191 << " ms without a response,"
1192 << " ms since last received ping="
1193 << now - last_ping_received_
1194 << " ms since last received data="
1195 << now - last_data_received_
1196 << " rtt=" << rtt;
1197 set_write_state(STATE_WRITE_UNRELIABLE);
1198 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001199 if ((write_state_ == STATE_WRITE_UNRELIABLE ||
1200 write_state_ == STATE_WRITE_INIT) &&
1201 TooLongWithoutResponse(pings_since_last_response_,
1202 CONNECTION_WRITE_TIMEOUT,
1203 now)) {
1204 LOG_J(LS_INFO, this) << "Timed out after "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001205 << now - pings_since_last_response_[0].sent_time
1206 << " ms without a response"
1207 << ", rtt=" << rtt;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001208 set_write_state(STATE_WRITE_TIMEOUT);
1209 }
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001210
honghaiz9ad0db52016-07-14 19:30:28 -07001211 // Update the receiving state.
1212 UpdateReceiving(now);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001213 if (dead(now)) {
1214 Destroy();
1215 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001216}
1217
honghaiz34b11eb2016-03-16 08:55:44 -07001218void Connection::Ping(int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001219 last_ping_sent_ = now;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001220 ConnectionRequest *req = new ConnectionRequest(this);
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001221 pings_since_last_response_.push_back(SentPing(req->id(), now, nomination_));
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001222 LOG_J(LS_VERBOSE, this) << "Sending STUN ping "
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001223 << ", id=" << rtc::hex_encode(req->id())
1224 << ", nomination=" << nomination_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001225 requests_.Send(req);
1226 state_ = STATE_INPROGRESS;
honghaiz524ecc22016-05-25 12:48:31 -07001227 num_pings_sent_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001228}
1229
1230void Connection::ReceivedPing() {
nisse1bffc1d2016-05-02 08:18:55 -07001231 last_ping_received_ = rtc::TimeMillis();
honghaiz9ad0db52016-07-14 19:30:28 -07001232 UpdateReceiving(last_ping_received_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001233}
1234
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001235void Connection::ReceivedPingResponse(int rtt, const std::string& request_id) {
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001236 // We've already validated that this is a STUN binding response with
1237 // the correct local and remote username for this connection.
1238 // So if we're not already, become writable. We may be bringing a pruned
1239 // connection back to life, but if we don't really want it, we can always
1240 // prune it again.
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001241 auto iter = std::find_if(
1242 pings_since_last_response_.begin(), pings_since_last_response_.end(),
1243 [request_id](const SentPing& ping) { return ping.id == request_id; });
1244 if (iter != pings_since_last_response_.end() &&
1245 iter->nomination > acked_nomination_) {
1246 acked_nomination_ = iter->nomination;
1247 }
1248
1249 pings_since_last_response_.clear();
honghaiz9ad0db52016-07-14 19:30:28 -07001250 last_ping_response_received_ = rtc::TimeMillis();
1251 UpdateReceiving(last_ping_response_received_);
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001252 set_write_state(STATE_WRITABLE);
1253 set_state(STATE_SUCCEEDED);
zhihuang435264a2016-06-21 11:28:38 -07001254 rtt_samples_++;
1255 rtt_ = (RTT_RATIO * rtt_ + rtt) / (RTT_RATIO + 1);
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001256}
1257
honghaiz34b11eb2016-03-16 08:55:44 -07001258bool Connection::dead(int64_t now) const {
honghaiz37389b42016-01-04 21:57:33 -08001259 if (last_received() > 0) {
1260 // If it has ever received anything, we keep it alive until it hasn't
1261 // received anything for DEAD_CONNECTION_RECEIVE_TIMEOUT. This covers the
1262 // normal case of a successfully used connection that stops working. This
1263 // also allows a remote peer to continue pinging over a locally inactive
1264 // (pruned) connection.
1265 return (now > (last_received() + DEAD_CONNECTION_RECEIVE_TIMEOUT));
1266 }
1267
1268 if (active()) {
1269 // If it has never received anything, keep it alive as long as it is
1270 // actively pinging and not pruned. Otherwise, the connection might be
1271 // deleted before it has a chance to ping. This is the normal case for a
1272 // new connection that is pinging but hasn't received anything yet.
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001273 return false;
1274 }
1275
honghaiz37389b42016-01-04 21:57:33 -08001276 // If it has never received anything and is not actively pinging (pruned), we
1277 // keep it around for at least MIN_CONNECTION_LIFETIME to prevent connections
1278 // from being pruned too quickly during a network change event when two
1279 // networks would be up simultaneously but only for a brief period.
1280 return now > (time_created_ms_ + MIN_CONNECTION_LIFETIME);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001281}
1282
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001283bool Connection::stable(int64_t now) const {
zhihuang435264a2016-06-21 11:28:38 -07001284 // A connection is stable if it's RTT has converged and it isn't missing any
1285 // responses. We should send pings at a higher rate until the RTT converges
1286 // and whenever a ping response is missing (so that we can detect
1287 // unwritability faster)
1288 return rtt_converged() && !missing_responses(now);
1289}
1290
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +00001291std::string Connection::ToDebugId() const {
1292 std::stringstream ss;
1293 ss << std::hex << this;
1294 return ss.str();
1295}
1296
honghaize1a0c942016-02-16 14:54:56 -08001297uint32_t Connection::ComputeNetworkCost() const {
1298 // TODO(honghaiz): Will add rtt as part of the network cost.
Honghai Zhang351d77b2016-05-20 15:08:29 -07001299 return port()->network_cost() + remote_candidate_.network_cost();
honghaize1a0c942016-02-16 14:54:56 -08001300}
1301
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001302std::string Connection::ToString() const {
1303 const char CONNECT_STATE_ABBREV[2] = {
1304 '-', // not connected (false)
1305 'C', // connected (true)
1306 };
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001307 const char RECEIVE_STATE_ABBREV[2] = {
1308 '-', // not receiving (false)
1309 'R', // receiving (true)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001310 };
1311 const char WRITE_STATE_ABBREV[4] = {
1312 'W', // STATE_WRITABLE
1313 'w', // STATE_WRITE_UNRELIABLE
1314 '-', // STATE_WRITE_INIT
1315 'x', // STATE_WRITE_TIMEOUT
1316 };
1317 const std::string ICESTATE[4] = {
1318 "W", // STATE_WAITING
1319 "I", // STATE_INPROGRESS
1320 "S", // STATE_SUCCEEDED
1321 "F" // STATE_FAILED
1322 };
1323 const Candidate& local = local_candidate();
1324 const Candidate& remote = remote_candidate();
1325 std::stringstream ss;
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001326 ss << "Conn[" << ToDebugId() << ":" << port_->content_name() << ":"
1327 << local.id() << ":" << local.component() << ":" << local.generation()
1328 << ":" << local.type() << ":" << local.protocol() << ":"
1329 << local.address().ToSensitiveString() << "->" << remote.id() << ":"
1330 << remote.component() << ":" << remote.priority() << ":" << remote.type()
1331 << ":" << remote.protocol() << ":" << remote.address().ToSensitiveString()
1332 << "|" << CONNECT_STATE_ABBREV[connected()]
1333 << RECEIVE_STATE_ABBREV[receiving()] << WRITE_STATE_ABBREV[write_state()]
1334 << ICESTATE[state()] << "|" << remote_nomination() << "|" << nomination()
1335 << "|" << priority() << "|";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001336 if (rtt_ < DEFAULT_RTT) {
1337 ss << rtt_ << "]";
1338 } else {
1339 ss << "-]";
1340 }
1341 return ss.str();
1342}
1343
1344std::string Connection::ToSensitiveString() const {
1345 return ToString();
1346}
1347
1348void Connection::OnConnectionRequestResponse(ConnectionRequest* request,
1349 StunMessage* response) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001350 // Log at LS_INFO if we receive a ping response on an unwritable
1351 // connection.
1352 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1353
honghaiz34b11eb2016-03-16 08:55:44 -07001354 int rtt = request->Elapsed();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001355
Peter Thatcherb2d26232015-05-15 11:25:14 -07001356 if (LOG_CHECK_LEVEL_V(sev)) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001357 std::string pings;
1358 PrintPingsSinceLastResponse(&pings, 5);
1359 LOG_JV(sev, this) << "Received STUN ping response"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001360 << ", id=" << rtc::hex_encode(request->id())
1361 << ", code=0" // Makes logging easier to parse.
1362 << ", rtt=" << rtt
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001363 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001364 }
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001365 ReceivedPingResponse(rtt, request->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001366
zhihuang5ecf16c2016-06-01 17:09:15 -07001367 stats_.recv_ping_responses++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001368
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001369 MaybeUpdateLocalCandidate(request, response);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001370}
1371
1372void Connection::OnConnectionRequestErrorResponse(ConnectionRequest* request,
1373 StunMessage* response) {
1374 const StunErrorCodeAttribute* error_attr = response->GetErrorCode();
1375 int error_code = STUN_ERROR_GLOBAL_FAILURE;
1376 if (error_attr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001377 error_code = error_attr->code();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001378 }
1379
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001380 LOG_J(LS_INFO, this) << "Received STUN error response"
1381 << " id=" << rtc::hex_encode(request->id())
1382 << " code=" << error_code
1383 << " rtt=" << request->Elapsed();
1384
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001385 if (error_code == STUN_ERROR_UNKNOWN_ATTRIBUTE ||
1386 error_code == STUN_ERROR_SERVER_ERROR ||
1387 error_code == STUN_ERROR_UNAUTHORIZED) {
1388 // Recoverable error, retry
1389 } else if (error_code == STUN_ERROR_STALE_CREDENTIALS) {
1390 // Race failure, retry
1391 } else if (error_code == STUN_ERROR_ROLE_CONFLICT) {
1392 HandleRoleConflictFromPeer();
1393 } else {
1394 // This is not a valid connection.
1395 LOG_J(LS_ERROR, this) << "Received STUN error response, code="
1396 << error_code << "; killing connection";
deadbeef376e1232015-11-25 09:00:08 -08001397 FailAndDestroy();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001398 }
1399}
1400
1401void Connection::OnConnectionRequestTimeout(ConnectionRequest* request) {
1402 // Log at LS_INFO if we miss a ping on a writable connection.
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001403 rtc::LoggingSeverity sev = writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1404 LOG_JV(sev, this) << "Timing-out STUN ping "
1405 << rtc::hex_encode(request->id())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001406 << " after " << request->Elapsed() << " ms";
1407}
1408
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001409void Connection::OnConnectionRequestSent(ConnectionRequest* request) {
1410 // Log at LS_INFO if we send a ping on an unwritable connection.
1411 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1412 LOG_JV(sev, this) << "Sent STUN ping"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001413 << ", id=" << rtc::hex_encode(request->id())
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001414 << ", use_candidate=" << use_candidate_attr()
1415 << ", nomination=" << nomination();
zhihuang5ecf16c2016-06-01 17:09:15 -07001416 stats_.sent_ping_requests_total++;
1417 if (stats_.recv_ping_responses == 0) {
1418 stats_.sent_ping_requests_before_first_response++;
1419 }
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001420}
1421
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001422void Connection::HandleRoleConflictFromPeer() {
1423 port_->SignalRoleConflict(port_);
1424}
1425
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001426void Connection::MaybeSetRemoteIceParametersAndGeneration(
1427 const IceParameters& ice_params,
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001428 int generation) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001429 if (remote_candidate_.username() == ice_params.ufrag &&
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001430 remote_candidate_.password().empty()) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001431 remote_candidate_.set_password(ice_params.pwd);
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001432 }
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001433 // TODO(deadbeef): A value of '0' for the generation is used for both
1434 // generation 0 and "generation unknown". It should be changed to an
1435 // rtc::Optional to fix this.
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001436 if (remote_candidate_.username() == ice_params.ufrag &&
1437 remote_candidate_.password() == ice_params.pwd &&
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001438 remote_candidate_.generation() == 0) {
1439 remote_candidate_.set_generation(generation);
1440 }
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001441}
1442
1443void Connection::MaybeUpdatePeerReflexiveCandidate(
1444 const Candidate& new_candidate) {
1445 if (remote_candidate_.type() == PRFLX_PORT_TYPE &&
1446 new_candidate.type() != PRFLX_PORT_TYPE &&
1447 remote_candidate_.protocol() == new_candidate.protocol() &&
1448 remote_candidate_.address() == new_candidate.address() &&
1449 remote_candidate_.username() == new_candidate.username() &&
1450 remote_candidate_.password() == new_candidate.password() &&
1451 remote_candidate_.generation() == new_candidate.generation()) {
1452 remote_candidate_ = new_candidate;
1453 }
1454}
1455
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001456void Connection::OnMessage(rtc::Message *pmsg) {
1457 ASSERT(pmsg->message_id == MSG_DELETE);
honghaiz18f9da02016-06-01 23:53:01 -07001458 LOG(LS_INFO) << "Connection deleted with number of pings sent: "
1459 << num_pings_sent_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001460 SignalDestroyed(this);
1461 delete this;
1462}
1463
honghaiz34b11eb2016-03-16 08:55:44 -07001464int64_t Connection::last_received() const {
Peter Thatcher54360512015-07-08 11:08:35 -07001465 return std::max(last_data_received_,
1466 std::max(last_ping_received_, last_ping_response_received_));
1467}
1468
zhihuang5ecf16c2016-06-01 17:09:15 -07001469ConnectionInfo Connection::stats() {
1470 stats_.recv_bytes_second = round(recv_rate_tracker_.ComputeRate());
1471 stats_.recv_total_bytes = recv_rate_tracker_.TotalSampleCount();
1472 stats_.sent_bytes_second = round(send_rate_tracker_.ComputeRate());
1473 stats_.sent_total_bytes = send_rate_tracker_.TotalSampleCount();
1474 return stats_;
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001475}
1476
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001477void Connection::MaybeUpdateLocalCandidate(ConnectionRequest* request,
1478 StunMessage* response) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001479 // RFC 5245
1480 // The agent checks the mapped address from the STUN response. If the
1481 // transport address does not match any of the local candidates that the
1482 // agent knows about, the mapped address represents a new candidate -- a
1483 // peer reflexive candidate.
1484 const StunAddressAttribute* addr =
1485 response->GetAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
1486 if (!addr) {
1487 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1488 << "No MAPPED-ADDRESS or XOR-MAPPED-ADDRESS found in the "
1489 << "stun response message";
1490 return;
1491 }
1492
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001493 for (size_t i = 0; i < port_->Candidates().size(); ++i) {
1494 if (port_->Candidates()[i].address() == addr->GetAddress()) {
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001495 if (local_candidate_index_ != i) {
1496 LOG_J(LS_INFO, this) << "Updating local candidate type to srflx.";
1497 local_candidate_index_ = i;
1498 // SignalStateChange to force a re-sort in P2PTransportChannel as this
1499 // Connection's local candidate has changed.
1500 SignalStateChange(this);
1501 }
1502 return;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001503 }
1504 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001505
1506 // RFC 5245
1507 // Its priority is set equal to the value of the PRIORITY attribute
1508 // in the Binding request.
1509 const StunUInt32Attribute* priority_attr =
1510 request->msg()->GetUInt32(STUN_ATTR_PRIORITY);
1511 if (!priority_attr) {
1512 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1513 << "No STUN_ATTR_PRIORITY found in the "
1514 << "stun response message";
1515 return;
1516 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001517 const uint32_t priority = priority_attr->value();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001518 std::string id = rtc::CreateRandomString(8);
1519
1520 Candidate new_local_candidate;
1521 new_local_candidate.set_id(id);
1522 new_local_candidate.set_component(local_candidate().component());
1523 new_local_candidate.set_type(PRFLX_PORT_TYPE);
1524 new_local_candidate.set_protocol(local_candidate().protocol());
1525 new_local_candidate.set_address(addr->GetAddress());
1526 new_local_candidate.set_priority(priority);
1527 new_local_candidate.set_username(local_candidate().username());
1528 new_local_candidate.set_password(local_candidate().password());
1529 new_local_candidate.set_network_name(local_candidate().network_name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001530 new_local_candidate.set_network_type(local_candidate().network_type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001531 new_local_candidate.set_related_address(local_candidate().address());
Taylor Brandstetterf7c15a92016-06-22 13:13:55 -07001532 new_local_candidate.set_generation(local_candidate().generation());
Honghai Zhang80f1db92016-01-27 11:54:45 -08001533 new_local_candidate.set_foundation(ComputeFoundation(
1534 PRFLX_PORT_TYPE, local_candidate().protocol(),
1535 local_candidate().relay_protocol(), local_candidate().address()));
honghaiza0c44ea2016-03-23 16:07:48 -07001536 new_local_candidate.set_network_id(local_candidate().network_id());
1537 new_local_candidate.set_network_cost(local_candidate().network_cost());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001538
1539 // Change the local candidate of this Connection to the new prflx candidate.
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001540 LOG_J(LS_INFO, this) << "Updating local candidate type to prflx.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001541 local_candidate_index_ = port_->AddPrflxCandidate(new_local_candidate);
1542
1543 // SignalStateChange to force a re-sort in P2PTransportChannel as this
1544 // Connection's local candidate has changed.
1545 SignalStateChange(this);
1546}
1547
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001548bool Connection::rtt_converged() const {
zhihuang435264a2016-06-21 11:28:38 -07001549 return rtt_samples_ > (RTT_RATIO + 1);
1550}
1551
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001552bool Connection::missing_responses(int64_t now) const {
zhihuang435264a2016-06-21 11:28:38 -07001553 if (pings_since_last_response_.empty()) {
1554 return false;
1555 }
1556
1557 int64_t waiting = now - pings_since_last_response_[0].sent_time;
1558 return waiting > 2 * rtt();
1559}
1560
deadbeef376e1232015-11-25 09:00:08 -08001561ProxyConnection::ProxyConnection(Port* port,
1562 size_t index,
1563 const Candidate& remote_candidate)
1564 : Connection(port, index, remote_candidate) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001565
1566int ProxyConnection::Send(const void* data, size_t size,
1567 const rtc::PacketOptions& options) {
zhihuang5ecf16c2016-06-01 17:09:15 -07001568 stats_.sent_total_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001569 int sent = port_->SendTo(data, size, remote_candidate_.address(),
1570 options, true);
1571 if (sent <= 0) {
1572 ASSERT(sent < 0);
1573 error_ = port_->GetError();
zhihuang5ecf16c2016-06-01 17:09:15 -07001574 stats_.sent_discarded_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001575 } else {
Tim Psiaki63046262015-09-14 10:38:08 -07001576 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001577 }
1578 return sent;
1579}
1580
1581} // namespace cricket