blob: b6173ebf45768be331c589631f81f9aee8ccbc80 [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "webrtc/p2p/base/port.h"
12
13#include <algorithm>
14#include <vector>
15
16#include "webrtc/p2p/base/common.h"
17#include "webrtc/p2p/base/portallocator.h"
18#include "webrtc/base/base64.h"
19#include "webrtc/base/crc32.h"
20#include "webrtc/base/helpers.h"
21#include "webrtc/base/logging.h"
22#include "webrtc/base/messagedigest.h"
honghaize3c6c822016-02-17 13:00:28 -080023#include "webrtc/base/network.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000024#include "webrtc/base/stringencode.h"
25#include "webrtc/base/stringutils.h"
26
27namespace {
28
29// Determines whether we have seen at least the given maximum number of
30// pings fail to have a response.
31inline bool TooManyFailures(
Peter Thatcher1cf6f812015-05-15 10:40:45 -070032 const std::vector<cricket::Connection::SentPing>& pings_since_last_response,
Peter Boström0c4e06b2015-10-07 12:23:21 +020033 uint32_t maximum_failures,
honghaiz34b11eb2016-03-16 08:55:44 -070034 int rtt_estimate,
35 int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000036 // If we haven't sent that many pings, then we can't have failed that many.
37 if (pings_since_last_response.size() < maximum_failures)
38 return false;
39
40 // Check if the window in which we would expect a response to the ping has
41 // already elapsed.
honghaiz34b11eb2016-03-16 08:55:44 -070042 int64_t expected_response_time =
Peter Thatcher1cf6f812015-05-15 10:40:45 -070043 pings_since_last_response[maximum_failures - 1].sent_time + rtt_estimate;
44 return now > expected_response_time;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000045}
46
47// Determines whether we have gone too long without seeing any response.
48inline bool TooLongWithoutResponse(
Peter Thatcher1cf6f812015-05-15 10:40:45 -070049 const std::vector<cricket::Connection::SentPing>& pings_since_last_response,
honghaiz34b11eb2016-03-16 08:55:44 -070050 int64_t maximum_time,
51 int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000052 if (pings_since_last_response.size() == 0)
53 return false;
54
Peter Thatcher1cf6f812015-05-15 10:40:45 -070055 auto first = pings_since_last_response[0];
56 return now > (first.sent_time + maximum_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000057}
58
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000059// We will restrict RTT estimates (when used for determining state) to be
60// within a reasonable range.
honghaiz34b11eb2016-03-16 08:55:44 -070061const int MINIMUM_RTT = 100; // 0.1 seconds
62const int MAXIMUM_RTT = 3000; // 3 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000063
64// When we don't have any RTT data, we have to pick something reasonable. We
65// use a large value just in case the connection is really slow.
honghaiz34b11eb2016-03-16 08:55:44 -070066const int DEFAULT_RTT = MAXIMUM_RTT;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000067
68// Computes our estimate of the RTT given the current estimate.
honghaiz34b11eb2016-03-16 08:55:44 -070069inline int ConservativeRTTEstimate(int rtt) {
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000070 return std::max(MINIMUM_RTT, std::min(MAXIMUM_RTT, 2 * rtt));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000071}
72
73// Weighting of the old rtt value to new data.
74const int RTT_RATIO = 3; // 3 : 1
75
76// The delay before we begin checking if this port is useless.
77const int kPortTimeoutDelay = 30 * 1000; // 30 seconds
Honghai Zhang351d77b2016-05-20 15:08:29 -070078} // namespace
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000079
80namespace cricket {
81
82// TODO(ronghuawu): Use "host", "srflx", "prflx" and "relay". But this requires
83// the signaling part be updated correspondingly as well.
84const char LOCAL_PORT_TYPE[] = "local";
85const char STUN_PORT_TYPE[] = "stun";
86const char PRFLX_PORT_TYPE[] = "prflx";
87const char RELAY_PORT_TYPE[] = "relay";
88
89const char UDP_PROTOCOL_NAME[] = "udp";
90const char TCP_PROTOCOL_NAME[] = "tcp";
91const char SSLTCP_PROTOCOL_NAME[] = "ssltcp";
92
93static const char* const PROTO_NAMES[] = { UDP_PROTOCOL_NAME,
94 TCP_PROTOCOL_NAME,
95 SSLTCP_PROTOCOL_NAME };
96
97const char* ProtoToString(ProtocolType proto) {
98 return PROTO_NAMES[proto];
99}
100
101bool StringToProto(const char* value, ProtocolType* proto) {
102 for (size_t i = 0; i <= PROTO_LAST; ++i) {
103 if (_stricmp(PROTO_NAMES[i], value) == 0) {
104 *proto = static_cast<ProtocolType>(i);
105 return true;
106 }
107 }
108 return false;
109}
110
111// RFC 6544, TCP candidate encoding rules.
112const int DISCARD_PORT = 9;
113const char TCPTYPE_ACTIVE_STR[] = "active";
114const char TCPTYPE_PASSIVE_STR[] = "passive";
115const char TCPTYPE_SIMOPEN_STR[] = "so";
116
117// Foundation: An arbitrary string that is the same for two candidates
118// that have the same type, base IP address, protocol (UDP, TCP,
119// etc.), and STUN or TURN server. If any of these are different,
120// then the foundation will be different. Two candidate pairs with
121// the same foundation pairs are likely to have similar network
122// characteristics. Foundations are used in the frozen algorithm.
Honghai Zhang80f1db92016-01-27 11:54:45 -0800123static std::string ComputeFoundation(const std::string& type,
124 const std::string& protocol,
125 const std::string& relay_protocol,
126 const rtc::SocketAddress& base_address) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000127 std::ostringstream ost;
Honghai Zhang80f1db92016-01-27 11:54:45 -0800128 ost << type << base_address.ipaddr().ToString() << protocol << relay_protocol;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200129 return rtc::ToString<uint32_t>(rtc::ComputeCrc32(ost.str()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000130}
131
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000132Port::Port(rtc::Thread* thread,
Honghai Zhangd00c0572016-06-28 09:44:47 -0700133 const std::string& type,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000134 rtc::PacketSocketFactory* factory,
135 rtc::Network* network,
136 const rtc::IPAddress& ip,
137 const std::string& username_fragment,
138 const std::string& password)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000139 : thread_(thread),
140 factory_(factory),
Honghai Zhangd00c0572016-06-28 09:44:47 -0700141 type_(type),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000142 send_retransmit_count_attribute_(false),
143 network_(network),
144 ip_(ip),
145 min_port_(0),
146 max_port_(0),
147 component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
148 generation_(0),
149 ice_username_fragment_(username_fragment),
150 password_(password),
151 timeout_delay_(kPortTimeoutDelay),
152 enable_port_packets_(false),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000153 ice_role_(ICEROLE_UNKNOWN),
154 tiebreaker_(0),
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700155 shared_socket_(true) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000156 Construct();
157}
158
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000159Port::Port(rtc::Thread* thread,
160 const std::string& type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000161 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000162 rtc::Network* network,
163 const rtc::IPAddress& ip,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200164 uint16_t min_port,
165 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000166 const std::string& username_fragment,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000167 const std::string& password)
168 : thread_(thread),
169 factory_(factory),
170 type_(type),
171 send_retransmit_count_attribute_(false),
172 network_(network),
173 ip_(ip),
174 min_port_(min_port),
175 max_port_(max_port),
176 component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
177 generation_(0),
178 ice_username_fragment_(username_fragment),
179 password_(password),
180 timeout_delay_(kPortTimeoutDelay),
181 enable_port_packets_(false),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000182 ice_role_(ICEROLE_UNKNOWN),
183 tiebreaker_(0),
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700184 shared_socket_(false) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000185 ASSERT(factory_ != NULL);
186 Construct();
187}
188
189void Port::Construct() {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700190 // TODO(pthatcher): Remove this old behavior once we're sure no one
191 // relies on it. If the username_fragment and password are empty,
192 // we should just create one.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000193 if (ice_username_fragment_.empty()) {
194 ASSERT(password_.empty());
195 ice_username_fragment_ = rtc::CreateRandomString(ICE_UFRAG_LENGTH);
196 password_ = rtc::CreateRandomString(ICE_PWD_LENGTH);
197 }
Honghai Zhang351d77b2016-05-20 15:08:29 -0700198 network_->SignalTypeChanged.connect(this, &Port::OnNetworkTypeChanged);
199 network_cost_ = network_->GetCost();
honghaize1a0c942016-02-16 14:54:56 -0800200
Honghai Zhang351d77b2016-05-20 15:08:29 -0700201 LOG_J(LS_INFO, this) << "Port created with network cost " << network_cost_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000202}
203
204Port::~Port() {
205 // Delete all of the remaining connections. We copy the list up front
206 // because each deletion will cause it to be modified.
207
208 std::vector<Connection*> list;
209
210 AddressMap::iterator iter = connections_.begin();
211 while (iter != connections_.end()) {
212 list.push_back(iter->second);
213 ++iter;
214 }
215
Peter Boström0c4e06b2015-10-07 12:23:21 +0200216 for (uint32_t i = 0; i < list.size(); i++)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000217 delete list[i];
218}
219
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700220void Port::SetIceParameters(int component,
221 const std::string& username_fragment,
222 const std::string& password) {
223 component_ = component;
224 ice_username_fragment_ = username_fragment;
225 password_ = password;
226 for (Candidate& c : candidates_) {
227 c.set_component(component);
228 c.set_username(username_fragment);
229 c.set_password(password);
230 }
231}
232
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000233Connection* Port::GetConnection(const rtc::SocketAddress& remote_addr) {
234 AddressMap::const_iterator iter = connections_.find(remote_addr);
235 if (iter != connections_.end())
236 return iter->second;
237 else
238 return NULL;
239}
240
241void Port::AddAddress(const rtc::SocketAddress& address,
242 const rtc::SocketAddress& base_address,
243 const rtc::SocketAddress& related_address,
244 const std::string& protocol,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700245 const std::string& relay_protocol,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000246 const std::string& tcptype,
247 const std::string& type,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200248 uint32_t type_preference,
249 uint32_t relay_preference,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000250 bool final) {
251 if (protocol == TCP_PROTOCOL_NAME && type == LOCAL_PORT_TYPE) {
252 ASSERT(!tcptype.empty());
253 }
254
honghaiza0c44ea2016-03-23 16:07:48 -0700255 std::string foundation =
256 ComputeFoundation(type, protocol, relay_protocol, base_address);
257 Candidate c(component_, protocol, address, 0U, username_fragment(), password_,
258 type, generation_, foundation, network_->id(), network_cost_);
259 c.set_priority(
260 c.GetPriority(type_preference, network_->preference(), relay_preference));
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700261 c.set_relay_protocol(relay_protocol);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000262 c.set_tcptype(tcptype);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000263 c.set_network_name(network_->name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +0000264 c.set_network_type(network_->type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000265 c.set_related_address(related_address);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000266 candidates_.push_back(c);
267 SignalCandidateReady(this, c);
268
269 if (final) {
270 SignalPortComplete(this);
271 }
272}
273
honghaiz36f50e82016-06-01 15:57:03 -0700274void Port::AddOrReplaceConnection(Connection* conn) {
275 auto ret = connections_.insert(
276 std::make_pair(conn->remote_candidate().address(), conn));
277 // If there is a different connection on the same remote address, replace
278 // it with the new one and destroy the old one.
279 if (ret.second == false && ret.first->second != conn) {
280 LOG_J(LS_WARNING, this)
281 << "A new connection was created on an existing remote address. "
282 << "New remote candidate: " << conn->remote_candidate().ToString();
283 ret.first->second->SignalDestroyed.disconnect(this);
284 ret.first->second->Destroy();
285 ret.first->second = conn;
286 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000287 conn->SignalDestroyed.connect(this, &Port::OnConnectionDestroyed);
288 SignalConnectionCreated(this, conn);
289}
290
291void Port::OnReadPacket(
292 const char* data, size_t size, const rtc::SocketAddress& addr,
293 ProtocolType proto) {
294 // If the user has enabled port packets, just hand this over.
295 if (enable_port_packets_) {
296 SignalReadPacket(this, data, size, addr);
297 return;
298 }
299
300 // If this is an authenticated STUN request, then signal unknown address and
301 // send back a proper binding response.
kwiberg3ec46792016-04-27 07:22:53 -0700302 std::unique_ptr<IceMessage> msg;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000303 std::string remote_username;
kwiberg6baec032016-03-15 11:09:39 -0700304 if (!GetStunMessage(data, size, addr, &msg, &remote_username)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000305 LOG_J(LS_ERROR, this) << "Received non-STUN packet from unknown address ("
306 << addr.ToSensitiveString() << ")";
307 } else if (!msg) {
308 // STUN message handled already
309 } else if (msg->type() == STUN_BINDING_REQUEST) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700310 LOG(LS_INFO) << "Received STUN ping "
311 << " id=" << rtc::hex_encode(msg->transaction_id())
312 << " from unknown address " << addr.ToSensitiveString();
313
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000314 // Check for role conflicts.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700315 if (!MaybeIceRoleConflict(addr, msg.get(), remote_username)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000316 LOG(LS_INFO) << "Received conflicting role from the peer.";
317 return;
318 }
319
320 SignalUnknownAddress(this, addr, proto, msg.get(), remote_username, false);
321 } else {
322 // NOTE(tschmelcher): STUN_BINDING_RESPONSE is benign. It occurs if we
323 // pruned a connection for this port while it had STUN requests in flight,
324 // because we then get back responses for them, which this code correctly
325 // does not handle.
326 if (msg->type() != STUN_BINDING_RESPONSE) {
327 LOG_J(LS_ERROR, this) << "Received unexpected STUN message type ("
328 << msg->type() << ") from unknown address ("
329 << addr.ToSensitiveString() << ")";
330 }
331 }
332}
333
334void Port::OnReadyToSend() {
335 AddressMap::iterator iter = connections_.begin();
336 for (; iter != connections_.end(); ++iter) {
337 iter->second->OnReadyToSend();
338 }
339}
340
341size_t Port::AddPrflxCandidate(const Candidate& local) {
342 candidates_.push_back(local);
343 return (candidates_.size() - 1);
344}
345
kwiberg6baec032016-03-15 11:09:39 -0700346bool Port::GetStunMessage(const char* data,
347 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000348 const rtc::SocketAddress& addr,
kwiberg3ec46792016-04-27 07:22:53 -0700349 std::unique_ptr<IceMessage>* out_msg,
kwiberg6baec032016-03-15 11:09:39 -0700350 std::string* out_username) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000351 // NOTE: This could clearly be optimized to avoid allocating any memory.
352 // However, at the data rates we'll be looking at on the client side,
353 // this probably isn't worth worrying about.
354 ASSERT(out_msg != NULL);
355 ASSERT(out_username != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000356 out_username->clear();
357
358 // Don't bother parsing the packet if we can tell it's not STUN.
359 // In ICE mode, all STUN packets will have a valid fingerprint.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700360 if (!StunMessage::ValidateFingerprint(data, size)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000361 return false;
362 }
363
364 // Parse the request message. If the packet is not a complete and correct
365 // STUN message, then ignore it.
kwiberg3ec46792016-04-27 07:22:53 -0700366 std::unique_ptr<IceMessage> stun_msg(new IceMessage());
jbauchf1f87202016-03-30 06:43:37 -0700367 rtc::ByteBufferReader buf(data, size);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000368 if (!stun_msg->Read(&buf) || (buf.Length() > 0)) {
369 return false;
370 }
371
372 if (stun_msg->type() == STUN_BINDING_REQUEST) {
373 // Check for the presence of USERNAME and MESSAGE-INTEGRITY (if ICE) first.
374 // If not present, fail with a 400 Bad Request.
375 if (!stun_msg->GetByteString(STUN_ATTR_USERNAME) ||
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700376 !stun_msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000377 LOG_J(LS_ERROR, this) << "Received STUN request without username/M-I "
378 << "from " << addr.ToSensitiveString();
379 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_BAD_REQUEST,
380 STUN_ERROR_REASON_BAD_REQUEST);
381 return true;
382 }
383
384 // If the username is bad or unknown, fail with a 401 Unauthorized.
385 std::string local_ufrag;
386 std::string remote_ufrag;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700387 if (!ParseStunUsername(stun_msg.get(), &local_ufrag, &remote_ufrag) ||
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000388 local_ufrag != username_fragment()) {
389 LOG_J(LS_ERROR, this) << "Received STUN request with bad local username "
390 << local_ufrag << " from "
391 << addr.ToSensitiveString();
392 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
393 STUN_ERROR_REASON_UNAUTHORIZED);
394 return true;
395 }
396
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000397 // If ICE, and the MESSAGE-INTEGRITY is bad, fail with a 401 Unauthorized
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700398 if (!stun_msg->ValidateMessageIntegrity(data, size, password_)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000399 LOG_J(LS_ERROR, this) << "Received STUN request with bad M-I "
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +0000400 << "from " << addr.ToSensitiveString()
401 << ", password_=" << password_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000402 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
403 STUN_ERROR_REASON_UNAUTHORIZED);
404 return true;
405 }
406 out_username->assign(remote_ufrag);
407 } else if ((stun_msg->type() == STUN_BINDING_RESPONSE) ||
408 (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE)) {
409 if (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE) {
410 if (const StunErrorCodeAttribute* error_code = stun_msg->GetErrorCode()) {
411 LOG_J(LS_ERROR, this) << "Received STUN binding error:"
412 << " class=" << error_code->eclass()
413 << " number=" << error_code->number()
414 << " reason='" << error_code->reason() << "'"
415 << " from " << addr.ToSensitiveString();
416 // Return message to allow error-specific processing
417 } else {
418 LOG_J(LS_ERROR, this) << "Received STUN binding error without a error "
419 << "code from " << addr.ToSensitiveString();
420 return true;
421 }
422 }
423 // NOTE: Username should not be used in verifying response messages.
424 out_username->clear();
425 } else if (stun_msg->type() == STUN_BINDING_INDICATION) {
426 LOG_J(LS_VERBOSE, this) << "Received STUN binding indication:"
427 << " from " << addr.ToSensitiveString();
428 out_username->clear();
429 // No stun attributes will be verified, if it's stun indication message.
430 // Returning from end of the this method.
431 } else {
432 LOG_J(LS_ERROR, this) << "Received STUN packet with invalid type ("
433 << stun_msg->type() << ") from "
434 << addr.ToSensitiveString();
435 return true;
436 }
437
438 // Return the STUN message found.
kwiberg6baec032016-03-15 11:09:39 -0700439 *out_msg = std::move(stun_msg);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000440 return true;
441}
442
443bool Port::IsCompatibleAddress(const rtc::SocketAddress& addr) {
444 int family = ip().family();
445 // We use single-stack sockets, so families must match.
446 if (addr.family() != family) {
447 return false;
448 }
449 // Link-local IPv6 ports can only connect to other link-local IPv6 ports.
Peter Thatcherb8b01432015-07-07 16:45:53 -0700450 if (family == AF_INET6 &&
451 (IPIsLinkLocal(ip()) != IPIsLinkLocal(addr.ipaddr()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000452 return false;
453 }
454 return true;
455}
456
457bool Port::ParseStunUsername(const StunMessage* stun_msg,
458 std::string* local_ufrag,
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700459 std::string* remote_ufrag) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000460 // The packet must include a username that either begins or ends with our
461 // fragment. It should begin with our fragment if it is a request and it
462 // should end with our fragment if it is a response.
463 local_ufrag->clear();
464 remote_ufrag->clear();
465 const StunByteStringAttribute* username_attr =
466 stun_msg->GetByteString(STUN_ATTR_USERNAME);
467 if (username_attr == NULL)
468 return false;
469
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700470 // RFRAG:LFRAG
471 const std::string username = username_attr->GetString();
472 size_t colon_pos = username.find(":");
473 if (colon_pos == std::string::npos) {
474 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000475 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000476
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700477 *local_ufrag = username.substr(0, colon_pos);
478 *remote_ufrag = username.substr(colon_pos + 1, username.size());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000479 return true;
480}
481
482bool Port::MaybeIceRoleConflict(
483 const rtc::SocketAddress& addr, IceMessage* stun_msg,
484 const std::string& remote_ufrag) {
485 // Validate ICE_CONTROLLING or ICE_CONTROLLED attributes.
486 bool ret = true;
487 IceRole remote_ice_role = ICEROLE_UNKNOWN;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200488 uint64_t remote_tiebreaker = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000489 const StunUInt64Attribute* stun_attr =
490 stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
491 if (stun_attr) {
492 remote_ice_role = ICEROLE_CONTROLLING;
493 remote_tiebreaker = stun_attr->value();
494 }
495
496 // If |remote_ufrag| is same as port local username fragment and
497 // tie breaker value received in the ping message matches port
498 // tiebreaker value this must be a loopback call.
499 // We will treat this as valid scenario.
500 if (remote_ice_role == ICEROLE_CONTROLLING &&
501 username_fragment() == remote_ufrag &&
502 remote_tiebreaker == IceTiebreaker()) {
503 return true;
504 }
505
506 stun_attr = stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
507 if (stun_attr) {
508 remote_ice_role = ICEROLE_CONTROLLED;
509 remote_tiebreaker = stun_attr->value();
510 }
511
512 switch (ice_role_) {
513 case ICEROLE_CONTROLLING:
514 if (ICEROLE_CONTROLLING == remote_ice_role) {
515 if (remote_tiebreaker >= tiebreaker_) {
516 SignalRoleConflict(this);
517 } else {
518 // Send Role Conflict (487) error response.
519 SendBindingErrorResponse(stun_msg, addr,
520 STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
521 ret = false;
522 }
523 }
524 break;
525 case ICEROLE_CONTROLLED:
526 if (ICEROLE_CONTROLLED == remote_ice_role) {
527 if (remote_tiebreaker < tiebreaker_) {
528 SignalRoleConflict(this);
529 } else {
530 // Send Role Conflict (487) error response.
531 SendBindingErrorResponse(stun_msg, addr,
532 STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
533 ret = false;
534 }
535 }
536 break;
537 default:
538 ASSERT(false);
539 }
540 return ret;
541}
542
543void Port::CreateStunUsername(const std::string& remote_username,
544 std::string* stun_username_attr_str) const {
545 stun_username_attr_str->clear();
546 *stun_username_attr_str = remote_username;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700547 stun_username_attr_str->append(":");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000548 stun_username_attr_str->append(username_fragment());
549}
550
551void Port::SendBindingResponse(StunMessage* request,
552 const rtc::SocketAddress& addr) {
553 ASSERT(request->type() == STUN_BINDING_REQUEST);
554
555 // Retrieve the username from the request.
556 const StunByteStringAttribute* username_attr =
557 request->GetByteString(STUN_ATTR_USERNAME);
558 ASSERT(username_attr != NULL);
559 if (username_attr == NULL) {
560 // No valid username, skip the response.
561 return;
562 }
563
564 // Fill in the response message.
565 StunMessage response;
566 response.SetType(STUN_BINDING_RESPONSE);
567 response.SetTransactionID(request->transaction_id());
568 const StunUInt32Attribute* retransmit_attr =
569 request->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
570 if (retransmit_attr) {
571 // Inherit the incoming retransmit value in the response so the other side
572 // can see our view of lost pings.
573 response.AddAttribute(new StunUInt32Attribute(
574 STUN_ATTR_RETRANSMIT_COUNT, retransmit_attr->value()));
575
576 if (retransmit_attr->value() > CONNECTION_WRITE_CONNECT_FAILURES) {
577 LOG_J(LS_INFO, this)
578 << "Received a remote ping with high retransmit count: "
579 << retransmit_attr->value();
580 }
581 }
582
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700583 response.AddAttribute(
584 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, addr));
585 response.AddMessageIntegrity(password_);
586 response.AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000587
588 // Send the response message.
jbauchf1f87202016-03-30 06:43:37 -0700589 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000590 response.Write(&buf);
591 rtc::PacketOptions options(DefaultDscpValue());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700592 auto err = SendTo(buf.Data(), buf.Length(), addr, options, false);
593 if (err < 0) {
594 LOG_J(LS_ERROR, this)
595 << "Failed to send STUN ping response"
596 << ", to=" << addr.ToSensitiveString()
597 << ", err=" << err
598 << ", id=" << rtc::hex_encode(response.transaction_id());
599 } else {
600 // Log at LS_INFO if we send a stun ping response on an unwritable
601 // connection.
honghaiz9b5ee9c2015-11-11 13:19:17 -0800602 Connection* conn = GetConnection(addr);
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700603 rtc::LoggingSeverity sev = (conn && !conn->writable()) ?
604 rtc::LS_INFO : rtc::LS_VERBOSE;
605 LOG_JV(sev, this)
606 << "Sent STUN ping response"
607 << ", to=" << addr.ToSensitiveString()
608 << ", id=" << rtc::hex_encode(response.transaction_id());
zhihuang5ecf16c2016-06-01 17:09:15 -0700609
610 conn->stats_.sent_ping_responses++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000611 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000612}
613
614void Port::SendBindingErrorResponse(StunMessage* request,
615 const rtc::SocketAddress& addr,
616 int error_code, const std::string& reason) {
617 ASSERT(request->type() == STUN_BINDING_REQUEST);
618
619 // Fill in the response message.
620 StunMessage response;
621 response.SetType(STUN_BINDING_ERROR_RESPONSE);
622 response.SetTransactionID(request->transaction_id());
623
624 // When doing GICE, we need to write out the error code incorrectly to
625 // maintain backwards compatiblility.
626 StunErrorCodeAttribute* error_attr = StunAttribute::CreateErrorCode();
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700627 error_attr->SetCode(error_code);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000628 error_attr->SetReason(reason);
629 response.AddAttribute(error_attr);
630
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700631 // Per Section 10.1.2, certain error cases don't get a MESSAGE-INTEGRITY,
632 // because we don't have enough information to determine the shared secret.
633 if (error_code != STUN_ERROR_BAD_REQUEST &&
634 error_code != STUN_ERROR_UNAUTHORIZED)
635 response.AddMessageIntegrity(password_);
636 response.AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000637
638 // Send the response message.
jbauchf1f87202016-03-30 06:43:37 -0700639 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000640 response.Write(&buf);
641 rtc::PacketOptions options(DefaultDscpValue());
642 SendTo(buf.Data(), buf.Length(), addr, options, false);
643 LOG_J(LS_INFO, this) << "Sending STUN binding error: reason=" << reason
644 << " to " << addr.ToSensitiveString();
645}
646
647void Port::OnMessage(rtc::Message *pmsg) {
honghaizd0b31432015-09-30 12:42:17 -0700648 ASSERT(pmsg->message_id == MSG_DEAD);
649 if (dead()) {
650 Destroy();
651 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000652}
653
Honghai Zhang351d77b2016-05-20 15:08:29 -0700654void Port::OnNetworkTypeChanged(const rtc::Network* network) {
655 ASSERT(network == network_);
656
657 UpdateNetworkCost();
658}
659
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000660std::string Port::ToString() const {
661 std::stringstream ss;
honghaize3c6c822016-02-17 13:00:28 -0800662 ss << "Port[" << std::hex << this << std::dec << ":" << content_name_ << ":"
663 << component_ << ":" << generation_ << ":" << type_ << ":"
664 << network_->ToString() << "]";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000665 return ss.str();
666}
667
Honghai Zhang351d77b2016-05-20 15:08:29 -0700668// TODO(honghaiz): Make the network cost configurable from user setting.
669void Port::UpdateNetworkCost() {
670 uint16_t new_cost = network_->GetCost();
671 if (network_cost_ == new_cost) {
672 return;
673 }
674 LOG(LS_INFO) << "Network cost changed from " << network_cost_
675 << " to " << new_cost
676 << ". Number of candidates created: " << candidates_.size()
677 << ". Number of connections created: " << connections_.size();
678 network_cost_ = new_cost;
679 for (cricket::Candidate& candidate : candidates_) {
680 candidate.set_network_cost(network_cost_);
681 }
682 // Network cost change will affect the connection selection criteria.
683 // Signal the connection state change on each connection to force a
684 // re-sort in P2PTransportChannel.
685 for (auto kv : connections_) {
686 Connection* conn = kv.second;
687 conn->SignalStateChange(conn);
688 }
689}
690
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000691void Port::EnablePortPackets() {
692 enable_port_packets_ = true;
693}
694
695void Port::OnConnectionDestroyed(Connection* conn) {
696 AddressMap::iterator iter =
697 connections_.find(conn->remote_candidate().address());
698 ASSERT(iter != connections_.end());
699 connections_.erase(iter);
honghaiz36f50e82016-06-01 15:57:03 -0700700 HandleConnectionDestroyed(conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000701
honghaizd0b31432015-09-30 12:42:17 -0700702 // On the controlled side, ports time out after all connections fail.
703 // Note: If a new connection is added after this message is posted, but it
704 // fails and is removed before kPortTimeoutDelay, then this message will
705 // still cause the Port to be destroyed.
706 if (dead()) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700707 thread_->PostDelayed(RTC_FROM_HERE, timeout_delay_, this, MSG_DEAD);
honghaizd0b31432015-09-30 12:42:17 -0700708 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000709}
710
711void Port::Destroy() {
712 ASSERT(connections_.empty());
713 LOG_J(LS_INFO, this) << "Port deleted";
714 SignalDestroyed(this);
715 delete this;
716}
717
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000718const std::string Port::username_fragment() const {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700719 return ice_username_fragment_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000720}
721
722// A ConnectionRequest is a simple STUN ping used to determine writability.
723class ConnectionRequest : public StunRequest {
724 public:
725 explicit ConnectionRequest(Connection* connection)
726 : StunRequest(new IceMessage()),
727 connection_(connection) {
728 }
729
730 virtual ~ConnectionRequest() {
731 }
732
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700733 void Prepare(StunMessage* request) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000734 request->SetType(STUN_BINDING_REQUEST);
735 std::string username;
736 connection_->port()->CreateStunUsername(
737 connection_->remote_candidate().username(), &username);
738 request->AddAttribute(
739 new StunByteStringAttribute(STUN_ATTR_USERNAME, username));
740
741 // connection_ already holds this ping, so subtract one from count.
742 if (connection_->port()->send_retransmit_count_attribute()) {
743 request->AddAttribute(new StunUInt32Attribute(
744 STUN_ATTR_RETRANSMIT_COUNT,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200745 static_cast<uint32_t>(connection_->pings_since_last_response_.size() -
746 1)));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000747 }
honghaiza0c44ea2016-03-23 16:07:48 -0700748 uint32_t network_info = connection_->port()->Network()->id();
749 network_info = (network_info << 16) | connection_->port()->network_cost();
750 request->AddAttribute(
751 new StunUInt32Attribute(STUN_ATTR_NETWORK_INFO, network_info));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000752
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700753 // Adding ICE_CONTROLLED or ICE_CONTROLLING attribute based on the role.
754 if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLING) {
755 request->AddAttribute(new StunUInt64Attribute(
756 STUN_ATTR_ICE_CONTROLLING, connection_->port()->IceTiebreaker()));
757 // Since we are trying aggressive nomination, sending USE-CANDIDATE
758 // attribute in every ping.
759 // If we are dealing with a ice-lite end point, nomination flag
760 // in Connection will be set to false by default. Once the connection
761 // becomes "best connection", nomination flag will be turned on.
762 if (connection_->use_candidate_attr()) {
763 request->AddAttribute(new StunByteStringAttribute(
764 STUN_ATTR_USE_CANDIDATE));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000765 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700766 } else if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLED) {
767 request->AddAttribute(new StunUInt64Attribute(
768 STUN_ATTR_ICE_CONTROLLED, connection_->port()->IceTiebreaker()));
769 } else {
770 ASSERT(false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000771 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700772
773 // Adding PRIORITY Attribute.
774 // Changing the type preference to Peer Reflexive and local preference
775 // and component id information is unchanged from the original priority.
776 // priority = (2^24)*(type preference) +
777 // (2^8)*(local preference) +
778 // (2^0)*(256 - component ID)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200779 uint32_t prflx_priority =
780 ICE_TYPE_PREFERENCE_PRFLX << 24 |
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700781 (connection_->local_candidate().priority() & 0x00FFFFFF);
782 request->AddAttribute(
783 new StunUInt32Attribute(STUN_ATTR_PRIORITY, prflx_priority));
784
785 // Adding Message Integrity attribute.
786 request->AddMessageIntegrity(connection_->remote_candidate().password());
787 // Adding Fingerprint.
788 request->AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000789 }
790
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700791 void OnResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000792 connection_->OnConnectionRequestResponse(this, response);
793 }
794
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700795 void OnErrorResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000796 connection_->OnConnectionRequestErrorResponse(this, response);
797 }
798
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700799 void OnTimeout() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000800 connection_->OnConnectionRequestTimeout(this);
801 }
802
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700803 void OnSent() override {
804 connection_->OnConnectionRequestSent(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000805 // Each request is sent only once. After a single delay , the request will
806 // time out.
807 timeout_ = true;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700808 }
809
810 int resend_delay() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000811 return CONNECTION_RESPONSE_TIMEOUT;
812 }
813
814 private:
815 Connection* connection_;
816};
817
818//
819// Connection
820//
821
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000822Connection::Connection(Port* port,
823 size_t index,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000824 const Candidate& remote_candidate)
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000825 : port_(port),
826 local_candidate_index_(index),
827 remote_candidate_(remote_candidate),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000828 write_state_(STATE_WRITE_INIT),
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700829 receiving_(false),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000830 connected_(true),
831 pruned_(false),
832 use_candidate_attr_(false),
honghaiz5a3acd82015-08-20 15:53:17 -0700833 nominated_(false),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000834 remote_ice_mode_(ICEMODE_FULL),
835 requests_(port->thread()),
836 rtt_(DEFAULT_RTT),
837 last_ping_sent_(0),
838 last_ping_received_(0),
839 last_data_received_(0),
840 last_ping_response_received_(0),
Honghai Zhang82d78622016-05-06 11:29:15 -0700841 recv_rate_tracker_(100, 10u),
842 send_rate_tracker_(100, 10u),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000843 reported_(false),
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700844 state_(STATE_WAITING),
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700845 receiving_timeout_(WEAK_CONNECTION_RECEIVE_TIMEOUT),
nisse1bffc1d2016-05-02 08:18:55 -0700846 time_created_ms_(rtc::TimeMillis()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000847 // All of our connections start in WAITING state.
848 // TODO(mallinath) - Start connections from STATE_FROZEN.
849 // Wire up to send stun packets
850 requests_.SignalSendPacket.connect(this, &Connection::OnSendStunPacket);
851 LOG_J(LS_INFO, this) << "Connection created";
852}
853
854Connection::~Connection() {
855}
856
857const Candidate& Connection::local_candidate() const {
858 ASSERT(local_candidate_index_ < port_->Candidates().size());
859 return port_->Candidates()[local_candidate_index_];
860}
861
Honghai Zhangcc411c02016-03-29 17:27:21 -0700862const Candidate& Connection::remote_candidate() const {
863 return remote_candidate_;
864}
865
Peter Boström0c4e06b2015-10-07 12:23:21 +0200866uint64_t Connection::priority() const {
867 uint64_t priority = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000868 // RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs
869 // Let G be the priority for the candidate provided by the controlling
870 // agent. Let D be the priority for the candidate provided by the
871 // controlled agent.
872 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
873 IceRole role = port_->GetIceRole();
874 if (role != ICEROLE_UNKNOWN) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200875 uint32_t g = 0;
876 uint32_t d = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000877 if (role == ICEROLE_CONTROLLING) {
878 g = local_candidate().priority();
879 d = remote_candidate_.priority();
880 } else {
881 g = remote_candidate_.priority();
882 d = local_candidate().priority();
883 }
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000884 priority = std::min(g, d);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000885 priority = priority << 32;
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000886 priority += 2 * std::max(g, d) + (g > d ? 1 : 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000887 }
888 return priority;
889}
890
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000891void Connection::set_write_state(WriteState value) {
892 WriteState old_value = write_state_;
893 write_state_ = value;
894 if (value != old_value) {
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +0000895 LOG_J(LS_VERBOSE, this) << "set_write_state from: " << old_value << " to "
896 << value;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000897 SignalStateChange(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000898 }
899}
900
honghaiz9ad0db52016-07-14 19:30:28 -0700901void Connection::UpdateReceiving(int64_t now) {
902 bool receiving = now <= last_received() + receiving_timeout_;
903 if (receiving_ == receiving) {
904 return;
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700905 }
honghaiz9ad0db52016-07-14 19:30:28 -0700906 LOG_J(LS_VERBOSE, this) << "set_receiving to " << receiving;
907 receiving_ = receiving;
908 receiving_unchanged_since_ = now;
909 SignalStateChange(this);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700910}
911
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000912void Connection::set_state(State state) {
913 State old_state = state_;
914 state_ = state;
915 if (state != old_state) {
916 LOG_J(LS_VERBOSE, this) << "set_state";
917 }
918}
919
920void Connection::set_connected(bool value) {
921 bool old_value = connected_;
922 connected_ = value;
923 if (value != old_value) {
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700924 LOG_J(LS_VERBOSE, this) << "set_connected from: " << old_value << " to "
925 << value;
Taylor Brandstetterb825aee2016-06-29 13:07:16 -0700926 SignalStateChange(this);
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.
nisse1bffc1d2016-05-02 08:18:55 -0700954 last_data_received_ = rtc::TimeMillis();
honghaiz9ad0db52016-07-14 19:30:28 -0700955 UpdateReceiving(last_data_received_);
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";
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001085 port_->thread()->Post(RTC_FROM_HERE, 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
honghaiz079a7a12016-06-22 16:26:29 -07001093void Connection::FailAndPrune() {
1094 set_state(Connection::STATE_FAILED);
1095 Prune();
1096}
1097
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001098void Connection::PrintPingsSinceLastResponse(std::string* s, size_t max) {
1099 std::ostringstream oss;
1100 oss << std::boolalpha;
1101 if (pings_since_last_response_.size() > max) {
1102 for (size_t i = 0; i < max; i++) {
1103 const SentPing& ping = pings_since_last_response_[i];
1104 oss << rtc::hex_encode(ping.id) << " ";
1105 }
1106 oss << "... " << (pings_since_last_response_.size() - max) << " more";
1107 } else {
1108 for (const SentPing& ping : pings_since_last_response_) {
1109 oss << rtc::hex_encode(ping.id) << " ";
1110 }
1111 }
1112 *s = oss.str();
1113}
1114
honghaiz34b11eb2016-03-16 08:55:44 -07001115void Connection::UpdateState(int64_t now) {
1116 int rtt = ConservativeRTTEstimate(rtt_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001117
Peter Thatcherb2d26232015-05-15 11:25:14 -07001118 if (LOG_CHECK_LEVEL(LS_VERBOSE)) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001119 std::string pings;
1120 PrintPingsSinceLastResponse(&pings, 5);
1121 LOG_J(LS_VERBOSE, this) << "UpdateState()"
1122 << ", ms since last received response="
1123 << now - last_ping_response_received_
1124 << ", ms since last received data="
1125 << now - last_data_received_
1126 << ", rtt=" << rtt
1127 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001128 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001129
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001130 // Check the writable state. (The order of these checks is important.)
1131 //
1132 // Before becoming unwritable, we allow for a fixed number of pings to fail
1133 // (i.e., receive no response). We also have to give the response time to
1134 // get back, so we include a conservative estimate of this.
1135 //
1136 // Before timing out writability, we give a fixed amount of time. This is to
1137 // allow for changes in network conditions.
1138
1139 if ((write_state_ == STATE_WRITABLE) &&
1140 TooManyFailures(pings_since_last_response_,
1141 CONNECTION_WRITE_CONNECT_FAILURES,
1142 rtt,
1143 now) &&
1144 TooLongWithoutResponse(pings_since_last_response_,
1145 CONNECTION_WRITE_CONNECT_TIMEOUT,
1146 now)) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001147 uint32_t max_pings = CONNECTION_WRITE_CONNECT_FAILURES;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001148 LOG_J(LS_INFO, this) << "Unwritable after " << max_pings
1149 << " ping failures and "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001150 << now - pings_since_last_response_[0].sent_time
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001151 << " ms without a response,"
1152 << " ms since last received ping="
1153 << now - last_ping_received_
1154 << " ms since last received data="
1155 << now - last_data_received_
1156 << " rtt=" << rtt;
1157 set_write_state(STATE_WRITE_UNRELIABLE);
1158 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001159 if ((write_state_ == STATE_WRITE_UNRELIABLE ||
1160 write_state_ == STATE_WRITE_INIT) &&
1161 TooLongWithoutResponse(pings_since_last_response_,
1162 CONNECTION_WRITE_TIMEOUT,
1163 now)) {
1164 LOG_J(LS_INFO, this) << "Timed out after "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001165 << now - pings_since_last_response_[0].sent_time
1166 << " ms without a response"
1167 << ", rtt=" << rtt;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001168 set_write_state(STATE_WRITE_TIMEOUT);
1169 }
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001170
honghaiz9ad0db52016-07-14 19:30:28 -07001171 // Update the receiving state.
1172 UpdateReceiving(now);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001173 if (dead(now)) {
1174 Destroy();
1175 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001176}
1177
honghaiz34b11eb2016-03-16 08:55:44 -07001178void Connection::Ping(int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001179 last_ping_sent_ = now;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001180 ConnectionRequest *req = new ConnectionRequest(this);
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001181 pings_since_last_response_.push_back(SentPing(req->id(), now));
1182 LOG_J(LS_VERBOSE, this) << "Sending STUN ping "
1183 << ", id=" << rtc::hex_encode(req->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001184 requests_.Send(req);
1185 state_ = STATE_INPROGRESS;
honghaiz524ecc22016-05-25 12:48:31 -07001186 num_pings_sent_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001187}
1188
1189void Connection::ReceivedPing() {
nisse1bffc1d2016-05-02 08:18:55 -07001190 last_ping_received_ = rtc::TimeMillis();
honghaiz9ad0db52016-07-14 19:30:28 -07001191 UpdateReceiving(last_ping_received_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001192}
1193
zhihuang435264a2016-06-21 11:28:38 -07001194void Connection::ReceivedPingResponse(int rtt) {
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001195 // We've already validated that this is a STUN binding response with
1196 // the correct local and remote username for this connection.
1197 // So if we're not already, become writable. We may be bringing a pruned
1198 // connection back to life, but if we don't really want it, we can always
1199 // prune it again.
honghaiz9ad0db52016-07-14 19:30:28 -07001200 last_ping_response_received_ = rtc::TimeMillis();
1201 UpdateReceiving(last_ping_response_received_);
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001202 set_write_state(STATE_WRITABLE);
1203 set_state(STATE_SUCCEEDED);
1204 pings_since_last_response_.clear();
zhihuang435264a2016-06-21 11:28:38 -07001205 rtt_samples_++;
1206 rtt_ = (RTT_RATIO * rtt_ + rtt) / (RTT_RATIO + 1);
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001207}
1208
honghaiz34b11eb2016-03-16 08:55:44 -07001209bool Connection::dead(int64_t now) const {
honghaiz37389b42016-01-04 21:57:33 -08001210 if (last_received() > 0) {
1211 // If it has ever received anything, we keep it alive until it hasn't
1212 // received anything for DEAD_CONNECTION_RECEIVE_TIMEOUT. This covers the
1213 // normal case of a successfully used connection that stops working. This
1214 // also allows a remote peer to continue pinging over a locally inactive
1215 // (pruned) connection.
1216 return (now > (last_received() + DEAD_CONNECTION_RECEIVE_TIMEOUT));
1217 }
1218
1219 if (active()) {
1220 // If it has never received anything, keep it alive as long as it is
1221 // actively pinging and not pruned. Otherwise, the connection might be
1222 // deleted before it has a chance to ping. This is the normal case for a
1223 // new connection that is pinging but hasn't received anything yet.
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001224 return false;
1225 }
1226
honghaiz37389b42016-01-04 21:57:33 -08001227 // If it has never received anything and is not actively pinging (pruned), we
1228 // keep it around for at least MIN_CONNECTION_LIFETIME to prevent connections
1229 // from being pruned too quickly during a network change event when two
1230 // networks would be up simultaneously but only for a brief period.
1231 return now > (time_created_ms_ + MIN_CONNECTION_LIFETIME);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001232}
1233
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001234bool Connection::stable(int64_t now) const {
zhihuang435264a2016-06-21 11:28:38 -07001235 // A connection is stable if it's RTT has converged and it isn't missing any
1236 // responses. We should send pings at a higher rate until the RTT converges
1237 // and whenever a ping response is missing (so that we can detect
1238 // unwritability faster)
1239 return rtt_converged() && !missing_responses(now);
1240}
1241
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +00001242std::string Connection::ToDebugId() const {
1243 std::stringstream ss;
1244 ss << std::hex << this;
1245 return ss.str();
1246}
1247
honghaize1a0c942016-02-16 14:54:56 -08001248uint32_t Connection::ComputeNetworkCost() const {
1249 // TODO(honghaiz): Will add rtt as part of the network cost.
Honghai Zhang351d77b2016-05-20 15:08:29 -07001250 return port()->network_cost() + remote_candidate_.network_cost();
honghaize1a0c942016-02-16 14:54:56 -08001251}
1252
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001253std::string Connection::ToString() const {
1254 const char CONNECT_STATE_ABBREV[2] = {
1255 '-', // not connected (false)
1256 'C', // connected (true)
1257 };
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001258 const char RECEIVE_STATE_ABBREV[2] = {
1259 '-', // not receiving (false)
1260 'R', // receiving (true)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001261 };
1262 const char WRITE_STATE_ABBREV[4] = {
1263 'W', // STATE_WRITABLE
1264 'w', // STATE_WRITE_UNRELIABLE
1265 '-', // STATE_WRITE_INIT
1266 'x', // STATE_WRITE_TIMEOUT
1267 };
1268 const std::string ICESTATE[4] = {
1269 "W", // STATE_WAITING
1270 "I", // STATE_INPROGRESS
1271 "S", // STATE_SUCCEEDED
1272 "F" // STATE_FAILED
1273 };
1274 const Candidate& local = local_candidate();
1275 const Candidate& remote = remote_candidate();
1276 std::stringstream ss;
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +00001277 ss << "Conn[" << ToDebugId()
1278 << ":" << port_->content_name()
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001279 << ":" << local.id() << ":" << local.component()
1280 << ":" << local.generation()
1281 << ":" << local.type() << ":" << local.protocol()
1282 << ":" << local.address().ToSensitiveString()
1283 << "->" << remote.id() << ":" << remote.component()
1284 << ":" << remote.priority()
1285 << ":" << remote.type() << ":"
1286 << remote.protocol() << ":" << remote.address().ToSensitiveString() << "|"
1287 << CONNECT_STATE_ABBREV[connected()]
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001288 << RECEIVE_STATE_ABBREV[receiving()]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001289 << WRITE_STATE_ABBREV[write_state()]
1290 << ICESTATE[state()] << "|"
1291 << priority() << "|";
1292 if (rtt_ < DEFAULT_RTT) {
1293 ss << rtt_ << "]";
1294 } else {
1295 ss << "-]";
1296 }
1297 return ss.str();
1298}
1299
1300std::string Connection::ToSensitiveString() const {
1301 return ToString();
1302}
1303
1304void Connection::OnConnectionRequestResponse(ConnectionRequest* request,
1305 StunMessage* response) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001306 // Log at LS_INFO if we receive a ping response on an unwritable
1307 // connection.
1308 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1309
honghaiz34b11eb2016-03-16 08:55:44 -07001310 int rtt = request->Elapsed();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001311
zhihuang435264a2016-06-21 11:28:38 -07001312 ReceivedPingResponse(rtt);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001313
Peter Thatcherb2d26232015-05-15 11:25:14 -07001314 if (LOG_CHECK_LEVEL_V(sev)) {
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001315 bool use_candidate = (
1316 response->GetByteString(STUN_ATTR_USE_CANDIDATE) != nullptr);
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001317 std::string pings;
1318 PrintPingsSinceLastResponse(&pings, 5);
1319 LOG_JV(sev, this) << "Received STUN ping response"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001320 << ", id=" << rtc::hex_encode(request->id())
1321 << ", code=0" // Makes logging easier to parse.
1322 << ", rtt=" << rtt
1323 << ", use_candidate=" << use_candidate
1324 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001325 }
1326
zhihuang5ecf16c2016-06-01 17:09:15 -07001327 stats_.recv_ping_responses++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001328
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001329 MaybeAddPrflxCandidate(request, response);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001330}
1331
1332void Connection::OnConnectionRequestErrorResponse(ConnectionRequest* request,
1333 StunMessage* response) {
1334 const StunErrorCodeAttribute* error_attr = response->GetErrorCode();
1335 int error_code = STUN_ERROR_GLOBAL_FAILURE;
1336 if (error_attr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001337 error_code = error_attr->code();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001338 }
1339
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001340 LOG_J(LS_INFO, this) << "Received STUN error response"
1341 << " id=" << rtc::hex_encode(request->id())
1342 << " code=" << error_code
1343 << " rtt=" << request->Elapsed();
1344
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001345 if (error_code == STUN_ERROR_UNKNOWN_ATTRIBUTE ||
1346 error_code == STUN_ERROR_SERVER_ERROR ||
1347 error_code == STUN_ERROR_UNAUTHORIZED) {
1348 // Recoverable error, retry
1349 } else if (error_code == STUN_ERROR_STALE_CREDENTIALS) {
1350 // Race failure, retry
1351 } else if (error_code == STUN_ERROR_ROLE_CONFLICT) {
1352 HandleRoleConflictFromPeer();
1353 } else {
1354 // This is not a valid connection.
1355 LOG_J(LS_ERROR, this) << "Received STUN error response, code="
1356 << error_code << "; killing connection";
deadbeef376e1232015-11-25 09:00:08 -08001357 FailAndDestroy();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001358 }
1359}
1360
1361void Connection::OnConnectionRequestTimeout(ConnectionRequest* request) {
1362 // Log at LS_INFO if we miss a ping on a writable connection.
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001363 rtc::LoggingSeverity sev = writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1364 LOG_JV(sev, this) << "Timing-out STUN ping "
1365 << rtc::hex_encode(request->id())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001366 << " after " << request->Elapsed() << " ms";
1367}
1368
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001369void Connection::OnConnectionRequestSent(ConnectionRequest* request) {
1370 // Log at LS_INFO if we send a ping on an unwritable connection.
1371 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001372 bool use_candidate = use_candidate_attr();
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001373 LOG_JV(sev, this) << "Sent STUN ping"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001374 << ", id=" << rtc::hex_encode(request->id())
1375 << ", use_candidate=" << use_candidate;
zhihuang5ecf16c2016-06-01 17:09:15 -07001376 stats_.sent_ping_requests_total++;
1377 if (stats_.recv_ping_responses == 0) {
1378 stats_.sent_ping_requests_before_first_response++;
1379 }
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001380}
1381
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001382void Connection::HandleRoleConflictFromPeer() {
1383 port_->SignalRoleConflict(port_);
1384}
1385
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001386void Connection::MaybeSetRemoteIceCredentialsAndGeneration(
1387 const std::string& ice_ufrag,
1388 const std::string& ice_pwd,
1389 int generation) {
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001390 if (remote_candidate_.username() == ice_ufrag &&
1391 remote_candidate_.password().empty()) {
1392 remote_candidate_.set_password(ice_pwd);
1393 }
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001394 // TODO(deadbeef): A value of '0' for the generation is used for both
1395 // generation 0 and "generation unknown". It should be changed to an
1396 // rtc::Optional to fix this.
1397 if (remote_candidate_.username() == ice_ufrag &&
1398 remote_candidate_.password() == ice_pwd &&
1399 remote_candidate_.generation() == 0) {
1400 remote_candidate_.set_generation(generation);
1401 }
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001402}
1403
1404void Connection::MaybeUpdatePeerReflexiveCandidate(
1405 const Candidate& new_candidate) {
1406 if (remote_candidate_.type() == PRFLX_PORT_TYPE &&
1407 new_candidate.type() != PRFLX_PORT_TYPE &&
1408 remote_candidate_.protocol() == new_candidate.protocol() &&
1409 remote_candidate_.address() == new_candidate.address() &&
1410 remote_candidate_.username() == new_candidate.username() &&
1411 remote_candidate_.password() == new_candidate.password() &&
1412 remote_candidate_.generation() == new_candidate.generation()) {
1413 remote_candidate_ = new_candidate;
1414 }
1415}
1416
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001417void Connection::OnMessage(rtc::Message *pmsg) {
1418 ASSERT(pmsg->message_id == MSG_DELETE);
honghaiz18f9da02016-06-01 23:53:01 -07001419 LOG(LS_INFO) << "Connection deleted with number of pings sent: "
1420 << num_pings_sent_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001421 SignalDestroyed(this);
1422 delete this;
1423}
1424
honghaiz34b11eb2016-03-16 08:55:44 -07001425int64_t Connection::last_received() const {
Peter Thatcher54360512015-07-08 11:08:35 -07001426 return std::max(last_data_received_,
1427 std::max(last_ping_received_, last_ping_response_received_));
1428}
1429
zhihuang5ecf16c2016-06-01 17:09:15 -07001430ConnectionInfo Connection::stats() {
1431 stats_.recv_bytes_second = round(recv_rate_tracker_.ComputeRate());
1432 stats_.recv_total_bytes = recv_rate_tracker_.TotalSampleCount();
1433 stats_.sent_bytes_second = round(send_rate_tracker_.ComputeRate());
1434 stats_.sent_total_bytes = send_rate_tracker_.TotalSampleCount();
1435 return stats_;
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001436}
1437
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001438void Connection::MaybeAddPrflxCandidate(ConnectionRequest* request,
1439 StunMessage* response) {
1440 // RFC 5245
1441 // The agent checks the mapped address from the STUN response. If the
1442 // transport address does not match any of the local candidates that the
1443 // agent knows about, the mapped address represents a new candidate -- a
1444 // peer reflexive candidate.
1445 const StunAddressAttribute* addr =
1446 response->GetAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
1447 if (!addr) {
1448 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1449 << "No MAPPED-ADDRESS or XOR-MAPPED-ADDRESS found in the "
1450 << "stun response message";
1451 return;
1452 }
1453
1454 bool known_addr = false;
1455 for (size_t i = 0; i < port_->Candidates().size(); ++i) {
1456 if (port_->Candidates()[i].address() == addr->GetAddress()) {
1457 known_addr = true;
1458 break;
1459 }
1460 }
1461 if (known_addr) {
1462 return;
1463 }
1464
1465 // RFC 5245
1466 // Its priority is set equal to the value of the PRIORITY attribute
1467 // in the Binding request.
1468 const StunUInt32Attribute* priority_attr =
1469 request->msg()->GetUInt32(STUN_ATTR_PRIORITY);
1470 if (!priority_attr) {
1471 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1472 << "No STUN_ATTR_PRIORITY found in the "
1473 << "stun response message";
1474 return;
1475 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001476 const uint32_t priority = priority_attr->value();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001477 std::string id = rtc::CreateRandomString(8);
1478
1479 Candidate new_local_candidate;
1480 new_local_candidate.set_id(id);
1481 new_local_candidate.set_component(local_candidate().component());
1482 new_local_candidate.set_type(PRFLX_PORT_TYPE);
1483 new_local_candidate.set_protocol(local_candidate().protocol());
1484 new_local_candidate.set_address(addr->GetAddress());
1485 new_local_candidate.set_priority(priority);
1486 new_local_candidate.set_username(local_candidate().username());
1487 new_local_candidate.set_password(local_candidate().password());
1488 new_local_candidate.set_network_name(local_candidate().network_name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001489 new_local_candidate.set_network_type(local_candidate().network_type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001490 new_local_candidate.set_related_address(local_candidate().address());
Taylor Brandstetterf7c15a92016-06-22 13:13:55 -07001491 new_local_candidate.set_generation(local_candidate().generation());
Honghai Zhang80f1db92016-01-27 11:54:45 -08001492 new_local_candidate.set_foundation(ComputeFoundation(
1493 PRFLX_PORT_TYPE, local_candidate().protocol(),
1494 local_candidate().relay_protocol(), local_candidate().address()));
honghaiza0c44ea2016-03-23 16:07:48 -07001495 new_local_candidate.set_network_id(local_candidate().network_id());
1496 new_local_candidate.set_network_cost(local_candidate().network_cost());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001497
1498 // Change the local candidate of this Connection to the new prflx candidate.
1499 local_candidate_index_ = port_->AddPrflxCandidate(new_local_candidate);
1500
1501 // SignalStateChange to force a re-sort in P2PTransportChannel as this
1502 // Connection's local candidate has changed.
1503 SignalStateChange(this);
1504}
1505
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001506bool Connection::rtt_converged() const {
zhihuang435264a2016-06-21 11:28:38 -07001507 return rtt_samples_ > (RTT_RATIO + 1);
1508}
1509
Taylor Brandstetterb825aee2016-06-29 13:07:16 -07001510bool Connection::missing_responses(int64_t now) const {
zhihuang435264a2016-06-21 11:28:38 -07001511 if (pings_since_last_response_.empty()) {
1512 return false;
1513 }
1514
1515 int64_t waiting = now - pings_since_last_response_[0].sent_time;
1516 return waiting > 2 * rtt();
1517}
1518
deadbeef376e1232015-11-25 09:00:08 -08001519ProxyConnection::ProxyConnection(Port* port,
1520 size_t index,
1521 const Candidate& remote_candidate)
1522 : Connection(port, index, remote_candidate) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001523
1524int ProxyConnection::Send(const void* data, size_t size,
1525 const rtc::PacketOptions& options) {
zhihuang5ecf16c2016-06-01 17:09:15 -07001526 stats_.sent_total_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001527 int sent = port_->SendTo(data, size, remote_candidate_.address(),
1528 options, true);
1529 if (sent <= 0) {
1530 ASSERT(sent < 0);
1531 error_ = port_->GetError();
zhihuang5ecf16c2016-06-01 17:09:15 -07001532 stats_.sent_discarded_packets++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001533 } else {
Tim Psiaki63046262015-09-14 10:38:08 -07001534 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001535 }
1536 return sent;
1537}
1538
1539} // namespace cricket