blob: 16a80194358a93d47bb7466a7f57eb57058d4af4 [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "webrtc/p2p/base/port.h"
12
13#include <algorithm>
14#include <vector>
15
16#include "webrtc/p2p/base/common.h"
17#include "webrtc/p2p/base/portallocator.h"
18#include "webrtc/base/base64.h"
nissec80e7412017-01-11 05:56:46 -080019#include "webrtc/base/checks.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000020#include "webrtc/base/crc32.h"
21#include "webrtc/base/helpers.h"
22#include "webrtc/base/logging.h"
23#include "webrtc/base/messagedigest.h"
honghaize3c6c822016-02-17 13:00:28 -080024#include "webrtc/base/network.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000025#include "webrtc/base/stringencode.h"
26#include "webrtc/base/stringutils.h"
27
28namespace {
29
30// Determines whether we have seen at least the given maximum number of
31// pings fail to have a response.
32inline bool TooManyFailures(
Peter Thatcher1cf6f812015-05-15 10:40:45 -070033 const std::vector<cricket::Connection::SentPing>& pings_since_last_response,
Peter Boström0c4e06b2015-10-07 12:23:21 +020034 uint32_t maximum_failures,
honghaiz34b11eb2016-03-16 08:55:44 -070035 int rtt_estimate,
36 int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000037 // If we haven't sent that many pings, then we can't have failed that many.
38 if (pings_since_last_response.size() < maximum_failures)
39 return false;
40
41 // Check if the window in which we would expect a response to the ping has
42 // already elapsed.
honghaiz34b11eb2016-03-16 08:55:44 -070043 int64_t expected_response_time =
Peter Thatcher1cf6f812015-05-15 10:40:45 -070044 pings_since_last_response[maximum_failures - 1].sent_time + rtt_estimate;
45 return now > expected_response_time;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000046}
47
48// Determines whether we have gone too long without seeing any response.
49inline bool TooLongWithoutResponse(
Peter Thatcher1cf6f812015-05-15 10:40:45 -070050 const std::vector<cricket::Connection::SentPing>& pings_since_last_response,
honghaiz34b11eb2016-03-16 08:55:44 -070051 int64_t maximum_time,
52 int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000053 if (pings_since_last_response.size() == 0)
54 return false;
55
Peter Thatcher1cf6f812015-05-15 10:40:45 -070056 auto first = pings_since_last_response[0];
57 return now > (first.sent_time + maximum_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000058}
59
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000060// We will restrict RTT estimates (when used for determining state) to be
61// within a reasonable range.
honghaiz34b11eb2016-03-16 08:55:44 -070062const int MINIMUM_RTT = 100; // 0.1 seconds
skvlad51072462017-02-02 11:50:14 -080063const int MAXIMUM_RTT = 60000; // 60 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000064
65// When we don't have any RTT data, we have to pick something reasonable. We
66// use a large value just in case the connection is really slow.
skvlad51072462017-02-02 11:50:14 -080067const int DEFAULT_RTT = 3000; // 3 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000068
69// Computes our estimate of the RTT given the current estimate.
honghaiz34b11eb2016-03-16 08:55:44 -070070inline int ConservativeRTTEstimate(int rtt) {
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000071 return std::max(MINIMUM_RTT, std::min(MAXIMUM_RTT, 2 * rtt));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000072}
73
74// Weighting of the old rtt value to new data.
75const int RTT_RATIO = 3; // 3 : 1
76
77// The delay before we begin checking if this port is useless.
78const int kPortTimeoutDelay = 30 * 1000; // 30 seconds
Honghai Zhang351d77b2016-05-20 15:08:29 -070079} // namespace
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000080
81namespace cricket {
82
83// TODO(ronghuawu): Use "host", "srflx", "prflx" and "relay". But this requires
84// the signaling part be updated correspondingly as well.
85const char LOCAL_PORT_TYPE[] = "local";
86const char STUN_PORT_TYPE[] = "stun";
87const char PRFLX_PORT_TYPE[] = "prflx";
88const char RELAY_PORT_TYPE[] = "relay";
89
90const char UDP_PROTOCOL_NAME[] = "udp";
91const char TCP_PROTOCOL_NAME[] = "tcp";
92const char SSLTCP_PROTOCOL_NAME[] = "ssltcp";
hnsl277b2502016-12-13 05:17:23 -080093const char TLS_PROTOCOL_NAME[] = "tls";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000094
hnsl277b2502016-12-13 05:17:23 -080095static const char* const PROTO_NAMES[] = {UDP_PROTOCOL_NAME, TCP_PROTOCOL_NAME,
96 SSLTCP_PROTOCOL_NAME,
97 TLS_PROTOCOL_NAME};
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000098
99const char* ProtoToString(ProtocolType proto) {
100 return PROTO_NAMES[proto];
101}
102
103bool StringToProto(const char* value, ProtocolType* proto) {
104 for (size_t i = 0; i <= PROTO_LAST; ++i) {
105 if (_stricmp(PROTO_NAMES[i], value) == 0) {
106 *proto = static_cast<ProtocolType>(i);
107 return true;
108 }
109 }
110 return false;
111}
112
113// RFC 6544, TCP candidate encoding rules.
114const int DISCARD_PORT = 9;
115const char TCPTYPE_ACTIVE_STR[] = "active";
116const char TCPTYPE_PASSIVE_STR[] = "passive";
117const char TCPTYPE_SIMOPEN_STR[] = "so";
118
119// Foundation: An arbitrary string that is the same for two candidates
120// that have the same type, base IP address, protocol (UDP, TCP,
121// etc.), and STUN or TURN server. If any of these are different,
122// then the foundation will be different. Two candidate pairs with
123// the same foundation pairs are likely to have similar network
124// characteristics. Foundations are used in the frozen algorithm.
Honghai Zhang80f1db92016-01-27 11:54:45 -0800125static std::string ComputeFoundation(const std::string& type,
126 const std::string& protocol,
127 const std::string& relay_protocol,
128 const rtc::SocketAddress& base_address) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000129 std::ostringstream ost;
Honghai Zhang80f1db92016-01-27 11:54:45 -0800130 ost << type << base_address.ipaddr().ToString() << protocol << relay_protocol;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200131 return rtc::ToString<uint32_t>(rtc::ComputeCrc32(ost.str()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000132}
133
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000134Port::Port(rtc::Thread* thread,
Honghai Zhangd00c0572016-06-28 09:44:47 -0700135 const std::string& type,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000136 rtc::PacketSocketFactory* factory,
137 rtc::Network* network,
138 const rtc::IPAddress& ip,
139 const std::string& username_fragment,
140 const std::string& password)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000141 : thread_(thread),
142 factory_(factory),
Honghai Zhangd00c0572016-06-28 09:44:47 -0700143 type_(type),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000144 send_retransmit_count_attribute_(false),
145 network_(network),
146 ip_(ip),
147 min_port_(0),
148 max_port_(0),
149 component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
150 generation_(0),
151 ice_username_fragment_(username_fragment),
152 password_(password),
153 timeout_delay_(kPortTimeoutDelay),
154 enable_port_packets_(false),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000155 ice_role_(ICEROLE_UNKNOWN),
156 tiebreaker_(0),
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700157 shared_socket_(true) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000158 Construct();
159}
160
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000161Port::Port(rtc::Thread* thread,
162 const std::string& type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000163 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000164 rtc::Network* network,
165 const rtc::IPAddress& ip,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200166 uint16_t min_port,
167 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000168 const std::string& username_fragment,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000169 const std::string& password)
170 : thread_(thread),
171 factory_(factory),
172 type_(type),
173 send_retransmit_count_attribute_(false),
174 network_(network),
175 ip_(ip),
176 min_port_(min_port),
177 max_port_(max_port),
178 component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
179 generation_(0),
180 ice_username_fragment_(username_fragment),
181 password_(password),
182 timeout_delay_(kPortTimeoutDelay),
183 enable_port_packets_(false),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000184 ice_role_(ICEROLE_UNKNOWN),
185 tiebreaker_(0),
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700186 shared_socket_(false) {
nisseede5da42017-01-12 05:15:36 -0800187 RTC_DCHECK(factory_ != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000188 Construct();
189}
190
191void Port::Construct() {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700192 // TODO(pthatcher): Remove this old behavior once we're sure no one
193 // relies on it. If the username_fragment and password are empty,
194 // we should just create one.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000195 if (ice_username_fragment_.empty()) {
nisseede5da42017-01-12 05:15:36 -0800196 RTC_DCHECK(password_.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000197 ice_username_fragment_ = rtc::CreateRandomString(ICE_UFRAG_LENGTH);
198 password_ = rtc::CreateRandomString(ICE_PWD_LENGTH);
199 }
Honghai Zhang351d77b2016-05-20 15:08:29 -0700200 network_->SignalTypeChanged.connect(this, &Port::OnNetworkTypeChanged);
201 network_cost_ = network_->GetCost();
honghaize1a0c942016-02-16 14:54:56 -0800202
Honghai Zhanga74363c2016-07-28 18:06:15 -0700203 thread_->PostDelayed(RTC_FROM_HERE, timeout_delay_, this,
204 MSG_DESTROY_IF_DEAD);
Honghai Zhang351d77b2016-05-20 15:08:29 -0700205 LOG_J(LS_INFO, this) << "Port created with network cost " << network_cost_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000206}
207
208Port::~Port() {
209 // Delete all of the remaining connections. We copy the list up front
210 // because each deletion will cause it to be modified.
211
212 std::vector<Connection*> list;
213
214 AddressMap::iterator iter = connections_.begin();
215 while (iter != connections_.end()) {
216 list.push_back(iter->second);
217 ++iter;
218 }
219
Peter Boström0c4e06b2015-10-07 12:23:21 +0200220 for (uint32_t i = 0; i < list.size(); i++)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000221 delete list[i];
222}
223
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700224void Port::SetIceParameters(int component,
225 const std::string& username_fragment,
226 const std::string& password) {
227 component_ = component;
228 ice_username_fragment_ = username_fragment;
229 password_ = password;
230 for (Candidate& c : candidates_) {
231 c.set_component(component);
232 c.set_username(username_fragment);
233 c.set_password(password);
234 }
235}
236
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000237Connection* Port::GetConnection(const rtc::SocketAddress& remote_addr) {
238 AddressMap::const_iterator iter = connections_.find(remote_addr);
239 if (iter != connections_.end())
240 return iter->second;
241 else
242 return NULL;
243}
244
245void Port::AddAddress(const rtc::SocketAddress& address,
246 const rtc::SocketAddress& base_address,
247 const rtc::SocketAddress& related_address,
248 const std::string& protocol,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700249 const std::string& relay_protocol,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000250 const std::string& tcptype,
251 const std::string& type,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200252 uint32_t type_preference,
253 uint32_t relay_preference,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000254 bool final) {
255 if (protocol == TCP_PROTOCOL_NAME && type == LOCAL_PORT_TYPE) {
nisseede5da42017-01-12 05:15:36 -0800256 RTC_DCHECK(!tcptype.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000257 }
258
honghaiza0c44ea2016-03-23 16:07:48 -0700259 std::string foundation =
260 ComputeFoundation(type, protocol, relay_protocol, base_address);
261 Candidate c(component_, protocol, address, 0U, username_fragment(), password_,
262 type, generation_, foundation, network_->id(), network_cost_);
263 c.set_priority(
264 c.GetPriority(type_preference, network_->preference(), relay_preference));
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700265 c.set_relay_protocol(relay_protocol);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000266 c.set_tcptype(tcptype);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000267 c.set_network_name(network_->name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +0000268 c.set_network_type(network_->type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000269 c.set_related_address(related_address);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000270 candidates_.push_back(c);
271 SignalCandidateReady(this, c);
272
273 if (final) {
274 SignalPortComplete(this);
275 }
276}
277
honghaiz36f50e82016-06-01 15:57:03 -0700278void Port::AddOrReplaceConnection(Connection* conn) {
279 auto ret = connections_.insert(
280 std::make_pair(conn->remote_candidate().address(), conn));
281 // If there is a different connection on the same remote address, replace
282 // it with the new one and destroy the old one.
283 if (ret.second == false && ret.first->second != conn) {
284 LOG_J(LS_WARNING, this)
285 << "A new connection was created on an existing remote address. "
286 << "New remote candidate: " << conn->remote_candidate().ToString();
287 ret.first->second->SignalDestroyed.disconnect(this);
288 ret.first->second->Destroy();
289 ret.first->second = conn;
290 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000291 conn->SignalDestroyed.connect(this, &Port::OnConnectionDestroyed);
292 SignalConnectionCreated(this, conn);
293}
294
295void Port::OnReadPacket(
296 const char* data, size_t size, const rtc::SocketAddress& addr,
297 ProtocolType proto) {
298 // If the user has enabled port packets, just hand this over.
299 if (enable_port_packets_) {
300 SignalReadPacket(this, data, size, addr);
301 return;
302 }
303
304 // If this is an authenticated STUN request, then signal unknown address and
305 // send back a proper binding response.
kwiberg3ec46792016-04-27 07:22:53 -0700306 std::unique_ptr<IceMessage> msg;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000307 std::string remote_username;
kwiberg6baec032016-03-15 11:09:39 -0700308 if (!GetStunMessage(data, size, addr, &msg, &remote_username)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000309 LOG_J(LS_ERROR, this) << "Received non-STUN packet from unknown address ("
310 << addr.ToSensitiveString() << ")";
311 } else if (!msg) {
312 // STUN message handled already
313 } else if (msg->type() == STUN_BINDING_REQUEST) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700314 LOG(LS_INFO) << "Received STUN ping "
315 << " id=" << rtc::hex_encode(msg->transaction_id())
316 << " from unknown address " << addr.ToSensitiveString();
317
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000318 // Check for role conflicts.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700319 if (!MaybeIceRoleConflict(addr, msg.get(), remote_username)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000320 LOG(LS_INFO) << "Received conflicting role from the peer.";
321 return;
322 }
323
324 SignalUnknownAddress(this, addr, proto, msg.get(), remote_username, false);
325 } else {
326 // NOTE(tschmelcher): STUN_BINDING_RESPONSE is benign. It occurs if we
327 // pruned a connection for this port while it had STUN requests in flight,
328 // because we then get back responses for them, which this code correctly
329 // does not handle.
330 if (msg->type() != STUN_BINDING_RESPONSE) {
331 LOG_J(LS_ERROR, this) << "Received unexpected STUN message type ("
332 << msg->type() << ") from unknown address ("
333 << addr.ToSensitiveString() << ")";
334 }
335 }
336}
337
338void Port::OnReadyToSend() {
339 AddressMap::iterator iter = connections_.begin();
340 for (; iter != connections_.end(); ++iter) {
341 iter->second->OnReadyToSend();
342 }
343}
344
345size_t Port::AddPrflxCandidate(const Candidate& local) {
346 candidates_.push_back(local);
347 return (candidates_.size() - 1);
348}
349
kwiberg6baec032016-03-15 11:09:39 -0700350bool Port::GetStunMessage(const char* data,
351 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000352 const rtc::SocketAddress& addr,
kwiberg3ec46792016-04-27 07:22:53 -0700353 std::unique_ptr<IceMessage>* out_msg,
kwiberg6baec032016-03-15 11:09:39 -0700354 std::string* out_username) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000355 // NOTE: This could clearly be optimized to avoid allocating any memory.
356 // However, at the data rates we'll be looking at on the client side,
357 // this probably isn't worth worrying about.
nisseede5da42017-01-12 05:15:36 -0800358 RTC_DCHECK(out_msg != NULL);
359 RTC_DCHECK(out_username != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000360 out_username->clear();
361
362 // Don't bother parsing the packet if we can tell it's not STUN.
363 // In ICE mode, all STUN packets will have a valid fingerprint.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700364 if (!StunMessage::ValidateFingerprint(data, size)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000365 return false;
366 }
367
368 // Parse the request message. If the packet is not a complete and correct
369 // STUN message, then ignore it.
kwiberg3ec46792016-04-27 07:22:53 -0700370 std::unique_ptr<IceMessage> stun_msg(new IceMessage());
jbauchf1f87202016-03-30 06:43:37 -0700371 rtc::ByteBufferReader buf(data, size);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000372 if (!stun_msg->Read(&buf) || (buf.Length() > 0)) {
373 return false;
374 }
375
376 if (stun_msg->type() == STUN_BINDING_REQUEST) {
377 // Check for the presence of USERNAME and MESSAGE-INTEGRITY (if ICE) first.
378 // If not present, fail with a 400 Bad Request.
379 if (!stun_msg->GetByteString(STUN_ATTR_USERNAME) ||
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700380 !stun_msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000381 LOG_J(LS_ERROR, this) << "Received STUN request without username/M-I "
382 << "from " << addr.ToSensitiveString();
383 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_BAD_REQUEST,
384 STUN_ERROR_REASON_BAD_REQUEST);
385 return true;
386 }
387
388 // If the username is bad or unknown, fail with a 401 Unauthorized.
389 std::string local_ufrag;
390 std::string remote_ufrag;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700391 if (!ParseStunUsername(stun_msg.get(), &local_ufrag, &remote_ufrag) ||
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000392 local_ufrag != username_fragment()) {
393 LOG_J(LS_ERROR, this) << "Received STUN request with bad local username "
394 << local_ufrag << " from "
395 << addr.ToSensitiveString();
396 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
397 STUN_ERROR_REASON_UNAUTHORIZED);
398 return true;
399 }
400
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000401 // If ICE, and the MESSAGE-INTEGRITY is bad, fail with a 401 Unauthorized
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700402 if (!stun_msg->ValidateMessageIntegrity(data, size, password_)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000403 LOG_J(LS_ERROR, this) << "Received STUN request with bad M-I "
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +0000404 << "from " << addr.ToSensitiveString()
405 << ", password_=" << password_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000406 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
407 STUN_ERROR_REASON_UNAUTHORIZED);
408 return true;
409 }
410 out_username->assign(remote_ufrag);
411 } else if ((stun_msg->type() == STUN_BINDING_RESPONSE) ||
412 (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE)) {
413 if (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE) {
414 if (const StunErrorCodeAttribute* error_code = stun_msg->GetErrorCode()) {
415 LOG_J(LS_ERROR, this) << "Received STUN binding error:"
416 << " class=" << error_code->eclass()
417 << " number=" << error_code->number()
418 << " reason='" << error_code->reason() << "'"
419 << " from " << addr.ToSensitiveString();
420 // Return message to allow error-specific processing
421 } else {
422 LOG_J(LS_ERROR, this) << "Received STUN binding error without a error "
423 << "code from " << addr.ToSensitiveString();
424 return true;
425 }
426 }
427 // NOTE: Username should not be used in verifying response messages.
428 out_username->clear();
429 } else if (stun_msg->type() == STUN_BINDING_INDICATION) {
430 LOG_J(LS_VERBOSE, this) << "Received STUN binding indication:"
431 << " from " << addr.ToSensitiveString();
432 out_username->clear();
433 // No stun attributes will be verified, if it's stun indication message.
434 // Returning from end of the this method.
435 } else {
436 LOG_J(LS_ERROR, this) << "Received STUN packet with invalid type ("
437 << stun_msg->type() << ") from "
438 << addr.ToSensitiveString();
439 return true;
440 }
441
442 // Return the STUN message found.
kwiberg6baec032016-03-15 11:09:39 -0700443 *out_msg = std::move(stun_msg);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000444 return true;
445}
446
447bool Port::IsCompatibleAddress(const rtc::SocketAddress& addr) {
448 int family = ip().family();
449 // We use single-stack sockets, so families must match.
450 if (addr.family() != family) {
451 return false;
452 }
453 // Link-local IPv6 ports can only connect to other link-local IPv6 ports.
Peter Thatcherb8b01432015-07-07 16:45:53 -0700454 if (family == AF_INET6 &&
455 (IPIsLinkLocal(ip()) != IPIsLinkLocal(addr.ipaddr()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000456 return false;
457 }
458 return true;
459}
460
461bool Port::ParseStunUsername(const StunMessage* stun_msg,
462 std::string* local_ufrag,
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700463 std::string* remote_ufrag) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000464 // The packet must include a username that either begins or ends with our
465 // fragment. It should begin with our fragment if it is a request and it
466 // should end with our fragment if it is a response.
467 local_ufrag->clear();
468 remote_ufrag->clear();
469 const StunByteStringAttribute* username_attr =
470 stun_msg->GetByteString(STUN_ATTR_USERNAME);
471 if (username_attr == NULL)
472 return false;
473
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700474 // RFRAG:LFRAG
475 const std::string username = username_attr->GetString();
476 size_t colon_pos = username.find(":");
477 if (colon_pos == std::string::npos) {
478 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000479 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000480
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700481 *local_ufrag = username.substr(0, colon_pos);
482 *remote_ufrag = username.substr(colon_pos + 1, username.size());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000483 return true;
484}
485
486bool Port::MaybeIceRoleConflict(
487 const rtc::SocketAddress& addr, IceMessage* stun_msg,
488 const std::string& remote_ufrag) {
489 // Validate ICE_CONTROLLING or ICE_CONTROLLED attributes.
490 bool ret = true;
491 IceRole remote_ice_role = ICEROLE_UNKNOWN;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200492 uint64_t remote_tiebreaker = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000493 const StunUInt64Attribute* stun_attr =
494 stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
495 if (stun_attr) {
496 remote_ice_role = ICEROLE_CONTROLLING;
497 remote_tiebreaker = stun_attr->value();
498 }
499
500 // If |remote_ufrag| is same as port local username fragment and
501 // tie breaker value received in the ping message matches port
502 // tiebreaker value this must be a loopback call.
503 // We will treat this as valid scenario.
504 if (remote_ice_role == ICEROLE_CONTROLLING &&
505 username_fragment() == remote_ufrag &&
506 remote_tiebreaker == IceTiebreaker()) {
507 return true;
508 }
509
510 stun_attr = stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
511 if (stun_attr) {
512 remote_ice_role = ICEROLE_CONTROLLED;
513 remote_tiebreaker = stun_attr->value();
514 }
515
516 switch (ice_role_) {
517 case ICEROLE_CONTROLLING:
518 if (ICEROLE_CONTROLLING == remote_ice_role) {
519 if (remote_tiebreaker >= tiebreaker_) {
520 SignalRoleConflict(this);
521 } else {
522 // Send Role Conflict (487) error response.
523 SendBindingErrorResponse(stun_msg, addr,
524 STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
525 ret = false;
526 }
527 }
528 break;
529 case ICEROLE_CONTROLLED:
530 if (ICEROLE_CONTROLLED == remote_ice_role) {
531 if (remote_tiebreaker < tiebreaker_) {
532 SignalRoleConflict(this);
533 } else {
534 // Send Role Conflict (487) error response.
535 SendBindingErrorResponse(stun_msg, addr,
536 STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
537 ret = false;
538 }
539 }
540 break;
541 default:
nissec80e7412017-01-11 05:56:46 -0800542 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000543 }
544 return ret;
545}
546
547void Port::CreateStunUsername(const std::string& remote_username,
548 std::string* stun_username_attr_str) const {
549 stun_username_attr_str->clear();
550 *stun_username_attr_str = remote_username;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700551 stun_username_attr_str->append(":");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000552 stun_username_attr_str->append(username_fragment());
553}
554
555void Port::SendBindingResponse(StunMessage* request,
556 const rtc::SocketAddress& addr) {
nisseede5da42017-01-12 05:15:36 -0800557 RTC_DCHECK(request->type() == STUN_BINDING_REQUEST);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000558
559 // Retrieve the username from the request.
560 const StunByteStringAttribute* username_attr =
561 request->GetByteString(STUN_ATTR_USERNAME);
nisseede5da42017-01-12 05:15:36 -0800562 RTC_DCHECK(username_attr != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000563 if (username_attr == NULL) {
564 // No valid username, skip the response.
565 return;
566 }
567
568 // Fill in the response message.
569 StunMessage response;
570 response.SetType(STUN_BINDING_RESPONSE);
571 response.SetTransactionID(request->transaction_id());
572 const StunUInt32Attribute* retransmit_attr =
573 request->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
574 if (retransmit_attr) {
575 // Inherit the incoming retransmit value in the response so the other side
576 // can see our view of lost pings.
577 response.AddAttribute(new StunUInt32Attribute(
578 STUN_ATTR_RETRANSMIT_COUNT, retransmit_attr->value()));
579
580 if (retransmit_attr->value() > CONNECTION_WRITE_CONNECT_FAILURES) {
581 LOG_J(LS_INFO, this)
582 << "Received a remote ping with high retransmit count: "
583 << retransmit_attr->value();
584 }
585 }
586
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700587 response.AddAttribute(
588 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, addr));
589 response.AddMessageIntegrity(password_);
590 response.AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000591
592 // Send the response message.
jbauchf1f87202016-03-30 06:43:37 -0700593 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000594 response.Write(&buf);
595 rtc::PacketOptions options(DefaultDscpValue());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700596 auto err = SendTo(buf.Data(), buf.Length(), addr, options, false);
597 if (err < 0) {
598 LOG_J(LS_ERROR, this)
599 << "Failed to send STUN ping response"
600 << ", to=" << addr.ToSensitiveString()
601 << ", err=" << err
602 << ", id=" << rtc::hex_encode(response.transaction_id());
603 } else {
604 // Log at LS_INFO if we send a stun ping response on an unwritable
605 // connection.
honghaiz9b5ee9c2015-11-11 13:19:17 -0800606 Connection* conn = GetConnection(addr);
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700607 rtc::LoggingSeverity sev = (conn && !conn->writable()) ?
608 rtc::LS_INFO : rtc::LS_VERBOSE;
609 LOG_JV(sev, this)
610 << "Sent STUN ping response"
611 << ", to=" << addr.ToSensitiveString()
612 << ", id=" << rtc::hex_encode(response.transaction_id());
zhihuang5ecf16c2016-06-01 17:09:15 -0700613
614 conn->stats_.sent_ping_responses++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000615 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000616}
617
618void Port::SendBindingErrorResponse(StunMessage* request,
619 const rtc::SocketAddress& addr,
620 int error_code, const std::string& reason) {
nisseede5da42017-01-12 05:15:36 -0800621 RTC_DCHECK(request->type() == STUN_BINDING_REQUEST);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000622
623 // Fill in the response message.
624 StunMessage response;
625 response.SetType(STUN_BINDING_ERROR_RESPONSE);
626 response.SetTransactionID(request->transaction_id());
627
628 // When doing GICE, we need to write out the error code incorrectly to
629 // maintain backwards compatiblility.
630 StunErrorCodeAttribute* error_attr = StunAttribute::CreateErrorCode();
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700631 error_attr->SetCode(error_code);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000632 error_attr->SetReason(reason);
633 response.AddAttribute(error_attr);
634
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700635 // Per Section 10.1.2, certain error cases don't get a MESSAGE-INTEGRITY,
636 // because we don't have enough information to determine the shared secret.
637 if (error_code != STUN_ERROR_BAD_REQUEST &&
638 error_code != STUN_ERROR_UNAUTHORIZED)
639 response.AddMessageIntegrity(password_);
640 response.AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000641
642 // Send the response message.
jbauchf1f87202016-03-30 06:43:37 -0700643 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000644 response.Write(&buf);
645 rtc::PacketOptions options(DefaultDscpValue());
646 SendTo(buf.Data(), buf.Length(), addr, options, false);
647 LOG_J(LS_INFO, this) << "Sending STUN binding error: reason=" << reason
648 << " to " << addr.ToSensitiveString();
649}
650
Honghai Zhanga74363c2016-07-28 18:06:15 -0700651void Port::KeepAliveUntilPruned() {
652 // If it is pruned, we won't bring it up again.
653 if (state_ == State::INIT) {
654 state_ = State::KEEP_ALIVE_UNTIL_PRUNED;
655 }
656}
657
658void Port::Prune() {
659 state_ = State::PRUNED;
660 thread_->Post(RTC_FROM_HERE, this, MSG_DESTROY_IF_DEAD);
661}
662
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000663void Port::OnMessage(rtc::Message *pmsg) {
nisseede5da42017-01-12 05:15:36 -0800664 RTC_DCHECK(pmsg->message_id == MSG_DESTROY_IF_DEAD);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700665 bool dead =
666 (state_ == State::INIT || state_ == State::PRUNED) &&
667 connections_.empty() &&
668 rtc::TimeMillis() - last_time_all_connections_removed_ >= timeout_delay_;
669 if (dead) {
honghaizd0b31432015-09-30 12:42:17 -0700670 Destroy();
671 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000672}
673
Honghai Zhang351d77b2016-05-20 15:08:29 -0700674void Port::OnNetworkTypeChanged(const rtc::Network* network) {
nisseede5da42017-01-12 05:15:36 -0800675 RTC_DCHECK(network == network_);
Honghai Zhang351d77b2016-05-20 15:08:29 -0700676
677 UpdateNetworkCost();
678}
679
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000680std::string Port::ToString() const {
681 std::stringstream ss;
honghaize3c6c822016-02-17 13:00:28 -0800682 ss << "Port[" << std::hex << this << std::dec << ":" << content_name_ << ":"
683 << component_ << ":" << generation_ << ":" << type_ << ":"
684 << network_->ToString() << "]";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000685 return ss.str();
686}
687
Honghai Zhang351d77b2016-05-20 15:08:29 -0700688// TODO(honghaiz): Make the network cost configurable from user setting.
689void Port::UpdateNetworkCost() {
690 uint16_t new_cost = network_->GetCost();
691 if (network_cost_ == new_cost) {
692 return;
693 }
694 LOG(LS_INFO) << "Network cost changed from " << network_cost_
695 << " to " << new_cost
696 << ". Number of candidates created: " << candidates_.size()
697 << ". Number of connections created: " << connections_.size();
698 network_cost_ = new_cost;
699 for (cricket::Candidate& candidate : candidates_) {
700 candidate.set_network_cost(network_cost_);
701 }
702 // Network cost change will affect the connection selection criteria.
703 // Signal the connection state change on each connection to force a
704 // re-sort in P2PTransportChannel.
705 for (auto kv : connections_) {
706 Connection* conn = kv.second;
707 conn->SignalStateChange(conn);
708 }
709}
710
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000711void Port::EnablePortPackets() {
712 enable_port_packets_ = true;
713}
714
715void Port::OnConnectionDestroyed(Connection* conn) {
716 AddressMap::iterator iter =
717 connections_.find(conn->remote_candidate().address());
nisseede5da42017-01-12 05:15:36 -0800718 RTC_DCHECK(iter != connections_.end());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000719 connections_.erase(iter);
honghaiz36f50e82016-06-01 15:57:03 -0700720 HandleConnectionDestroyed(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000721
Honghai Zhanga74363c2016-07-28 18:06:15 -0700722 // Ports time out after all connections fail if it is not marked as
723 // "keep alive until pruned."
honghaizd0b31432015-09-30 12:42:17 -0700724 // Note: If a new connection is added after this message is posted, but it
725 // fails and is removed before kPortTimeoutDelay, then this message will
Honghai Zhangb5db1ec2016-07-28 13:23:05 -0700726 // not cause the Port to be destroyed.
Honghai Zhanga74363c2016-07-28 18:06:15 -0700727 if (connections_.empty()) {
Honghai Zhangb5db1ec2016-07-28 13:23:05 -0700728 last_time_all_connections_removed_ = rtc::TimeMillis();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700729 thread_->PostDelayed(RTC_FROM_HERE, timeout_delay_, this,
730 MSG_DESTROY_IF_DEAD);
honghaizd0b31432015-09-30 12:42:17 -0700731 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000732}
733
734void Port::Destroy() {
nisseede5da42017-01-12 05:15:36 -0800735 RTC_DCHECK(connections_.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000736 LOG_J(LS_INFO, this) << "Port deleted";
737 SignalDestroyed(this);
738 delete this;
739}
740
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000741const std::string Port::username_fragment() const {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700742 return ice_username_fragment_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000743}
744
745// A ConnectionRequest is a simple STUN ping used to determine writability.
746class ConnectionRequest : public StunRequest {
747 public:
748 explicit ConnectionRequest(Connection* connection)
749 : StunRequest(new IceMessage()),
750 connection_(connection) {
751 }
752
753 virtual ~ConnectionRequest() {
754 }
755
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700756 void Prepare(StunMessage* request) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000757 request->SetType(STUN_BINDING_REQUEST);
758 std::string username;
759 connection_->port()->CreateStunUsername(
760 connection_->remote_candidate().username(), &username);
761 request->AddAttribute(
762 new StunByteStringAttribute(STUN_ATTR_USERNAME, username));
763
764 // connection_ already holds this ping, so subtract one from count.
765 if (connection_->port()->send_retransmit_count_attribute()) {
766 request->AddAttribute(new StunUInt32Attribute(
767 STUN_ATTR_RETRANSMIT_COUNT,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200768 static_cast<uint32_t>(connection_->pings_since_last_response_.size() -
769 1)));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000770 }
honghaiza0c44ea2016-03-23 16:07:48 -0700771 uint32_t network_info = connection_->port()->Network()->id();
772 network_info = (network_info << 16) | connection_->port()->network_cost();
773 request->AddAttribute(
774 new StunUInt32Attribute(STUN_ATTR_NETWORK_INFO, network_info));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000775
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700776 // Adding ICE_CONTROLLED or ICE_CONTROLLING attribute based on the role.
777 if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLING) {
778 request->AddAttribute(new StunUInt64Attribute(
779 STUN_ATTR_ICE_CONTROLLING, connection_->port()->IceTiebreaker()));
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700780 // We should have either USE_CANDIDATE attribute or ICE_NOMINATION
781 // attribute but not both. That was enforced in p2ptransportchannel.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700782 if (connection_->use_candidate_attr()) {
783 request->AddAttribute(new StunByteStringAttribute(
784 STUN_ATTR_USE_CANDIDATE));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000785 }
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700786 if (connection_->nomination() &&
787 connection_->nomination() != connection_->acked_nomination()) {
788 request->AddAttribute(new StunUInt32Attribute(
789 STUN_ATTR_NOMINATION, connection_->nomination()));
790 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700791 } else if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLED) {
792 request->AddAttribute(new StunUInt64Attribute(
793 STUN_ATTR_ICE_CONTROLLED, connection_->port()->IceTiebreaker()));
794 } else {
nissec80e7412017-01-11 05:56:46 -0800795 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000796 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700797
798 // Adding PRIORITY Attribute.
799 // Changing the type preference to Peer Reflexive and local preference
800 // and component id information is unchanged from the original priority.
801 // priority = (2^24)*(type preference) +
802 // (2^8)*(local preference) +
803 // (2^0)*(256 - component ID)
Taylor Brandstetter62351c92016-08-11 16:05:07 -0700804 uint32_t type_preference =
805 (connection_->local_candidate().protocol() == TCP_PROTOCOL_NAME)
806 ? ICE_TYPE_PREFERENCE_PRFLX_TCP
807 : ICE_TYPE_PREFERENCE_PRFLX;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200808 uint32_t prflx_priority =
Taylor Brandstetter62351c92016-08-11 16:05:07 -0700809 type_preference << 24 |
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700810 (connection_->local_candidate().priority() & 0x00FFFFFF);
811 request->AddAttribute(
812 new StunUInt32Attribute(STUN_ATTR_PRIORITY, prflx_priority));
813
814 // Adding Message Integrity attribute.
815 request->AddMessageIntegrity(connection_->remote_candidate().password());
816 // Adding Fingerprint.
817 request->AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000818 }
819
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700820 void OnResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000821 connection_->OnConnectionRequestResponse(this, response);
822 }
823
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700824 void OnErrorResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000825 connection_->OnConnectionRequestErrorResponse(this, response);
826 }
827
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700828 void OnTimeout() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000829 connection_->OnConnectionRequestTimeout(this);
830 }
831
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700832 void OnSent() override {
833 connection_->OnConnectionRequestSent(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000834 // Each request is sent only once. After a single delay , the request will
835 // time out.
836 timeout_ = true;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700837 }
838
839 int resend_delay() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000840 return CONNECTION_RESPONSE_TIMEOUT;
841 }
842
843 private:
844 Connection* connection_;
845};
846
847//
848// Connection
849//
850
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000851Connection::Connection(Port* port,
852 size_t index,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000853 const Candidate& remote_candidate)
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000854 : port_(port),
855 local_candidate_index_(index),
856 remote_candidate_(remote_candidate),
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700857 recv_rate_tracker_(100, 10u),
858 send_rate_tracker_(100, 10u),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000859 write_state_(STATE_WRITE_INIT),
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700860 receiving_(false),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000861 connected_(true),
862 pruned_(false),
863 use_candidate_attr_(false),
864 remote_ice_mode_(ICEMODE_FULL),
865 requests_(port->thread()),
866 rtt_(DEFAULT_RTT),
867 last_ping_sent_(0),
868 last_ping_received_(0),
869 last_data_received_(0),
870 last_ping_response_received_(0),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000871 reported_(false),
hbos06495bc2017-01-02 08:08:18 -0800872 state_(IceCandidatePairState::WAITING),
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700873 receiving_timeout_(WEAK_CONNECTION_RECEIVE_TIMEOUT),
nisse1bffc1d2016-05-02 08:18:55 -0700874 time_created_ms_(rtc::TimeMillis()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000875 // All of our connections start in WAITING state.
876 // TODO(mallinath) - Start connections from STATE_FROZEN.
877 // Wire up to send stun packets
878 requests_.SignalSendPacket.connect(this, &Connection::OnSendStunPacket);
879 LOG_J(LS_INFO, this) << "Connection created";
880}
881
882Connection::~Connection() {
883}
884
885const Candidate& Connection::local_candidate() const {
nisseede5da42017-01-12 05:15:36 -0800886 RTC_DCHECK(local_candidate_index_ < port_->Candidates().size());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000887 return port_->Candidates()[local_candidate_index_];
888}
889
Honghai Zhangcc411c02016-03-29 17:27:21 -0700890const Candidate& Connection::remote_candidate() const {
891 return remote_candidate_;
892}
893
Peter Boström0c4e06b2015-10-07 12:23:21 +0200894uint64_t Connection::priority() const {
895 uint64_t priority = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000896 // RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs
897 // Let G be the priority for the candidate provided by the controlling
898 // agent. Let D be the priority for the candidate provided by the
899 // controlled agent.
900 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
901 IceRole role = port_->GetIceRole();
902 if (role != ICEROLE_UNKNOWN) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200903 uint32_t g = 0;
904 uint32_t d = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000905 if (role == ICEROLE_CONTROLLING) {
906 g = local_candidate().priority();
907 d = remote_candidate_.priority();
908 } else {
909 g = remote_candidate_.priority();
910 d = local_candidate().priority();
911 }
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000912 priority = std::min(g, d);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000913 priority = priority << 32;
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000914 priority += 2 * std::max(g, d) + (g > d ? 1 : 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000915 }
916 return priority;
917}
918
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000919void Connection::set_write_state(WriteState value) {
920 WriteState old_value = write_state_;
921 write_state_ = value;
922 if (value != old_value) {
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +0000923 LOG_J(LS_VERBOSE, this) << "set_write_state from: " << old_value << " to "
924 << value;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000925 SignalStateChange(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000926 }
927}
928
honghaiz9ad0db52016-07-14 19:30:28 -0700929void Connection::UpdateReceiving(int64_t now) {
honghaize58d73d2016-10-24 16:38:26 -0700930 bool receiving =
931 last_received() > 0 && now <= last_received() + receiving_timeout_;
honghaiz9ad0db52016-07-14 19:30:28 -0700932 if (receiving_ == receiving) {
933 return;
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700934 }
honghaiz9ad0db52016-07-14 19:30:28 -0700935 LOG_J(LS_VERBOSE, this) << "set_receiving to " << receiving;
936 receiving_ = receiving;
937 receiving_unchanged_since_ = now;
938 SignalStateChange(this);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700939}
940
hbos06495bc2017-01-02 08:08:18 -0800941void Connection::set_state(IceCandidatePairState state) {
942 IceCandidatePairState old_state = state_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000943 state_ = state;
944 if (state != old_state) {
945 LOG_J(LS_VERBOSE, this) << "set_state";
946 }
947}
948
949void Connection::set_connected(bool value) {
950 bool old_value = connected_;
951 connected_ = value;
952 if (value != old_value) {
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700953 LOG_J(LS_VERBOSE, this) << "set_connected from: " << old_value << " to "
954 << value;
Taylor Brandstetterb825aee2016-06-29 13:07:16 -0700955 SignalStateChange(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000956 }
957}
958
959void Connection::set_use_candidate_attr(bool enable) {
960 use_candidate_attr_ = enable;
961}
962
963void Connection::OnSendStunPacket(const void* data, size_t size,
964 StunRequest* req) {
965 rtc::PacketOptions options(port_->DefaultDscpValue());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700966 auto err = port_->SendTo(
967 data, size, remote_candidate_.address(), options, false);
968 if (err < 0) {
969 LOG_J(LS_WARNING, this) << "Failed to send STUN ping "
970 << " err=" << err
971 << " id=" << rtc::hex_encode(req->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000972 }
973}
974
975void Connection::OnReadPacket(
976 const char* data, size_t size, const rtc::PacketTime& packet_time) {
kwiberg3ec46792016-04-27 07:22:53 -0700977 std::unique_ptr<IceMessage> msg;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000978 std::string remote_ufrag;
979 const rtc::SocketAddress& addr(remote_candidate_.address());
kwiberg6baec032016-03-15 11:09:39 -0700980 if (!port_->GetStunMessage(data, size, addr, &msg, &remote_ufrag)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000981 // The packet did not parse as a valid STUN message
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700982 // This is a data packet, pass it along.
nisse1bffc1d2016-05-02 08:18:55 -0700983 last_data_received_ = rtc::TimeMillis();
honghaiz9ad0db52016-07-14 19:30:28 -0700984 UpdateReceiving(last_data_received_);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700985 recv_rate_tracker_.AddSamples(size);
986 SignalReadPacket(this, data, size, packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000987
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700988 // If timed out sending writability checks, start up again
989 if (!pruned_ && (write_state_ == STATE_WRITE_TIMEOUT)) {
990 LOG(LS_WARNING) << "Received a data packet on a timed-out Connection. "
991 << "Resetting state to STATE_WRITE_INIT.";
992 set_write_state(STATE_WRITE_INIT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000993 }
994 } else if (!msg) {
995 // The packet was STUN, but failed a check and was handled internally.
996 } else {
997 // The packet is STUN and passed the Port checks.
998 // Perform our own checks to ensure this packet is valid.
honghaizd0b31432015-09-30 12:42:17 -0700999 // If this is a STUN request, then update the receiving bit and respond.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001000 // If this is a STUN response, then update the writable bit.
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001001 // Log at LS_INFO if we receive a ping on an unwritable connection.
1002 rtc::LoggingSeverity sev = (!writable() ? rtc::LS_INFO : rtc::LS_VERBOSE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001003 switch (msg->type()) {
1004 case STUN_BINDING_REQUEST:
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001005 LOG_JV(sev, this) << "Received STUN ping"
1006 << ", id=" << rtc::hex_encode(msg->transaction_id());
1007
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001008 if (remote_ufrag == remote_candidate_.username()) {
honghaiz9b5ee9c2015-11-11 13:19:17 -08001009 HandleBindingRequest(msg.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001010 } else {
1011 // The packet had the right local username, but the remote username
1012 // was not the right one for the remote address.
1013 LOG_J(LS_ERROR, this)
1014 << "Received STUN request with bad remote username "
1015 << remote_ufrag;
1016 port_->SendBindingErrorResponse(msg.get(), addr,
1017 STUN_ERROR_UNAUTHORIZED,
1018 STUN_ERROR_REASON_UNAUTHORIZED);
1019
1020 }
1021 break;
1022
1023 // Response from remote peer. Does it match request sent?
1024 // This doesn't just check, it makes callbacks if transaction
1025 // id's match.
1026 case STUN_BINDING_RESPONSE:
1027 case STUN_BINDING_ERROR_RESPONSE:
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001028 if (msg->ValidateMessageIntegrity(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001029 data, size, remote_candidate().password())) {
1030 requests_.CheckResponse(msg.get());
1031 }
1032 // Otherwise silently discard the response message.
1033 break;
1034
honghaizd0b31432015-09-30 12:42:17 -07001035 // Remote end point sent an STUN indication instead of regular binding
1036 // request. In this case |last_ping_received_| will be updated but no
1037 // response will be sent.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001038 case STUN_BINDING_INDICATION:
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001039 ReceivedPing();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001040 break;
1041
1042 default:
nissec80e7412017-01-11 05:56:46 -08001043 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001044 break;
1045 }
1046 }
1047}
1048
honghaiz9b5ee9c2015-11-11 13:19:17 -08001049void Connection::HandleBindingRequest(IceMessage* msg) {
1050 // This connection should now be receiving.
1051 ReceivedPing();
1052
1053 const rtc::SocketAddress& remote_addr = remote_candidate_.address();
1054 const std::string& remote_ufrag = remote_candidate_.username();
1055 // Check for role conflicts.
1056 if (!port_->MaybeIceRoleConflict(remote_addr, msg, remote_ufrag)) {
1057 // Received conflicting role from the peer.
1058 LOG(LS_INFO) << "Received conflicting role from the peer.";
1059 return;
1060 }
1061
zhihuang5ecf16c2016-06-01 17:09:15 -07001062 stats_.recv_ping_requests++;
1063
honghaiz9b5ee9c2015-11-11 13:19:17 -08001064 // This is a validated stun request from remote peer.
1065 port_->SendBindingResponse(msg, remote_addr);
1066
1067 // If it timed out on writing check, start up again
1068 if (!pruned_ && write_state_ == STATE_WRITE_TIMEOUT) {
1069 set_write_state(STATE_WRITE_INIT);
1070 }
1071
1072 if (port_->GetIceRole() == ICEROLE_CONTROLLED) {
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001073 const StunUInt32Attribute* nomination_attr =
1074 msg->GetUInt32(STUN_ATTR_NOMINATION);
1075 uint32_t nomination = 0;
1076 if (nomination_attr) {
1077 nomination = nomination_attr->value();
1078 if (nomination == 0) {
1079 LOG(LS_ERROR) << "Invalid nomination: " << nomination;
1080 }
1081 } else {
1082 const StunByteStringAttribute* use_candidate_attr =
1083 msg->GetByteString(STUN_ATTR_USE_CANDIDATE);
1084 if (use_candidate_attr) {
1085 nomination = 1;
1086 }
1087 }
1088 // We don't un-nominate a connection, so we only keep a larger nomination.
1089 if (nomination > remote_nomination_) {
1090 set_remote_nomination(nomination);
honghaiz9b5ee9c2015-11-11 13:19:17 -08001091 SignalNominated(this);
1092 }
1093 }
Honghai Zhang351d77b2016-05-20 15:08:29 -07001094 // Set the remote cost if the network_info attribute is available.
1095 // Note: If packets are re-ordered, we may get incorrect network cost
1096 // temporarily, but it should get the correct value shortly after that.
1097 const StunUInt32Attribute* network_attr =
1098 msg->GetUInt32(STUN_ATTR_NETWORK_INFO);
1099 if (network_attr) {
1100 uint32_t network_info = network_attr->value();
1101 uint16_t network_cost = static_cast<uint16_t>(network_info);
1102 if (network_cost != remote_candidate_.network_cost()) {
1103 remote_candidate_.set_network_cost(network_cost);
1104 // Network cost change will affect the connection ranking, so signal
1105 // state change to force a re-sort in P2PTransportChannel.
1106 SignalStateChange(this);
1107 }
1108 }
honghaiz9b5ee9c2015-11-11 13:19:17 -08001109}
1110
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001111void Connection::OnReadyToSend() {
deadbeefdd7fb432016-09-30 15:16:48 -07001112 SignalReadyToSend(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001113}
1114
1115void Connection::Prune() {
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001116 if (!pruned_ || active()) {
Honghai Zhang1590c392016-05-24 13:15:02 -07001117 LOG_J(LS_INFO, this) << "Connection pruned";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001118 pruned_ = true;
1119 requests_.Clear();
1120 set_write_state(STATE_WRITE_TIMEOUT);
1121 }
1122}
1123
1124void Connection::Destroy() {
1125 LOG_J(LS_VERBOSE, this) << "Connection destroyed";
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001126 port_->thread()->Post(RTC_FROM_HERE, this, MSG_DELETE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001127}
1128
deadbeef376e1232015-11-25 09:00:08 -08001129void Connection::FailAndDestroy() {
hbos06495bc2017-01-02 08:08:18 -08001130 set_state(IceCandidatePairState::FAILED);
deadbeef376e1232015-11-25 09:00:08 -08001131 Destroy();
1132}
1133
honghaiz079a7a12016-06-22 16:26:29 -07001134void Connection::FailAndPrune() {
hbos06495bc2017-01-02 08:08:18 -08001135 set_state(IceCandidatePairState::FAILED);
honghaiz079a7a12016-06-22 16:26:29 -07001136 Prune();
1137}
1138
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001139void Connection::PrintPingsSinceLastResponse(std::string* s, size_t max) {
1140 std::ostringstream oss;
1141 oss << std::boolalpha;
1142 if (pings_since_last_response_.size() > max) {
1143 for (size_t i = 0; i < max; i++) {
1144 const SentPing& ping = pings_since_last_response_[i];
1145 oss << rtc::hex_encode(ping.id) << " ";
1146 }
1147 oss << "... " << (pings_since_last_response_.size() - max) << " more";
1148 } else {
1149 for (const SentPing& ping : pings_since_last_response_) {
1150 oss << rtc::hex_encode(ping.id) << " ";
1151 }
1152 }
1153 *s = oss.str();
1154}
1155
honghaiz34b11eb2016-03-16 08:55:44 -07001156void Connection::UpdateState(int64_t now) {
1157 int rtt = ConservativeRTTEstimate(rtt_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001158
Peter Thatcherb2d26232015-05-15 11:25:14 -07001159 if (LOG_CHECK_LEVEL(LS_VERBOSE)) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001160 std::string pings;
1161 PrintPingsSinceLastResponse(&pings, 5);
1162 LOG_J(LS_VERBOSE, this) << "UpdateState()"
1163 << ", ms since last received response="
1164 << now - last_ping_response_received_
1165 << ", ms since last received data="
1166 << now - last_data_received_
1167 << ", rtt=" << rtt
1168 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001169 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001170
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001171 // Check the writable state. (The order of these checks is important.)
1172 //
1173 // Before becoming unwritable, we allow for a fixed number of pings to fail
1174 // (i.e., receive no response). We also have to give the response time to
1175 // get back, so we include a conservative estimate of this.
1176 //
1177 // Before timing out writability, we give a fixed amount of time. This is to
1178 // allow for changes in network conditions.
1179
1180 if ((write_state_ == STATE_WRITABLE) &&
1181 TooManyFailures(pings_since_last_response_,
1182 CONNECTION_WRITE_CONNECT_FAILURES,
1183 rtt,
1184 now) &&
1185 TooLongWithoutResponse(pings_since_last_response_,
1186 CONNECTION_WRITE_CONNECT_TIMEOUT,
1187 now)) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001188 uint32_t max_pings = CONNECTION_WRITE_CONNECT_FAILURES;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001189 LOG_J(LS_INFO, this) << "Unwritable after " << max_pings
1190 << " ping failures and "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001191 << now - pings_since_last_response_[0].sent_time
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001192 << " ms without a response,"
1193 << " ms since last received ping="
1194 << now - last_ping_received_
1195 << " ms since last received data="
1196 << now - last_data_received_
1197 << " rtt=" << rtt;
1198 set_write_state(STATE_WRITE_UNRELIABLE);
1199 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001200 if ((write_state_ == STATE_WRITE_UNRELIABLE ||
1201 write_state_ == STATE_WRITE_INIT) &&
1202 TooLongWithoutResponse(pings_since_last_response_,
1203 CONNECTION_WRITE_TIMEOUT,
1204 now)) {
1205 LOG_J(LS_INFO, this) << "Timed out after "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001206 << now - pings_since_last_response_[0].sent_time
1207 << " ms without a response"
1208 << ", rtt=" << rtt;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001209 set_write_state(STATE_WRITE_TIMEOUT);
1210 }
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001211
honghaiz9ad0db52016-07-14 19:30:28 -07001212 // Update the receiving state.
1213 UpdateReceiving(now);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001214 if (dead(now)) {
1215 Destroy();
1216 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001217}
1218
honghaiz34b11eb2016-03-16 08:55:44 -07001219void Connection::Ping(int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001220 last_ping_sent_ = now;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001221 ConnectionRequest *req = new ConnectionRequest(this);
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001222 pings_since_last_response_.push_back(SentPing(req->id(), now, nomination_));
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001223 LOG_J(LS_VERBOSE, this) << "Sending STUN ping "
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001224 << ", id=" << rtc::hex_encode(req->id())
1225 << ", nomination=" << nomination_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001226 requests_.Send(req);
hbos06495bc2017-01-02 08:08:18 -08001227 state_ = IceCandidatePairState::IN_PROGRESS;
honghaiz524ecc22016-05-25 12:48:31 -07001228 num_pings_sent_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001229}
1230
1231void Connection::ReceivedPing() {
nisse1bffc1d2016-05-02 08:18:55 -07001232 last_ping_received_ = rtc::TimeMillis();
honghaiz9ad0db52016-07-14 19:30:28 -07001233 UpdateReceiving(last_ping_received_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001234}
1235
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001236void Connection::ReceivedPingResponse(int rtt, const std::string& request_id) {
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001237 // We've already validated that this is a STUN binding response with
1238 // the correct local and remote username for this connection.
1239 // So if we're not already, become writable. We may be bringing a pruned
1240 // connection back to life, but if we don't really want it, we can always
1241 // prune it again.
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001242 auto iter = std::find_if(
1243 pings_since_last_response_.begin(), pings_since_last_response_.end(),
1244 [request_id](const SentPing& ping) { return ping.id == request_id; });
1245 if (iter != pings_since_last_response_.end() &&
1246 iter->nomination > acked_nomination_) {
1247 acked_nomination_ = iter->nomination;
1248 }
1249
1250 pings_since_last_response_.clear();
honghaiz9ad0db52016-07-14 19:30:28 -07001251 last_ping_response_received_ = rtc::TimeMillis();
1252 UpdateReceiving(last_ping_response_received_);
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001253 set_write_state(STATE_WRITABLE);
hbos06495bc2017-01-02 08:08:18 -08001254 set_state(IceCandidatePairState::SUCCEEDED);
skvladd0309122017-02-02 17:18:37 -08001255 if (rtt_samples_ > 0) {
1256 rtt_ = (RTT_RATIO * rtt_ + rtt) / (RTT_RATIO + 1);
1257 } else {
1258 rtt_ = rtt;
1259 }
zhihuang435264a2016-06-21 11:28:38 -07001260 rtt_samples_++;
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001261}
1262
honghaiz34b11eb2016-03-16 08:55:44 -07001263bool Connection::dead(int64_t now) const {
honghaiz37389b42016-01-04 21:57:33 -08001264 if (last_received() > 0) {
1265 // If it has ever received anything, we keep it alive until it hasn't
1266 // received anything for DEAD_CONNECTION_RECEIVE_TIMEOUT. This covers the
1267 // normal case of a successfully used connection that stops working. This
1268 // also allows a remote peer to continue pinging over a locally inactive
1269 // (pruned) connection.
1270 return (now > (last_received() + DEAD_CONNECTION_RECEIVE_TIMEOUT));
1271 }
1272
1273 if (active()) {
1274 // If it has never received anything, keep it alive as long as it is
1275 // actively pinging and not pruned. Otherwise, the connection might be
1276 // deleted before it has a chance to ping. This is the normal case for a
1277 // new connection that is pinging but hasn't received anything yet.
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001278 return false;
1279 }
1280
honghaiz37389b42016-01-04 21:57:33 -08001281 // If it has never received anything and is not actively pinging (pruned), we
1282 // keep it around for at least MIN_CONNECTION_LIFETIME to prevent connections
1283 // from being pruned too quickly during a network change event when two
1284 // networks would be up simultaneously but only for a brief period.
1285 return now > (time_created_ms_ + MIN_CONNECTION_LIFETIME);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001286}
1287
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001288bool Connection::stable(int64_t now) const {
zhihuang435264a2016-06-21 11:28:38 -07001289 // A connection is stable if it's RTT has converged and it isn't missing any
1290 // responses. We should send pings at a higher rate until the RTT converges
1291 // and whenever a ping response is missing (so that we can detect
1292 // unwritability faster)
1293 return rtt_converged() && !missing_responses(now);
1294}
1295
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +00001296std::string Connection::ToDebugId() const {
1297 std::stringstream ss;
1298 ss << std::hex << this;
1299 return ss.str();
1300}
1301
honghaize1a0c942016-02-16 14:54:56 -08001302uint32_t Connection::ComputeNetworkCost() const {
1303 // TODO(honghaiz): Will add rtt as part of the network cost.
Honghai Zhang351d77b2016-05-20 15:08:29 -07001304 return port()->network_cost() + remote_candidate_.network_cost();
honghaize1a0c942016-02-16 14:54:56 -08001305}
1306
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001307std::string Connection::ToString() const {
1308 const char CONNECT_STATE_ABBREV[2] = {
1309 '-', // not connected (false)
1310 'C', // connected (true)
1311 };
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001312 const char RECEIVE_STATE_ABBREV[2] = {
1313 '-', // not receiving (false)
1314 'R', // receiving (true)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001315 };
1316 const char WRITE_STATE_ABBREV[4] = {
1317 'W', // STATE_WRITABLE
1318 'w', // STATE_WRITE_UNRELIABLE
1319 '-', // STATE_WRITE_INIT
1320 'x', // STATE_WRITE_TIMEOUT
1321 };
1322 const std::string ICESTATE[4] = {
1323 "W", // STATE_WAITING
1324 "I", // STATE_INPROGRESS
1325 "S", // STATE_SUCCEEDED
1326 "F" // STATE_FAILED
1327 };
1328 const Candidate& local = local_candidate();
1329 const Candidate& remote = remote_candidate();
1330 std::stringstream ss;
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001331 ss << "Conn[" << ToDebugId() << ":" << port_->content_name() << ":"
1332 << local.id() << ":" << local.component() << ":" << local.generation()
1333 << ":" << local.type() << ":" << local.protocol() << ":"
1334 << local.address().ToSensitiveString() << "->" << remote.id() << ":"
1335 << remote.component() << ":" << remote.priority() << ":" << remote.type()
1336 << ":" << remote.protocol() << ":" << remote.address().ToSensitiveString()
1337 << "|" << CONNECT_STATE_ABBREV[connected()]
1338 << RECEIVE_STATE_ABBREV[receiving()] << WRITE_STATE_ABBREV[write_state()]
hbos06495bc2017-01-02 08:08:18 -08001339 << ICESTATE[static_cast<int>(state())] << "|" << remote_nomination() << "|"
1340 << nomination() << "|" << priority() << "|";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001341 if (rtt_ < DEFAULT_RTT) {
1342 ss << rtt_ << "]";
1343 } else {
1344 ss << "-]";
1345 }
1346 return ss.str();
1347}
1348
1349std::string Connection::ToSensitiveString() const {
1350 return ToString();
1351}
1352
1353void Connection::OnConnectionRequestResponse(ConnectionRequest* request,
1354 StunMessage* response) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001355 // Log at LS_INFO if we receive a ping response on an unwritable
1356 // connection.
1357 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1358
honghaiz34b11eb2016-03-16 08:55:44 -07001359 int rtt = request->Elapsed();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001360
Peter Thatcherb2d26232015-05-15 11:25:14 -07001361 if (LOG_CHECK_LEVEL_V(sev)) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001362 std::string pings;
1363 PrintPingsSinceLastResponse(&pings, 5);
1364 LOG_JV(sev, this) << "Received STUN ping response"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001365 << ", id=" << rtc::hex_encode(request->id())
1366 << ", code=0" // Makes logging easier to parse.
1367 << ", rtt=" << rtt
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001368 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001369 }
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001370 ReceivedPingResponse(rtt, request->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001371
zhihuang5ecf16c2016-06-01 17:09:15 -07001372 stats_.recv_ping_responses++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001373
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001374 MaybeUpdateLocalCandidate(request, response);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001375}
1376
1377void Connection::OnConnectionRequestErrorResponse(ConnectionRequest* request,
1378 StunMessage* response) {
1379 const StunErrorCodeAttribute* error_attr = response->GetErrorCode();
1380 int error_code = STUN_ERROR_GLOBAL_FAILURE;
1381 if (error_attr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001382 error_code = error_attr->code();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001383 }
1384
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001385 LOG_J(LS_INFO, this) << "Received STUN error response"
1386 << " id=" << rtc::hex_encode(request->id())
1387 << " code=" << error_code
1388 << " rtt=" << request->Elapsed();
1389
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001390 if (error_code == STUN_ERROR_UNKNOWN_ATTRIBUTE ||
1391 error_code == STUN_ERROR_SERVER_ERROR ||
1392 error_code == STUN_ERROR_UNAUTHORIZED) {
1393 // Recoverable error, retry
1394 } else if (error_code == STUN_ERROR_STALE_CREDENTIALS) {
1395 // Race failure, retry
1396 } else if (error_code == STUN_ERROR_ROLE_CONFLICT) {
1397 HandleRoleConflictFromPeer();
1398 } else {
1399 // This is not a valid connection.
1400 LOG_J(LS_ERROR, this) << "Received STUN error response, code="
1401 << error_code << "; killing connection";
deadbeef376e1232015-11-25 09:00:08 -08001402 FailAndDestroy();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001403 }
1404}
1405
1406void Connection::OnConnectionRequestTimeout(ConnectionRequest* request) {
1407 // Log at LS_INFO if we miss a ping on a writable connection.
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001408 rtc::LoggingSeverity sev = writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1409 LOG_JV(sev, this) << "Timing-out STUN ping "
1410 << rtc::hex_encode(request->id())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001411 << " after " << request->Elapsed() << " ms";
1412}
1413
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001414void Connection::OnConnectionRequestSent(ConnectionRequest* request) {
1415 // Log at LS_INFO if we send a ping on an unwritable connection.
1416 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1417 LOG_JV(sev, this) << "Sent STUN ping"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001418 << ", id=" << rtc::hex_encode(request->id())
Honghai Zhang8cd8f812016-08-03 19:50:41 -07001419 << ", use_candidate=" << use_candidate_attr()
1420 << ", nomination=" << nomination();
zhihuang5ecf16c2016-06-01 17:09:15 -07001421 stats_.sent_ping_requests_total++;
1422 if (stats_.recv_ping_responses == 0) {
1423 stats_.sent_ping_requests_before_first_response++;
1424 }
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001425}
1426
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001427void Connection::HandleRoleConflictFromPeer() {
1428 port_->SignalRoleConflict(port_);
1429}
1430
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001431void Connection::MaybeSetRemoteIceParametersAndGeneration(
1432 const IceParameters& ice_params,
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001433 int generation) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001434 if (remote_candidate_.username() == ice_params.ufrag &&
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001435 remote_candidate_.password().empty()) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001436 remote_candidate_.set_password(ice_params.pwd);
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001437 }
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001438 // TODO(deadbeef): A value of '0' for the generation is used for both
1439 // generation 0 and "generation unknown". It should be changed to an
1440 // rtc::Optional to fix this.
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001441 if (remote_candidate_.username() == ice_params.ufrag &&
1442 remote_candidate_.password() == ice_params.pwd &&
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001443 remote_candidate_.generation() == 0) {
1444 remote_candidate_.set_generation(generation);
1445 }
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001446}
1447
1448void Connection::MaybeUpdatePeerReflexiveCandidate(
1449 const Candidate& new_candidate) {
1450 if (remote_candidate_.type() == PRFLX_PORT_TYPE &&
1451 new_candidate.type() != PRFLX_PORT_TYPE &&
1452 remote_candidate_.protocol() == new_candidate.protocol() &&
1453 remote_candidate_.address() == new_candidate.address() &&
1454 remote_candidate_.username() == new_candidate.username() &&
1455 remote_candidate_.password() == new_candidate.password() &&
1456 remote_candidate_.generation() == new_candidate.generation()) {
1457 remote_candidate_ = new_candidate;
1458 }
1459}
1460
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001461void Connection::OnMessage(rtc::Message *pmsg) {
nisseede5da42017-01-12 05:15:36 -08001462 RTC_DCHECK(pmsg->message_id == MSG_DELETE);
honghaiz18f9da02016-06-01 23:53:01 -07001463 LOG(LS_INFO) << "Connection deleted with number of pings sent: "
1464 << num_pings_sent_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001465 SignalDestroyed(this);
1466 delete this;
1467}
1468
honghaiz34b11eb2016-03-16 08:55:44 -07001469int64_t Connection::last_received() const {
Peter Thatcher54360512015-07-08 11:08:35 -07001470 return std::max(last_data_received_,
1471 std::max(last_ping_received_, last_ping_response_received_));
1472}
1473
zhihuang5ecf16c2016-06-01 17:09:15 -07001474ConnectionInfo Connection::stats() {
1475 stats_.recv_bytes_second = round(recv_rate_tracker_.ComputeRate());
1476 stats_.recv_total_bytes = recv_rate_tracker_.TotalSampleCount();
1477 stats_.sent_bytes_second = round(send_rate_tracker_.ComputeRate());
1478 stats_.sent_total_bytes = send_rate_tracker_.TotalSampleCount();
hbos06495bc2017-01-02 08:08:18 -08001479 stats_.receiving = receiving_;
1480 stats_.writable = write_state_ == STATE_WRITABLE;
1481 stats_.timeout = write_state_ == STATE_WRITE_TIMEOUT;
1482 stats_.new_connection = !reported_;
1483 stats_.rtt = rtt_;
1484 stats_.local_candidate = local_candidate();
1485 stats_.remote_candidate = remote_candidate();
1486 stats_.key = this;
1487 stats_.state = state_;
1488 stats_.priority = priority();
zhihuang5ecf16c2016-06-01 17:09:15 -07001489 return stats_;
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001490}
1491
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001492void Connection::MaybeUpdateLocalCandidate(ConnectionRequest* request,
1493 StunMessage* response) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001494 // RFC 5245
1495 // The agent checks the mapped address from the STUN response. If the
1496 // transport address does not match any of the local candidates that the
1497 // agent knows about, the mapped address represents a new candidate -- a
1498 // peer reflexive candidate.
1499 const StunAddressAttribute* addr =
1500 response->GetAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
1501 if (!addr) {
1502 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1503 << "No MAPPED-ADDRESS or XOR-MAPPED-ADDRESS found in the "
1504 << "stun response message";
1505 return;
1506 }
1507
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001508 for (size_t i = 0; i < port_->Candidates().size(); ++i) {
1509 if (port_->Candidates()[i].address() == addr->GetAddress()) {
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001510 if (local_candidate_index_ != i) {
1511 LOG_J(LS_INFO, this) << "Updating local candidate type to srflx.";
1512 local_candidate_index_ = i;
1513 // SignalStateChange to force a re-sort in P2PTransportChannel as this
1514 // Connection's local candidate has changed.
1515 SignalStateChange(this);
1516 }
1517 return;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001518 }
1519 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001520
1521 // RFC 5245
1522 // Its priority is set equal to the value of the PRIORITY attribute
1523 // in the Binding request.
1524 const StunUInt32Attribute* priority_attr =
1525 request->msg()->GetUInt32(STUN_ATTR_PRIORITY);
1526 if (!priority_attr) {
1527 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1528 << "No STUN_ATTR_PRIORITY found in the "
1529 << "stun response message";
1530 return;
1531 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001532 const uint32_t priority = priority_attr->value();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001533 std::string id = rtc::CreateRandomString(8);
1534
1535 Candidate new_local_candidate;
1536 new_local_candidate.set_id(id);
1537 new_local_candidate.set_component(local_candidate().component());
1538 new_local_candidate.set_type(PRFLX_PORT_TYPE);
1539 new_local_candidate.set_protocol(local_candidate().protocol());
1540 new_local_candidate.set_address(addr->GetAddress());
1541 new_local_candidate.set_priority(priority);
1542 new_local_candidate.set_username(local_candidate().username());
1543 new_local_candidate.set_password(local_candidate().password());
1544 new_local_candidate.set_network_name(local_candidate().network_name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001545 new_local_candidate.set_network_type(local_candidate().network_type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001546 new_local_candidate.set_related_address(local_candidate().address());
Taylor Brandstetterf7c15a92016-06-22 13:13:55 -07001547 new_local_candidate.set_generation(local_candidate().generation());
Honghai Zhang80f1db92016-01-27 11:54:45 -08001548 new_local_candidate.set_foundation(ComputeFoundation(
1549 PRFLX_PORT_TYPE, local_candidate().protocol(),
1550 local_candidate().relay_protocol(), local_candidate().address()));
honghaiza0c44ea2016-03-23 16:07:48 -07001551 new_local_candidate.set_network_id(local_candidate().network_id());
1552 new_local_candidate.set_network_cost(local_candidate().network_cost());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001553
1554 // Change the local candidate of this Connection to the new prflx candidate.
Taylor Brandstetter62351c92016-08-11 16:05:07 -07001555 LOG_J(LS_INFO, this) << "Updating local candidate type to prflx.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001556 local_candidate_index_ = port_->AddPrflxCandidate(new_local_candidate);
1557
1558 // SignalStateChange to force a re-sort in P2PTransportChannel as this
1559 // Connection's local candidate has changed.
1560 SignalStateChange(this);
1561}
1562
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001563bool Connection::rtt_converged() const {
zhihuang435264a2016-06-21 11:28:38 -07001564 return rtt_samples_ > (RTT_RATIO + 1);
1565}
1566
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001567bool Connection::missing_responses(int64_t now) const {
zhihuang435264a2016-06-21 11:28:38 -07001568 if (pings_since_last_response_.empty()) {
1569 return false;
1570 }
1571
1572 int64_t waiting = now - pings_since_last_response_[0].sent_time;
1573 return waiting > 2 * rtt();
1574}
1575
deadbeef376e1232015-11-25 09:00:08 -08001576ProxyConnection::ProxyConnection(Port* port,
1577 size_t index,
1578 const Candidate& remote_candidate)
1579 : Connection(port, index, remote_candidate) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001580
1581int ProxyConnection::Send(const void* data, size_t size,
1582 const rtc::PacketOptions& options) {
zhihuang5ecf16c2016-06-01 17:09:15 -07001583 stats_.sent_total_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001584 int sent = port_->SendTo(data, size, remote_candidate_.address(),
1585 options, true);
1586 if (sent <= 0) {
nisseede5da42017-01-12 05:15:36 -08001587 RTC_DCHECK(sent < 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001588 error_ = port_->GetError();
zhihuang5ecf16c2016-06-01 17:09:15 -07001589 stats_.sent_discarded_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001590 } else {
Tim Psiaki63046262015-09-14 10:38:08 -07001591 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001592 }
1593 return sent;
1594}
1595
1596} // namespace cricket