blob: 9fa6bad9116577d279af162bd51cc06ac825381e [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "webrtc/p2p/base/port.h"
12
13#include <algorithm>
14#include <vector>
15
16#include "webrtc/p2p/base/common.h"
17#include "webrtc/p2p/base/portallocator.h"
18#include "webrtc/base/base64.h"
19#include "webrtc/base/crc32.h"
20#include "webrtc/base/helpers.h"
21#include "webrtc/base/logging.h"
22#include "webrtc/base/messagedigest.h"
honghaize3c6c822016-02-17 13:00:28 -080023#include "webrtc/base/network.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000024#include "webrtc/base/stringencode.h"
25#include "webrtc/base/stringutils.h"
26
27namespace {
28
29// Determines whether we have seen at least the given maximum number of
30// pings fail to have a response.
31inline bool TooManyFailures(
Peter Thatcher1cf6f812015-05-15 10:40:45 -070032 const std::vector<cricket::Connection::SentPing>& pings_since_last_response,
Peter Boström0c4e06b2015-10-07 12:23:21 +020033 uint32_t maximum_failures,
honghaiz34b11eb2016-03-16 08:55:44 -070034 int rtt_estimate,
35 int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000036 // If we haven't sent that many pings, then we can't have failed that many.
37 if (pings_since_last_response.size() < maximum_failures)
38 return false;
39
40 // Check if the window in which we would expect a response to the ping has
41 // already elapsed.
honghaiz34b11eb2016-03-16 08:55:44 -070042 int64_t expected_response_time =
Peter Thatcher1cf6f812015-05-15 10:40:45 -070043 pings_since_last_response[maximum_failures - 1].sent_time + rtt_estimate;
44 return now > expected_response_time;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000045}
46
47// Determines whether we have gone too long without seeing any response.
48inline bool TooLongWithoutResponse(
Peter Thatcher1cf6f812015-05-15 10:40:45 -070049 const std::vector<cricket::Connection::SentPing>& pings_since_last_response,
honghaiz34b11eb2016-03-16 08:55:44 -070050 int64_t maximum_time,
51 int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000052 if (pings_since_last_response.size() == 0)
53 return false;
54
Peter Thatcher1cf6f812015-05-15 10:40:45 -070055 auto first = pings_since_last_response[0];
56 return now > (first.sent_time + maximum_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000057}
58
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000059// We will restrict RTT estimates (when used for determining state) to be
60// within a reasonable range.
honghaiz34b11eb2016-03-16 08:55:44 -070061const int MINIMUM_RTT = 100; // 0.1 seconds
62const int MAXIMUM_RTT = 3000; // 3 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000063
64// When we don't have any RTT data, we have to pick something reasonable. We
65// use a large value just in case the connection is really slow.
honghaiz34b11eb2016-03-16 08:55:44 -070066const int DEFAULT_RTT = MAXIMUM_RTT;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000067
68// Computes our estimate of the RTT given the current estimate.
honghaiz34b11eb2016-03-16 08:55:44 -070069inline int ConservativeRTTEstimate(int rtt) {
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000070 return std::max(MINIMUM_RTT, std::min(MAXIMUM_RTT, 2 * rtt));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000071}
72
73// Weighting of the old rtt value to new data.
74const int RTT_RATIO = 3; // 3 : 1
75
76// The delay before we begin checking if this port is useless.
77const int kPortTimeoutDelay = 30 * 1000; // 30 seconds
Honghai Zhang351d77b2016-05-20 15:08:29 -070078} // namespace
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000079
80namespace cricket {
81
82// TODO(ronghuawu): Use "host", "srflx", "prflx" and "relay". But this requires
83// the signaling part be updated correspondingly as well.
84const char LOCAL_PORT_TYPE[] = "local";
85const char STUN_PORT_TYPE[] = "stun";
86const char PRFLX_PORT_TYPE[] = "prflx";
87const char RELAY_PORT_TYPE[] = "relay";
88
89const char UDP_PROTOCOL_NAME[] = "udp";
90const char TCP_PROTOCOL_NAME[] = "tcp";
91const char SSLTCP_PROTOCOL_NAME[] = "ssltcp";
92
93static const char* const PROTO_NAMES[] = { UDP_PROTOCOL_NAME,
94 TCP_PROTOCOL_NAME,
95 SSLTCP_PROTOCOL_NAME };
96
97const char* ProtoToString(ProtocolType proto) {
98 return PROTO_NAMES[proto];
99}
100
101bool StringToProto(const char* value, ProtocolType* proto) {
102 for (size_t i = 0; i <= PROTO_LAST; ++i) {
103 if (_stricmp(PROTO_NAMES[i], value) == 0) {
104 *proto = static_cast<ProtocolType>(i);
105 return true;
106 }
107 }
108 return false;
109}
110
111// RFC 6544, TCP candidate encoding rules.
112const int DISCARD_PORT = 9;
113const char TCPTYPE_ACTIVE_STR[] = "active";
114const char TCPTYPE_PASSIVE_STR[] = "passive";
115const char TCPTYPE_SIMOPEN_STR[] = "so";
116
117// Foundation: An arbitrary string that is the same for two candidates
118// that have the same type, base IP address, protocol (UDP, TCP,
119// etc.), and STUN or TURN server. If any of these are different,
120// then the foundation will be different. Two candidate pairs with
121// the same foundation pairs are likely to have similar network
122// characteristics. Foundations are used in the frozen algorithm.
Honghai Zhang80f1db92016-01-27 11:54:45 -0800123static std::string ComputeFoundation(const std::string& type,
124 const std::string& protocol,
125 const std::string& relay_protocol,
126 const rtc::SocketAddress& base_address) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000127 std::ostringstream ost;
Honghai Zhang80f1db92016-01-27 11:54:45 -0800128 ost << type << base_address.ipaddr().ToString() << protocol << relay_protocol;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200129 return rtc::ToString<uint32_t>(rtc::ComputeCrc32(ost.str()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000130}
131
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000132Port::Port(rtc::Thread* thread,
133 rtc::PacketSocketFactory* factory,
134 rtc::Network* network,
135 const rtc::IPAddress& ip,
136 const std::string& username_fragment,
137 const std::string& password)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000138 : thread_(thread),
139 factory_(factory),
140 send_retransmit_count_attribute_(false),
141 network_(network),
142 ip_(ip),
143 min_port_(0),
144 max_port_(0),
145 component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
146 generation_(0),
147 ice_username_fragment_(username_fragment),
148 password_(password),
149 timeout_delay_(kPortTimeoutDelay),
150 enable_port_packets_(false),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000151 ice_role_(ICEROLE_UNKNOWN),
152 tiebreaker_(0),
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700153 shared_socket_(true) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000154 Construct();
155}
156
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000157Port::Port(rtc::Thread* thread,
158 const std::string& type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000159 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000160 rtc::Network* network,
161 const rtc::IPAddress& ip,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200162 uint16_t min_port,
163 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000164 const std::string& username_fragment,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000165 const std::string& password)
166 : thread_(thread),
167 factory_(factory),
168 type_(type),
169 send_retransmit_count_attribute_(false),
170 network_(network),
171 ip_(ip),
172 min_port_(min_port),
173 max_port_(max_port),
174 component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
175 generation_(0),
176 ice_username_fragment_(username_fragment),
177 password_(password),
178 timeout_delay_(kPortTimeoutDelay),
179 enable_port_packets_(false),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000180 ice_role_(ICEROLE_UNKNOWN),
181 tiebreaker_(0),
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700182 shared_socket_(false) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000183 ASSERT(factory_ != NULL);
184 Construct();
185}
186
187void Port::Construct() {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700188 // TODO(pthatcher): Remove this old behavior once we're sure no one
189 // relies on it. If the username_fragment and password are empty,
190 // we should just create one.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000191 if (ice_username_fragment_.empty()) {
192 ASSERT(password_.empty());
193 ice_username_fragment_ = rtc::CreateRandomString(ICE_UFRAG_LENGTH);
194 password_ = rtc::CreateRandomString(ICE_PWD_LENGTH);
195 }
honghaize3c6c822016-02-17 13:00:28 -0800196 network_->SignalInactive.connect(this, &Port::OnNetworkInactive);
Honghai Zhang351d77b2016-05-20 15:08:29 -0700197 network_->SignalTypeChanged.connect(this, &Port::OnNetworkTypeChanged);
198 network_cost_ = network_->GetCost();
honghaize1a0c942016-02-16 14:54:56 -0800199
Honghai Zhang351d77b2016-05-20 15:08:29 -0700200 LOG_J(LS_INFO, this) << "Port created with network cost " << network_cost_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000201}
202
203Port::~Port() {
204 // Delete all of the remaining connections. We copy the list up front
205 // because each deletion will cause it to be modified.
206
207 std::vector<Connection*> list;
208
209 AddressMap::iterator iter = connections_.begin();
210 while (iter != connections_.end()) {
211 list.push_back(iter->second);
212 ++iter;
213 }
214
Peter Boström0c4e06b2015-10-07 12:23:21 +0200215 for (uint32_t i = 0; i < list.size(); i++)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000216 delete list[i];
217}
218
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700219void Port::SetIceParameters(int component,
220 const std::string& username_fragment,
221 const std::string& password) {
222 component_ = component;
223 ice_username_fragment_ = username_fragment;
224 password_ = password;
225 for (Candidate& c : candidates_) {
226 c.set_component(component);
227 c.set_username(username_fragment);
228 c.set_password(password);
229 }
230}
231
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000232Connection* Port::GetConnection(const rtc::SocketAddress& remote_addr) {
233 AddressMap::const_iterator iter = connections_.find(remote_addr);
234 if (iter != connections_.end())
235 return iter->second;
236 else
237 return NULL;
238}
239
240void Port::AddAddress(const rtc::SocketAddress& address,
241 const rtc::SocketAddress& base_address,
242 const rtc::SocketAddress& related_address,
243 const std::string& protocol,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700244 const std::string& relay_protocol,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000245 const std::string& tcptype,
246 const std::string& type,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200247 uint32_t type_preference,
248 uint32_t relay_preference,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000249 bool final) {
250 if (protocol == TCP_PROTOCOL_NAME && type == LOCAL_PORT_TYPE) {
251 ASSERT(!tcptype.empty());
252 }
253
honghaiza0c44ea2016-03-23 16:07:48 -0700254 std::string foundation =
255 ComputeFoundation(type, protocol, relay_protocol, base_address);
256 Candidate c(component_, protocol, address, 0U, username_fragment(), password_,
257 type, generation_, foundation, network_->id(), network_cost_);
258 c.set_priority(
259 c.GetPriority(type_preference, network_->preference(), relay_preference));
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700260 c.set_relay_protocol(relay_protocol);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000261 c.set_tcptype(tcptype);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000262 c.set_network_name(network_->name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +0000263 c.set_network_type(network_->type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000264 c.set_related_address(related_address);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000265 candidates_.push_back(c);
266 SignalCandidateReady(this, c);
267
268 if (final) {
269 SignalPortComplete(this);
270 }
271}
272
honghaiz36f50e82016-06-01 15:57:03 -0700273void Port::AddOrReplaceConnection(Connection* conn) {
274 auto ret = connections_.insert(
275 std::make_pair(conn->remote_candidate().address(), conn));
276 // If there is a different connection on the same remote address, replace
277 // it with the new one and destroy the old one.
278 if (ret.second == false && ret.first->second != conn) {
279 LOG_J(LS_WARNING, this)
280 << "A new connection was created on an existing remote address. "
281 << "New remote candidate: " << conn->remote_candidate().ToString();
282 ret.first->second->SignalDestroyed.disconnect(this);
283 ret.first->second->Destroy();
284 ret.first->second = conn;
285 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000286 conn->SignalDestroyed.connect(this, &Port::OnConnectionDestroyed);
287 SignalConnectionCreated(this, conn);
288}
289
290void Port::OnReadPacket(
291 const char* data, size_t size, const rtc::SocketAddress& addr,
292 ProtocolType proto) {
293 // If the user has enabled port packets, just hand this over.
294 if (enable_port_packets_) {
295 SignalReadPacket(this, data, size, addr);
296 return;
297 }
298
299 // If this is an authenticated STUN request, then signal unknown address and
300 // send back a proper binding response.
kwiberg3ec46792016-04-27 07:22:53 -0700301 std::unique_ptr<IceMessage> msg;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000302 std::string remote_username;
kwiberg6baec032016-03-15 11:09:39 -0700303 if (!GetStunMessage(data, size, addr, &msg, &remote_username)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000304 LOG_J(LS_ERROR, this) << "Received non-STUN packet from unknown address ("
305 << addr.ToSensitiveString() << ")";
306 } else if (!msg) {
307 // STUN message handled already
308 } else if (msg->type() == STUN_BINDING_REQUEST) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700309 LOG(LS_INFO) << "Received STUN ping "
310 << " id=" << rtc::hex_encode(msg->transaction_id())
311 << " from unknown address " << addr.ToSensitiveString();
312
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000313 // Check for role conflicts.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700314 if (!MaybeIceRoleConflict(addr, msg.get(), remote_username)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000315 LOG(LS_INFO) << "Received conflicting role from the peer.";
316 return;
317 }
318
319 SignalUnknownAddress(this, addr, proto, msg.get(), remote_username, false);
320 } else {
321 // NOTE(tschmelcher): STUN_BINDING_RESPONSE is benign. It occurs if we
322 // pruned a connection for this port while it had STUN requests in flight,
323 // because we then get back responses for them, which this code correctly
324 // does not handle.
325 if (msg->type() != STUN_BINDING_RESPONSE) {
326 LOG_J(LS_ERROR, this) << "Received unexpected STUN message type ("
327 << msg->type() << ") from unknown address ("
328 << addr.ToSensitiveString() << ")";
329 }
330 }
331}
332
333void Port::OnReadyToSend() {
334 AddressMap::iterator iter = connections_.begin();
335 for (; iter != connections_.end(); ++iter) {
336 iter->second->OnReadyToSend();
337 }
338}
339
340size_t Port::AddPrflxCandidate(const Candidate& local) {
341 candidates_.push_back(local);
342 return (candidates_.size() - 1);
343}
344
kwiberg6baec032016-03-15 11:09:39 -0700345bool Port::GetStunMessage(const char* data,
346 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000347 const rtc::SocketAddress& addr,
kwiberg3ec46792016-04-27 07:22:53 -0700348 std::unique_ptr<IceMessage>* out_msg,
kwiberg6baec032016-03-15 11:09:39 -0700349 std::string* out_username) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000350 // NOTE: This could clearly be optimized to avoid allocating any memory.
351 // However, at the data rates we'll be looking at on the client side,
352 // this probably isn't worth worrying about.
353 ASSERT(out_msg != NULL);
354 ASSERT(out_username != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000355 out_username->clear();
356
357 // Don't bother parsing the packet if we can tell it's not STUN.
358 // In ICE mode, all STUN packets will have a valid fingerprint.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700359 if (!StunMessage::ValidateFingerprint(data, size)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000360 return false;
361 }
362
363 // Parse the request message. If the packet is not a complete and correct
364 // STUN message, then ignore it.
kwiberg3ec46792016-04-27 07:22:53 -0700365 std::unique_ptr<IceMessage> stun_msg(new IceMessage());
jbauchf1f87202016-03-30 06:43:37 -0700366 rtc::ByteBufferReader buf(data, size);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000367 if (!stun_msg->Read(&buf) || (buf.Length() > 0)) {
368 return false;
369 }
370
371 if (stun_msg->type() == STUN_BINDING_REQUEST) {
372 // Check for the presence of USERNAME and MESSAGE-INTEGRITY (if ICE) first.
373 // If not present, fail with a 400 Bad Request.
374 if (!stun_msg->GetByteString(STUN_ATTR_USERNAME) ||
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700375 !stun_msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000376 LOG_J(LS_ERROR, this) << "Received STUN request without username/M-I "
377 << "from " << addr.ToSensitiveString();
378 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_BAD_REQUEST,
379 STUN_ERROR_REASON_BAD_REQUEST);
380 return true;
381 }
382
383 // If the username is bad or unknown, fail with a 401 Unauthorized.
384 std::string local_ufrag;
385 std::string remote_ufrag;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700386 if (!ParseStunUsername(stun_msg.get(), &local_ufrag, &remote_ufrag) ||
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000387 local_ufrag != username_fragment()) {
388 LOG_J(LS_ERROR, this) << "Received STUN request with bad local username "
389 << local_ufrag << " from "
390 << addr.ToSensitiveString();
391 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
392 STUN_ERROR_REASON_UNAUTHORIZED);
393 return true;
394 }
395
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000396 // If ICE, and the MESSAGE-INTEGRITY is bad, fail with a 401 Unauthorized
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700397 if (!stun_msg->ValidateMessageIntegrity(data, size, password_)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000398 LOG_J(LS_ERROR, this) << "Received STUN request with bad M-I "
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +0000399 << "from " << addr.ToSensitiveString()
400 << ", password_=" << password_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000401 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
402 STUN_ERROR_REASON_UNAUTHORIZED);
403 return true;
404 }
405 out_username->assign(remote_ufrag);
406 } else if ((stun_msg->type() == STUN_BINDING_RESPONSE) ||
407 (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE)) {
408 if (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE) {
409 if (const StunErrorCodeAttribute* error_code = stun_msg->GetErrorCode()) {
410 LOG_J(LS_ERROR, this) << "Received STUN binding error:"
411 << " class=" << error_code->eclass()
412 << " number=" << error_code->number()
413 << " reason='" << error_code->reason() << "'"
414 << " from " << addr.ToSensitiveString();
415 // Return message to allow error-specific processing
416 } else {
417 LOG_J(LS_ERROR, this) << "Received STUN binding error without a error "
418 << "code from " << addr.ToSensitiveString();
419 return true;
420 }
421 }
422 // NOTE: Username should not be used in verifying response messages.
423 out_username->clear();
424 } else if (stun_msg->type() == STUN_BINDING_INDICATION) {
425 LOG_J(LS_VERBOSE, this) << "Received STUN binding indication:"
426 << " from " << addr.ToSensitiveString();
427 out_username->clear();
428 // No stun attributes will be verified, if it's stun indication message.
429 // Returning from end of the this method.
430 } else {
431 LOG_J(LS_ERROR, this) << "Received STUN packet with invalid type ("
432 << stun_msg->type() << ") from "
433 << addr.ToSensitiveString();
434 return true;
435 }
436
437 // Return the STUN message found.
kwiberg6baec032016-03-15 11:09:39 -0700438 *out_msg = std::move(stun_msg);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000439 return true;
440}
441
442bool Port::IsCompatibleAddress(const rtc::SocketAddress& addr) {
443 int family = ip().family();
444 // We use single-stack sockets, so families must match.
445 if (addr.family() != family) {
446 return false;
447 }
448 // Link-local IPv6 ports can only connect to other link-local IPv6 ports.
Peter Thatcherb8b01432015-07-07 16:45:53 -0700449 if (family == AF_INET6 &&
450 (IPIsLinkLocal(ip()) != IPIsLinkLocal(addr.ipaddr()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000451 return false;
452 }
453 return true;
454}
455
456bool Port::ParseStunUsername(const StunMessage* stun_msg,
457 std::string* local_ufrag,
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700458 std::string* remote_ufrag) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000459 // The packet must include a username that either begins or ends with our
460 // fragment. It should begin with our fragment if it is a request and it
461 // should end with our fragment if it is a response.
462 local_ufrag->clear();
463 remote_ufrag->clear();
464 const StunByteStringAttribute* username_attr =
465 stun_msg->GetByteString(STUN_ATTR_USERNAME);
466 if (username_attr == NULL)
467 return false;
468
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700469 // RFRAG:LFRAG
470 const std::string username = username_attr->GetString();
471 size_t colon_pos = username.find(":");
472 if (colon_pos == std::string::npos) {
473 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000474 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000475
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700476 *local_ufrag = username.substr(0, colon_pos);
477 *remote_ufrag = username.substr(colon_pos + 1, username.size());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000478 return true;
479}
480
481bool Port::MaybeIceRoleConflict(
482 const rtc::SocketAddress& addr, IceMessage* stun_msg,
483 const std::string& remote_ufrag) {
484 // Validate ICE_CONTROLLING or ICE_CONTROLLED attributes.
485 bool ret = true;
486 IceRole remote_ice_role = ICEROLE_UNKNOWN;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200487 uint64_t remote_tiebreaker = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000488 const StunUInt64Attribute* stun_attr =
489 stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
490 if (stun_attr) {
491 remote_ice_role = ICEROLE_CONTROLLING;
492 remote_tiebreaker = stun_attr->value();
493 }
494
495 // If |remote_ufrag| is same as port local username fragment and
496 // tie breaker value received in the ping message matches port
497 // tiebreaker value this must be a loopback call.
498 // We will treat this as valid scenario.
499 if (remote_ice_role == ICEROLE_CONTROLLING &&
500 username_fragment() == remote_ufrag &&
501 remote_tiebreaker == IceTiebreaker()) {
502 return true;
503 }
504
505 stun_attr = stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
506 if (stun_attr) {
507 remote_ice_role = ICEROLE_CONTROLLED;
508 remote_tiebreaker = stun_attr->value();
509 }
510
511 switch (ice_role_) {
512 case ICEROLE_CONTROLLING:
513 if (ICEROLE_CONTROLLING == remote_ice_role) {
514 if (remote_tiebreaker >= tiebreaker_) {
515 SignalRoleConflict(this);
516 } else {
517 // Send Role Conflict (487) error response.
518 SendBindingErrorResponse(stun_msg, addr,
519 STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
520 ret = false;
521 }
522 }
523 break;
524 case ICEROLE_CONTROLLED:
525 if (ICEROLE_CONTROLLED == remote_ice_role) {
526 if (remote_tiebreaker < tiebreaker_) {
527 SignalRoleConflict(this);
528 } else {
529 // Send Role Conflict (487) error response.
530 SendBindingErrorResponse(stun_msg, addr,
531 STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
532 ret = false;
533 }
534 }
535 break;
536 default:
537 ASSERT(false);
538 }
539 return ret;
540}
541
542void Port::CreateStunUsername(const std::string& remote_username,
543 std::string* stun_username_attr_str) const {
544 stun_username_attr_str->clear();
545 *stun_username_attr_str = remote_username;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700546 stun_username_attr_str->append(":");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000547 stun_username_attr_str->append(username_fragment());
548}
549
550void Port::SendBindingResponse(StunMessage* request,
551 const rtc::SocketAddress& addr) {
552 ASSERT(request->type() == STUN_BINDING_REQUEST);
553
554 // Retrieve the username from the request.
555 const StunByteStringAttribute* username_attr =
556 request->GetByteString(STUN_ATTR_USERNAME);
557 ASSERT(username_attr != NULL);
558 if (username_attr == NULL) {
559 // No valid username, skip the response.
560 return;
561 }
562
563 // Fill in the response message.
564 StunMessage response;
565 response.SetType(STUN_BINDING_RESPONSE);
566 response.SetTransactionID(request->transaction_id());
567 const StunUInt32Attribute* retransmit_attr =
568 request->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
569 if (retransmit_attr) {
570 // Inherit the incoming retransmit value in the response so the other side
571 // can see our view of lost pings.
572 response.AddAttribute(new StunUInt32Attribute(
573 STUN_ATTR_RETRANSMIT_COUNT, retransmit_attr->value()));
574
575 if (retransmit_attr->value() > CONNECTION_WRITE_CONNECT_FAILURES) {
576 LOG_J(LS_INFO, this)
577 << "Received a remote ping with high retransmit count: "
578 << retransmit_attr->value();
579 }
580 }
581
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700582 response.AddAttribute(
583 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, addr));
584 response.AddMessageIntegrity(password_);
585 response.AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000586
587 // Send the response message.
jbauchf1f87202016-03-30 06:43:37 -0700588 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000589 response.Write(&buf);
590 rtc::PacketOptions options(DefaultDscpValue());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700591 auto err = SendTo(buf.Data(), buf.Length(), addr, options, false);
592 if (err < 0) {
593 LOG_J(LS_ERROR, this)
594 << "Failed to send STUN ping response"
595 << ", to=" << addr.ToSensitiveString()
596 << ", err=" << err
597 << ", id=" << rtc::hex_encode(response.transaction_id());
598 } else {
599 // Log at LS_INFO if we send a stun ping response on an unwritable
600 // connection.
honghaiz9b5ee9c2015-11-11 13:19:17 -0800601 Connection* conn = GetConnection(addr);
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700602 rtc::LoggingSeverity sev = (conn && !conn->writable()) ?
603 rtc::LS_INFO : rtc::LS_VERBOSE;
604 LOG_JV(sev, this)
605 << "Sent STUN ping response"
606 << ", to=" << addr.ToSensitiveString()
607 << ", id=" << rtc::hex_encode(response.transaction_id());
zhihuang5ecf16c2016-06-01 17:09:15 -0700608
609 conn->stats_.sent_ping_responses++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000610 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000611}
612
613void Port::SendBindingErrorResponse(StunMessage* request,
614 const rtc::SocketAddress& addr,
615 int error_code, const std::string& reason) {
616 ASSERT(request->type() == STUN_BINDING_REQUEST);
617
618 // Fill in the response message.
619 StunMessage response;
620 response.SetType(STUN_BINDING_ERROR_RESPONSE);
621 response.SetTransactionID(request->transaction_id());
622
623 // When doing GICE, we need to write out the error code incorrectly to
624 // maintain backwards compatiblility.
625 StunErrorCodeAttribute* error_attr = StunAttribute::CreateErrorCode();
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700626 error_attr->SetCode(error_code);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000627 error_attr->SetReason(reason);
628 response.AddAttribute(error_attr);
629
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700630 // Per Section 10.1.2, certain error cases don't get a MESSAGE-INTEGRITY,
631 // because we don't have enough information to determine the shared secret.
632 if (error_code != STUN_ERROR_BAD_REQUEST &&
633 error_code != STUN_ERROR_UNAUTHORIZED)
634 response.AddMessageIntegrity(password_);
635 response.AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000636
637 // Send the response message.
jbauchf1f87202016-03-30 06:43:37 -0700638 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000639 response.Write(&buf);
640 rtc::PacketOptions options(DefaultDscpValue());
641 SendTo(buf.Data(), buf.Length(), addr, options, false);
642 LOG_J(LS_INFO, this) << "Sending STUN binding error: reason=" << reason
643 << " to " << addr.ToSensitiveString();
644}
645
646void Port::OnMessage(rtc::Message *pmsg) {
honghaizd0b31432015-09-30 12:42:17 -0700647 ASSERT(pmsg->message_id == MSG_DEAD);
648 if (dead()) {
649 Destroy();
650 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000651}
652
honghaize3c6c822016-02-17 13:00:28 -0800653void Port::OnNetworkInactive(const rtc::Network* network) {
654 ASSERT(network == network_);
655 SignalNetworkInactive(this);
656}
657
Honghai Zhang351d77b2016-05-20 15:08:29 -0700658void Port::OnNetworkTypeChanged(const rtc::Network* network) {
659 ASSERT(network == network_);
660
661 UpdateNetworkCost();
662}
663
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000664std::string Port::ToString() const {
665 std::stringstream ss;
honghaize3c6c822016-02-17 13:00:28 -0800666 ss << "Port[" << std::hex << this << std::dec << ":" << content_name_ << ":"
667 << component_ << ":" << generation_ << ":" << type_ << ":"
668 << network_->ToString() << "]";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000669 return ss.str();
670}
671
Honghai Zhang351d77b2016-05-20 15:08:29 -0700672// TODO(honghaiz): Make the network cost configurable from user setting.
673void Port::UpdateNetworkCost() {
674 uint16_t new_cost = network_->GetCost();
675 if (network_cost_ == new_cost) {
676 return;
677 }
678 LOG(LS_INFO) << "Network cost changed from " << network_cost_
679 << " to " << new_cost
680 << ". Number of candidates created: " << candidates_.size()
681 << ". Number of connections created: " << connections_.size();
682 network_cost_ = new_cost;
683 for (cricket::Candidate& candidate : candidates_) {
684 candidate.set_network_cost(network_cost_);
685 }
686 // Network cost change will affect the connection selection criteria.
687 // Signal the connection state change on each connection to force a
688 // re-sort in P2PTransportChannel.
689 for (auto kv : connections_) {
690 Connection* conn = kv.second;
691 conn->SignalStateChange(conn);
692 }
693}
694
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000695void Port::EnablePortPackets() {
696 enable_port_packets_ = true;
697}
698
699void Port::OnConnectionDestroyed(Connection* conn) {
700 AddressMap::iterator iter =
701 connections_.find(conn->remote_candidate().address());
702 ASSERT(iter != connections_.end());
703 connections_.erase(iter);
honghaiz36f50e82016-06-01 15:57:03 -0700704 HandleConnectionDestroyed(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000705
honghaizd0b31432015-09-30 12:42:17 -0700706 // On the controlled side, ports time out after all connections fail.
707 // Note: If a new connection is added after this message is posted, but it
708 // fails and is removed before kPortTimeoutDelay, then this message will
709 // still cause the Port to be destroyed.
710 if (dead()) {
711 thread_->PostDelayed(timeout_delay_, this, MSG_DEAD);
712 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000713}
714
715void Port::Destroy() {
716 ASSERT(connections_.empty());
717 LOG_J(LS_INFO, this) << "Port deleted";
718 SignalDestroyed(this);
719 delete this;
720}
721
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000722const std::string Port::username_fragment() const {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700723 return ice_username_fragment_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000724}
725
726// A ConnectionRequest is a simple STUN ping used to determine writability.
727class ConnectionRequest : public StunRequest {
728 public:
729 explicit ConnectionRequest(Connection* connection)
730 : StunRequest(new IceMessage()),
731 connection_(connection) {
732 }
733
734 virtual ~ConnectionRequest() {
735 }
736
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700737 void Prepare(StunMessage* request) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000738 request->SetType(STUN_BINDING_REQUEST);
739 std::string username;
740 connection_->port()->CreateStunUsername(
741 connection_->remote_candidate().username(), &username);
742 request->AddAttribute(
743 new StunByteStringAttribute(STUN_ATTR_USERNAME, username));
744
745 // connection_ already holds this ping, so subtract one from count.
746 if (connection_->port()->send_retransmit_count_attribute()) {
747 request->AddAttribute(new StunUInt32Attribute(
748 STUN_ATTR_RETRANSMIT_COUNT,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200749 static_cast<uint32_t>(connection_->pings_since_last_response_.size() -
750 1)));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000751 }
honghaiza0c44ea2016-03-23 16:07:48 -0700752 uint32_t network_info = connection_->port()->Network()->id();
753 network_info = (network_info << 16) | connection_->port()->network_cost();
754 request->AddAttribute(
755 new StunUInt32Attribute(STUN_ATTR_NETWORK_INFO, network_info));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000756
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700757 // Adding ICE_CONTROLLED or ICE_CONTROLLING attribute based on the role.
758 if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLING) {
759 request->AddAttribute(new StunUInt64Attribute(
760 STUN_ATTR_ICE_CONTROLLING, connection_->port()->IceTiebreaker()));
761 // Since we are trying aggressive nomination, sending USE-CANDIDATE
762 // attribute in every ping.
763 // If we are dealing with a ice-lite end point, nomination flag
764 // in Connection will be set to false by default. Once the connection
765 // becomes "best connection", nomination flag will be turned on.
766 if (connection_->use_candidate_attr()) {
767 request->AddAttribute(new StunByteStringAttribute(
768 STUN_ATTR_USE_CANDIDATE));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000769 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700770 } else if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLED) {
771 request->AddAttribute(new StunUInt64Attribute(
772 STUN_ATTR_ICE_CONTROLLED, connection_->port()->IceTiebreaker()));
773 } else {
774 ASSERT(false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000775 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700776
777 // Adding PRIORITY Attribute.
778 // Changing the type preference to Peer Reflexive and local preference
779 // and component id information is unchanged from the original priority.
780 // priority = (2^24)*(type preference) +
781 // (2^8)*(local preference) +
782 // (2^0)*(256 - component ID)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200783 uint32_t prflx_priority =
784 ICE_TYPE_PREFERENCE_PRFLX << 24 |
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700785 (connection_->local_candidate().priority() & 0x00FFFFFF);
786 request->AddAttribute(
787 new StunUInt32Attribute(STUN_ATTR_PRIORITY, prflx_priority));
788
789 // Adding Message Integrity attribute.
790 request->AddMessageIntegrity(connection_->remote_candidate().password());
791 // Adding Fingerprint.
792 request->AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000793 }
794
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700795 void OnResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000796 connection_->OnConnectionRequestResponse(this, response);
797 }
798
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700799 void OnErrorResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000800 connection_->OnConnectionRequestErrorResponse(this, response);
801 }
802
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700803 void OnTimeout() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000804 connection_->OnConnectionRequestTimeout(this);
805 }
806
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700807 void OnSent() override {
808 connection_->OnConnectionRequestSent(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000809 // Each request is sent only once. After a single delay , the request will
810 // time out.
811 timeout_ = true;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700812 }
813
814 int resend_delay() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000815 return CONNECTION_RESPONSE_TIMEOUT;
816 }
817
818 private:
819 Connection* connection_;
820};
821
822//
823// Connection
824//
825
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000826Connection::Connection(Port* port,
827 size_t index,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000828 const Candidate& remote_candidate)
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000829 : port_(port),
830 local_candidate_index_(index),
831 remote_candidate_(remote_candidate),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000832 write_state_(STATE_WRITE_INIT),
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700833 receiving_(false),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000834 connected_(true),
835 pruned_(false),
836 use_candidate_attr_(false),
honghaiz5a3acd82015-08-20 15:53:17 -0700837 nominated_(false),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000838 remote_ice_mode_(ICEMODE_FULL),
839 requests_(port->thread()),
840 rtt_(DEFAULT_RTT),
841 last_ping_sent_(0),
842 last_ping_received_(0),
843 last_data_received_(0),
844 last_ping_response_received_(0),
Honghai Zhang82d78622016-05-06 11:29:15 -0700845 recv_rate_tracker_(100, 10u),
846 send_rate_tracker_(100, 10u),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000847 reported_(false),
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700848 state_(STATE_WAITING),
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700849 receiving_timeout_(WEAK_CONNECTION_RECEIVE_TIMEOUT),
nisse1bffc1d2016-05-02 08:18:55 -0700850 time_created_ms_(rtc::TimeMillis()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000851 // All of our connections start in WAITING state.
852 // TODO(mallinath) - Start connections from STATE_FROZEN.
853 // Wire up to send stun packets
854 requests_.SignalSendPacket.connect(this, &Connection::OnSendStunPacket);
855 LOG_J(LS_INFO, this) << "Connection created";
856}
857
858Connection::~Connection() {
859}
860
861const Candidate& Connection::local_candidate() const {
862 ASSERT(local_candidate_index_ < port_->Candidates().size());
863 return port_->Candidates()[local_candidate_index_];
864}
865
Honghai Zhangcc411c02016-03-29 17:27:21 -0700866const Candidate& Connection::remote_candidate() const {
867 return remote_candidate_;
868}
869
Peter Boström0c4e06b2015-10-07 12:23:21 +0200870uint64_t Connection::priority() const {
871 uint64_t priority = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000872 // RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs
873 // Let G be the priority for the candidate provided by the controlling
874 // agent. Let D be the priority for the candidate provided by the
875 // controlled agent.
876 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
877 IceRole role = port_->GetIceRole();
878 if (role != ICEROLE_UNKNOWN) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200879 uint32_t g = 0;
880 uint32_t d = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000881 if (role == ICEROLE_CONTROLLING) {
882 g = local_candidate().priority();
883 d = remote_candidate_.priority();
884 } else {
885 g = remote_candidate_.priority();
886 d = local_candidate().priority();
887 }
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000888 priority = std::min(g, d);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000889 priority = priority << 32;
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000890 priority += 2 * std::max(g, d) + (g > d ? 1 : 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000891 }
892 return priority;
893}
894
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000895void Connection::set_write_state(WriteState value) {
896 WriteState old_value = write_state_;
897 write_state_ = value;
898 if (value != old_value) {
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +0000899 LOG_J(LS_VERBOSE, this) << "set_write_state from: " << old_value << " to "
900 << value;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000901 SignalStateChange(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000902 }
903}
904
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700905void Connection::set_receiving(bool value) {
906 if (value != receiving_) {
907 LOG_J(LS_VERBOSE, this) << "set_receiving to " << value;
908 receiving_ = value;
909 SignalStateChange(this);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700910 }
911}
912
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000913void Connection::set_state(State state) {
914 State old_state = state_;
915 state_ = state;
916 if (state != old_state) {
917 LOG_J(LS_VERBOSE, this) << "set_state";
918 }
919}
920
921void Connection::set_connected(bool value) {
922 bool old_value = connected_;
923 connected_ = value;
924 if (value != old_value) {
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700925 LOG_J(LS_VERBOSE, this) << "set_connected from: " << old_value << " to "
926 << value;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000927 }
928}
929
930void Connection::set_use_candidate_attr(bool enable) {
931 use_candidate_attr_ = enable;
932}
933
934void Connection::OnSendStunPacket(const void* data, size_t size,
935 StunRequest* req) {
936 rtc::PacketOptions options(port_->DefaultDscpValue());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700937 auto err = port_->SendTo(
938 data, size, remote_candidate_.address(), options, false);
939 if (err < 0) {
940 LOG_J(LS_WARNING, this) << "Failed to send STUN ping "
941 << " err=" << err
942 << " id=" << rtc::hex_encode(req->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000943 }
944}
945
946void Connection::OnReadPacket(
947 const char* data, size_t size, const rtc::PacketTime& packet_time) {
kwiberg3ec46792016-04-27 07:22:53 -0700948 std::unique_ptr<IceMessage> msg;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000949 std::string remote_ufrag;
950 const rtc::SocketAddress& addr(remote_candidate_.address());
kwiberg6baec032016-03-15 11:09:39 -0700951 if (!port_->GetStunMessage(data, size, addr, &msg, &remote_ufrag)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000952 // The packet did not parse as a valid STUN message
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700953 // This is a data packet, pass it along.
954 set_receiving(true);
nisse1bffc1d2016-05-02 08:18:55 -0700955 last_data_received_ = rtc::TimeMillis();
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700956 recv_rate_tracker_.AddSamples(size);
957 SignalReadPacket(this, data, size, packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000958
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700959 // If timed out sending writability checks, start up again
960 if (!pruned_ && (write_state_ == STATE_WRITE_TIMEOUT)) {
961 LOG(LS_WARNING) << "Received a data packet on a timed-out Connection. "
962 << "Resetting state to STATE_WRITE_INIT.";
963 set_write_state(STATE_WRITE_INIT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000964 }
965 } else if (!msg) {
966 // The packet was STUN, but failed a check and was handled internally.
967 } else {
968 // The packet is STUN and passed the Port checks.
969 // Perform our own checks to ensure this packet is valid.
honghaizd0b31432015-09-30 12:42:17 -0700970 // If this is a STUN request, then update the receiving bit and respond.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000971 // If this is a STUN response, then update the writable bit.
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700972 // Log at LS_INFO if we receive a ping on an unwritable connection.
973 rtc::LoggingSeverity sev = (!writable() ? rtc::LS_INFO : rtc::LS_VERBOSE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000974 switch (msg->type()) {
975 case STUN_BINDING_REQUEST:
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700976 LOG_JV(sev, this) << "Received STUN ping"
977 << ", id=" << rtc::hex_encode(msg->transaction_id());
978
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000979 if (remote_ufrag == remote_candidate_.username()) {
honghaiz9b5ee9c2015-11-11 13:19:17 -0800980 HandleBindingRequest(msg.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000981 } else {
982 // The packet had the right local username, but the remote username
983 // was not the right one for the remote address.
984 LOG_J(LS_ERROR, this)
985 << "Received STUN request with bad remote username "
986 << remote_ufrag;
987 port_->SendBindingErrorResponse(msg.get(), addr,
988 STUN_ERROR_UNAUTHORIZED,
989 STUN_ERROR_REASON_UNAUTHORIZED);
990
991 }
992 break;
993
994 // Response from remote peer. Does it match request sent?
995 // This doesn't just check, it makes callbacks if transaction
996 // id's match.
997 case STUN_BINDING_RESPONSE:
998 case STUN_BINDING_ERROR_RESPONSE:
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700999 if (msg->ValidateMessageIntegrity(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001000 data, size, remote_candidate().password())) {
1001 requests_.CheckResponse(msg.get());
1002 }
1003 // Otherwise silently discard the response message.
1004 break;
1005
honghaizd0b31432015-09-30 12:42:17 -07001006 // Remote end point sent an STUN indication instead of regular binding
1007 // request. In this case |last_ping_received_| will be updated but no
1008 // response will be sent.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001009 case STUN_BINDING_INDICATION:
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001010 ReceivedPing();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001011 break;
1012
1013 default:
1014 ASSERT(false);
1015 break;
1016 }
1017 }
1018}
1019
honghaiz9b5ee9c2015-11-11 13:19:17 -08001020void Connection::HandleBindingRequest(IceMessage* msg) {
1021 // This connection should now be receiving.
1022 ReceivedPing();
1023
1024 const rtc::SocketAddress& remote_addr = remote_candidate_.address();
1025 const std::string& remote_ufrag = remote_candidate_.username();
1026 // Check for role conflicts.
1027 if (!port_->MaybeIceRoleConflict(remote_addr, msg, remote_ufrag)) {
1028 // Received conflicting role from the peer.
1029 LOG(LS_INFO) << "Received conflicting role from the peer.";
1030 return;
1031 }
1032
zhihuang5ecf16c2016-06-01 17:09:15 -07001033 stats_.recv_ping_requests++;
1034
honghaiz9b5ee9c2015-11-11 13:19:17 -08001035 // This is a validated stun request from remote peer.
1036 port_->SendBindingResponse(msg, remote_addr);
1037
1038 // If it timed out on writing check, start up again
1039 if (!pruned_ && write_state_ == STATE_WRITE_TIMEOUT) {
1040 set_write_state(STATE_WRITE_INIT);
1041 }
1042
1043 if (port_->GetIceRole() == ICEROLE_CONTROLLED) {
1044 const StunByteStringAttribute* use_candidate_attr =
1045 msg->GetByteString(STUN_ATTR_USE_CANDIDATE);
1046 if (use_candidate_attr) {
1047 set_nominated(true);
1048 SignalNominated(this);
1049 }
1050 }
Honghai Zhang351d77b2016-05-20 15:08:29 -07001051 // Set the remote cost if the network_info attribute is available.
1052 // Note: If packets are re-ordered, we may get incorrect network cost
1053 // temporarily, but it should get the correct value shortly after that.
1054 const StunUInt32Attribute* network_attr =
1055 msg->GetUInt32(STUN_ATTR_NETWORK_INFO);
1056 if (network_attr) {
1057 uint32_t network_info = network_attr->value();
1058 uint16_t network_cost = static_cast<uint16_t>(network_info);
1059 if (network_cost != remote_candidate_.network_cost()) {
1060 remote_candidate_.set_network_cost(network_cost);
1061 // Network cost change will affect the connection ranking, so signal
1062 // state change to force a re-sort in P2PTransportChannel.
1063 SignalStateChange(this);
1064 }
1065 }
honghaiz9b5ee9c2015-11-11 13:19:17 -08001066}
1067
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001068void Connection::OnReadyToSend() {
1069 if (write_state_ == STATE_WRITABLE) {
1070 SignalReadyToSend(this);
1071 }
1072}
1073
1074void Connection::Prune() {
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001075 if (!pruned_ || active()) {
Honghai Zhang1590c392016-05-24 13:15:02 -07001076 LOG_J(LS_INFO, this) << "Connection pruned";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001077 pruned_ = true;
1078 requests_.Clear();
1079 set_write_state(STATE_WRITE_TIMEOUT);
1080 }
1081}
1082
1083void Connection::Destroy() {
1084 LOG_J(LS_VERBOSE, this) << "Connection destroyed";
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001085 port_->thread()->Post(this, MSG_DELETE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001086}
1087
deadbeef376e1232015-11-25 09:00:08 -08001088void Connection::FailAndDestroy() {
1089 set_state(Connection::STATE_FAILED);
1090 Destroy();
1091}
1092
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001093void Connection::PrintPingsSinceLastResponse(std::string* s, size_t max) {
1094 std::ostringstream oss;
1095 oss << std::boolalpha;
1096 if (pings_since_last_response_.size() > max) {
1097 for (size_t i = 0; i < max; i++) {
1098 const SentPing& ping = pings_since_last_response_[i];
1099 oss << rtc::hex_encode(ping.id) << " ";
1100 }
1101 oss << "... " << (pings_since_last_response_.size() - max) << " more";
1102 } else {
1103 for (const SentPing& ping : pings_since_last_response_) {
1104 oss << rtc::hex_encode(ping.id) << " ";
1105 }
1106 }
1107 *s = oss.str();
1108}
1109
honghaiz34b11eb2016-03-16 08:55:44 -07001110void Connection::UpdateState(int64_t now) {
1111 int rtt = ConservativeRTTEstimate(rtt_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001112
Peter Thatcherb2d26232015-05-15 11:25:14 -07001113 if (LOG_CHECK_LEVEL(LS_VERBOSE)) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001114 std::string pings;
1115 PrintPingsSinceLastResponse(&pings, 5);
1116 LOG_J(LS_VERBOSE, this) << "UpdateState()"
1117 << ", ms since last received response="
1118 << now - last_ping_response_received_
1119 << ", ms since last received data="
1120 << now - last_data_received_
1121 << ", rtt=" << rtt
1122 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001123 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001124
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001125 // Check the writable state. (The order of these checks is important.)
1126 //
1127 // Before becoming unwritable, we allow for a fixed number of pings to fail
1128 // (i.e., receive no response). We also have to give the response time to
1129 // get back, so we include a conservative estimate of this.
1130 //
1131 // Before timing out writability, we give a fixed amount of time. This is to
1132 // allow for changes in network conditions.
1133
1134 if ((write_state_ == STATE_WRITABLE) &&
1135 TooManyFailures(pings_since_last_response_,
1136 CONNECTION_WRITE_CONNECT_FAILURES,
1137 rtt,
1138 now) &&
1139 TooLongWithoutResponse(pings_since_last_response_,
1140 CONNECTION_WRITE_CONNECT_TIMEOUT,
1141 now)) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001142 uint32_t max_pings = CONNECTION_WRITE_CONNECT_FAILURES;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001143 LOG_J(LS_INFO, this) << "Unwritable after " << max_pings
1144 << " ping failures and "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001145 << now - pings_since_last_response_[0].sent_time
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001146 << " ms without a response,"
1147 << " ms since last received ping="
1148 << now - last_ping_received_
1149 << " ms since last received data="
1150 << now - last_data_received_
1151 << " rtt=" << rtt;
1152 set_write_state(STATE_WRITE_UNRELIABLE);
1153 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001154 if ((write_state_ == STATE_WRITE_UNRELIABLE ||
1155 write_state_ == STATE_WRITE_INIT) &&
1156 TooLongWithoutResponse(pings_since_last_response_,
1157 CONNECTION_WRITE_TIMEOUT,
1158 now)) {
1159 LOG_J(LS_INFO, this) << "Timed out after "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001160 << now - pings_since_last_response_[0].sent_time
1161 << " ms without a response"
1162 << ", rtt=" << rtt;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001163 set_write_state(STATE_WRITE_TIMEOUT);
1164 }
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001165
1166 // Check the receiving state.
honghaiz34b11eb2016-03-16 08:55:44 -07001167 int64_t last_recv_time = last_received();
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001168 bool receiving = now <= last_recv_time + receiving_timeout_;
1169 set_receiving(receiving);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001170 if (dead(now)) {
1171 Destroy();
1172 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001173}
1174
honghaiz34b11eb2016-03-16 08:55:44 -07001175void Connection::Ping(int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001176 last_ping_sent_ = now;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001177 ConnectionRequest *req = new ConnectionRequest(this);
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001178 pings_since_last_response_.push_back(SentPing(req->id(), now));
1179 LOG_J(LS_VERBOSE, this) << "Sending STUN ping "
1180 << ", id=" << rtc::hex_encode(req->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001181 requests_.Send(req);
1182 state_ = STATE_INPROGRESS;
honghaiz524ecc22016-05-25 12:48:31 -07001183 num_pings_sent_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001184}
1185
1186void Connection::ReceivedPing() {
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001187 set_receiving(true);
nisse1bffc1d2016-05-02 08:18:55 -07001188 last_ping_received_ = rtc::TimeMillis();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001189}
1190
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001191void Connection::ReceivedPingResponse() {
1192 // We've already validated that this is a STUN binding response with
1193 // the correct local and remote username for this connection.
1194 // So if we're not already, become writable. We may be bringing a pruned
1195 // connection back to life, but if we don't really want it, we can always
1196 // prune it again.
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001197 set_receiving(true);
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001198 set_write_state(STATE_WRITABLE);
1199 set_state(STATE_SUCCEEDED);
1200 pings_since_last_response_.clear();
nisse1bffc1d2016-05-02 08:18:55 -07001201 last_ping_response_received_ = rtc::TimeMillis();
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001202}
1203
honghaiz34b11eb2016-03-16 08:55:44 -07001204bool Connection::dead(int64_t now) const {
honghaiz37389b42016-01-04 21:57:33 -08001205 if (last_received() > 0) {
1206 // If it has ever received anything, we keep it alive until it hasn't
1207 // received anything for DEAD_CONNECTION_RECEIVE_TIMEOUT. This covers the
1208 // normal case of a successfully used connection that stops working. This
1209 // also allows a remote peer to continue pinging over a locally inactive
1210 // (pruned) connection.
1211 return (now > (last_received() + DEAD_CONNECTION_RECEIVE_TIMEOUT));
1212 }
1213
1214 if (active()) {
1215 // If it has never received anything, keep it alive as long as it is
1216 // actively pinging and not pruned. Otherwise, the connection might be
1217 // deleted before it has a chance to ping. This is the normal case for a
1218 // new connection that is pinging but hasn't received anything yet.
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001219 return false;
1220 }
1221
honghaiz37389b42016-01-04 21:57:33 -08001222 // If it has never received anything and is not actively pinging (pruned), we
1223 // keep it around for at least MIN_CONNECTION_LIFETIME to prevent connections
1224 // from being pruned too quickly during a network change event when two
1225 // networks would be up simultaneously but only for a brief period.
1226 return now > (time_created_ms_ + MIN_CONNECTION_LIFETIME);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001227}
1228
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +00001229std::string Connection::ToDebugId() const {
1230 std::stringstream ss;
1231 ss << std::hex << this;
1232 return ss.str();
1233}
1234
honghaize1a0c942016-02-16 14:54:56 -08001235uint32_t Connection::ComputeNetworkCost() const {
1236 // TODO(honghaiz): Will add rtt as part of the network cost.
Honghai Zhang351d77b2016-05-20 15:08:29 -07001237 return port()->network_cost() + remote_candidate_.network_cost();
honghaize1a0c942016-02-16 14:54:56 -08001238}
1239
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001240std::string Connection::ToString() const {
1241 const char CONNECT_STATE_ABBREV[2] = {
1242 '-', // not connected (false)
1243 'C', // connected (true)
1244 };
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001245 const char RECEIVE_STATE_ABBREV[2] = {
1246 '-', // not receiving (false)
1247 'R', // receiving (true)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001248 };
1249 const char WRITE_STATE_ABBREV[4] = {
1250 'W', // STATE_WRITABLE
1251 'w', // STATE_WRITE_UNRELIABLE
1252 '-', // STATE_WRITE_INIT
1253 'x', // STATE_WRITE_TIMEOUT
1254 };
1255 const std::string ICESTATE[4] = {
1256 "W", // STATE_WAITING
1257 "I", // STATE_INPROGRESS
1258 "S", // STATE_SUCCEEDED
1259 "F" // STATE_FAILED
1260 };
1261 const Candidate& local = local_candidate();
1262 const Candidate& remote = remote_candidate();
1263 std::stringstream ss;
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +00001264 ss << "Conn[" << ToDebugId()
1265 << ":" << port_->content_name()
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001266 << ":" << local.id() << ":" << local.component()
1267 << ":" << local.generation()
1268 << ":" << local.type() << ":" << local.protocol()
1269 << ":" << local.address().ToSensitiveString()
1270 << "->" << remote.id() << ":" << remote.component()
1271 << ":" << remote.priority()
1272 << ":" << remote.type() << ":"
1273 << remote.protocol() << ":" << remote.address().ToSensitiveString() << "|"
1274 << CONNECT_STATE_ABBREV[connected()]
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001275 << RECEIVE_STATE_ABBREV[receiving()]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001276 << WRITE_STATE_ABBREV[write_state()]
1277 << ICESTATE[state()] << "|"
1278 << priority() << "|";
1279 if (rtt_ < DEFAULT_RTT) {
1280 ss << rtt_ << "]";
1281 } else {
1282 ss << "-]";
1283 }
1284 return ss.str();
1285}
1286
1287std::string Connection::ToSensitiveString() const {
1288 return ToString();
1289}
1290
1291void Connection::OnConnectionRequestResponse(ConnectionRequest* request,
1292 StunMessage* response) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001293 // Log at LS_INFO if we receive a ping response on an unwritable
1294 // connection.
1295 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1296
honghaiz34b11eb2016-03-16 08:55:44 -07001297 int rtt = request->Elapsed();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001298
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001299 ReceivedPingResponse();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001300
Peter Thatcherb2d26232015-05-15 11:25:14 -07001301 if (LOG_CHECK_LEVEL_V(sev)) {
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001302 bool use_candidate = (
1303 response->GetByteString(STUN_ATTR_USE_CANDIDATE) != nullptr);
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001304 std::string pings;
1305 PrintPingsSinceLastResponse(&pings, 5);
1306 LOG_JV(sev, this) << "Received STUN ping response"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001307 << ", id=" << rtc::hex_encode(request->id())
1308 << ", code=0" // Makes logging easier to parse.
1309 << ", rtt=" << rtt
1310 << ", use_candidate=" << use_candidate
1311 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001312 }
1313
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001314 rtt_ = (RTT_RATIO * rtt_ + rtt) / (RTT_RATIO + 1);
zhihuang5ecf16c2016-06-01 17:09:15 -07001315 stats_.recv_ping_responses++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001316
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001317 MaybeAddPrflxCandidate(request, response);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001318}
1319
1320void Connection::OnConnectionRequestErrorResponse(ConnectionRequest* request,
1321 StunMessage* response) {
1322 const StunErrorCodeAttribute* error_attr = response->GetErrorCode();
1323 int error_code = STUN_ERROR_GLOBAL_FAILURE;
1324 if (error_attr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001325 error_code = error_attr->code();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001326 }
1327
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001328 LOG_J(LS_INFO, this) << "Received STUN error response"
1329 << " id=" << rtc::hex_encode(request->id())
1330 << " code=" << error_code
1331 << " rtt=" << request->Elapsed();
1332
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001333 if (error_code == STUN_ERROR_UNKNOWN_ATTRIBUTE ||
1334 error_code == STUN_ERROR_SERVER_ERROR ||
1335 error_code == STUN_ERROR_UNAUTHORIZED) {
1336 // Recoverable error, retry
1337 } else if (error_code == STUN_ERROR_STALE_CREDENTIALS) {
1338 // Race failure, retry
1339 } else if (error_code == STUN_ERROR_ROLE_CONFLICT) {
1340 HandleRoleConflictFromPeer();
1341 } else {
1342 // This is not a valid connection.
1343 LOG_J(LS_ERROR, this) << "Received STUN error response, code="
1344 << error_code << "; killing connection";
deadbeef376e1232015-11-25 09:00:08 -08001345 FailAndDestroy();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001346 }
1347}
1348
1349void Connection::OnConnectionRequestTimeout(ConnectionRequest* request) {
1350 // Log at LS_INFO if we miss a ping on a writable connection.
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001351 rtc::LoggingSeverity sev = writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1352 LOG_JV(sev, this) << "Timing-out STUN ping "
1353 << rtc::hex_encode(request->id())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001354 << " after " << request->Elapsed() << " ms";
1355}
1356
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001357void Connection::OnConnectionRequestSent(ConnectionRequest* request) {
1358 // Log at LS_INFO if we send a ping on an unwritable connection.
1359 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001360 bool use_candidate = use_candidate_attr();
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001361 LOG_JV(sev, this) << "Sent STUN ping"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001362 << ", id=" << rtc::hex_encode(request->id())
1363 << ", use_candidate=" << use_candidate;
zhihuang5ecf16c2016-06-01 17:09:15 -07001364 stats_.sent_ping_requests_total++;
1365 if (stats_.recv_ping_responses == 0) {
1366 stats_.sent_ping_requests_before_first_response++;
1367 }
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001368}
1369
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001370void Connection::HandleRoleConflictFromPeer() {
1371 port_->SignalRoleConflict(port_);
1372}
1373
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001374void Connection::MaybeSetRemoteIceCredentialsAndGeneration(
1375 const std::string& ice_ufrag,
1376 const std::string& ice_pwd,
1377 int generation) {
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001378 if (remote_candidate_.username() == ice_ufrag &&
1379 remote_candidate_.password().empty()) {
1380 remote_candidate_.set_password(ice_pwd);
1381 }
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001382 // TODO(deadbeef): A value of '0' for the generation is used for both
1383 // generation 0 and "generation unknown". It should be changed to an
1384 // rtc::Optional to fix this.
1385 if (remote_candidate_.username() == ice_ufrag &&
1386 remote_candidate_.password() == ice_pwd &&
1387 remote_candidate_.generation() == 0) {
1388 remote_candidate_.set_generation(generation);
1389 }
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001390}
1391
1392void Connection::MaybeUpdatePeerReflexiveCandidate(
1393 const Candidate& new_candidate) {
1394 if (remote_candidate_.type() == PRFLX_PORT_TYPE &&
1395 new_candidate.type() != PRFLX_PORT_TYPE &&
1396 remote_candidate_.protocol() == new_candidate.protocol() &&
1397 remote_candidate_.address() == new_candidate.address() &&
1398 remote_candidate_.username() == new_candidate.username() &&
1399 remote_candidate_.password() == new_candidate.password() &&
1400 remote_candidate_.generation() == new_candidate.generation()) {
1401 remote_candidate_ = new_candidate;
1402 }
1403}
1404
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001405void Connection::OnMessage(rtc::Message *pmsg) {
1406 ASSERT(pmsg->message_id == MSG_DELETE);
honghaiz524ecc22016-05-25 12:48:31 -07001407 LOG_J(LS_INFO, this) << "Connection deleted with number of pings sent: "
1408 << num_pings_sent_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001409 SignalDestroyed(this);
1410 delete this;
1411}
1412
honghaiz34b11eb2016-03-16 08:55:44 -07001413int64_t Connection::last_received() const {
Peter Thatcher54360512015-07-08 11:08:35 -07001414 return std::max(last_data_received_,
1415 std::max(last_ping_received_, last_ping_response_received_));
1416}
1417
zhihuang5ecf16c2016-06-01 17:09:15 -07001418ConnectionInfo Connection::stats() {
1419 stats_.recv_bytes_second = round(recv_rate_tracker_.ComputeRate());
1420 stats_.recv_total_bytes = recv_rate_tracker_.TotalSampleCount();
1421 stats_.sent_bytes_second = round(send_rate_tracker_.ComputeRate());
1422 stats_.sent_total_bytes = send_rate_tracker_.TotalSampleCount();
1423 return stats_;
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001424}
1425
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001426void Connection::MaybeAddPrflxCandidate(ConnectionRequest* request,
1427 StunMessage* response) {
1428 // RFC 5245
1429 // The agent checks the mapped address from the STUN response. If the
1430 // transport address does not match any of the local candidates that the
1431 // agent knows about, the mapped address represents a new candidate -- a
1432 // peer reflexive candidate.
1433 const StunAddressAttribute* addr =
1434 response->GetAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
1435 if (!addr) {
1436 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1437 << "No MAPPED-ADDRESS or XOR-MAPPED-ADDRESS found in the "
1438 << "stun response message";
1439 return;
1440 }
1441
1442 bool known_addr = false;
1443 for (size_t i = 0; i < port_->Candidates().size(); ++i) {
1444 if (port_->Candidates()[i].address() == addr->GetAddress()) {
1445 known_addr = true;
1446 break;
1447 }
1448 }
1449 if (known_addr) {
1450 return;
1451 }
1452
1453 // RFC 5245
1454 // Its priority is set equal to the value of the PRIORITY attribute
1455 // in the Binding request.
1456 const StunUInt32Attribute* priority_attr =
1457 request->msg()->GetUInt32(STUN_ATTR_PRIORITY);
1458 if (!priority_attr) {
1459 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1460 << "No STUN_ATTR_PRIORITY found in the "
1461 << "stun response message";
1462 return;
1463 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001464 const uint32_t priority = priority_attr->value();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001465 std::string id = rtc::CreateRandomString(8);
1466
1467 Candidate new_local_candidate;
1468 new_local_candidate.set_id(id);
1469 new_local_candidate.set_component(local_candidate().component());
1470 new_local_candidate.set_type(PRFLX_PORT_TYPE);
1471 new_local_candidate.set_protocol(local_candidate().protocol());
1472 new_local_candidate.set_address(addr->GetAddress());
1473 new_local_candidate.set_priority(priority);
1474 new_local_candidate.set_username(local_candidate().username());
1475 new_local_candidate.set_password(local_candidate().password());
1476 new_local_candidate.set_network_name(local_candidate().network_name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001477 new_local_candidate.set_network_type(local_candidate().network_type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001478 new_local_candidate.set_related_address(local_candidate().address());
Honghai Zhang80f1db92016-01-27 11:54:45 -08001479 new_local_candidate.set_foundation(ComputeFoundation(
1480 PRFLX_PORT_TYPE, local_candidate().protocol(),
1481 local_candidate().relay_protocol(), local_candidate().address()));
honghaiza0c44ea2016-03-23 16:07:48 -07001482 new_local_candidate.set_network_id(local_candidate().network_id());
1483 new_local_candidate.set_network_cost(local_candidate().network_cost());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001484
1485 // Change the local candidate of this Connection to the new prflx candidate.
1486 local_candidate_index_ = port_->AddPrflxCandidate(new_local_candidate);
1487
1488 // SignalStateChange to force a re-sort in P2PTransportChannel as this
1489 // Connection's local candidate has changed.
1490 SignalStateChange(this);
1491}
1492
deadbeef376e1232015-11-25 09:00:08 -08001493ProxyConnection::ProxyConnection(Port* port,
1494 size_t index,
1495 const Candidate& remote_candidate)
1496 : Connection(port, index, remote_candidate) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001497
1498int ProxyConnection::Send(const void* data, size_t size,
1499 const rtc::PacketOptions& options) {
1500 if (write_state_ == STATE_WRITE_INIT || write_state_ == STATE_WRITE_TIMEOUT) {
1501 error_ = EWOULDBLOCK;
1502 return SOCKET_ERROR;
1503 }
zhihuang5ecf16c2016-06-01 17:09:15 -07001504 stats_.sent_total_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001505 int sent = port_->SendTo(data, size, remote_candidate_.address(),
1506 options, true);
1507 if (sent <= 0) {
1508 ASSERT(sent < 0);
1509 error_ = port_->GetError();
zhihuang5ecf16c2016-06-01 17:09:15 -07001510 stats_.sent_discarded_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001511 } else {
Tim Psiaki63046262015-09-14 10:38:08 -07001512 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001513 }
1514 return sent;
1515}
1516
1517} // namespace cricket