blob: 15da8f95aec4ca05bdb42385028cd1a76b9c98b5 [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
273void Port::AddConnection(Connection* conn) {
274 connections_[conn->remote_candidate().address()] = conn;
275 conn->SignalDestroyed.connect(this, &Port::OnConnectionDestroyed);
276 SignalConnectionCreated(this, conn);
277}
278
279void Port::OnReadPacket(
280 const char* data, size_t size, const rtc::SocketAddress& addr,
281 ProtocolType proto) {
282 // If the user has enabled port packets, just hand this over.
283 if (enable_port_packets_) {
284 SignalReadPacket(this, data, size, addr);
285 return;
286 }
287
288 // If this is an authenticated STUN request, then signal unknown address and
289 // send back a proper binding response.
kwiberg3ec46792016-04-27 07:22:53 -0700290 std::unique_ptr<IceMessage> msg;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000291 std::string remote_username;
kwiberg6baec032016-03-15 11:09:39 -0700292 if (!GetStunMessage(data, size, addr, &msg, &remote_username)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000293 LOG_J(LS_ERROR, this) << "Received non-STUN packet from unknown address ("
294 << addr.ToSensitiveString() << ")";
295 } else if (!msg) {
296 // STUN message handled already
297 } else if (msg->type() == STUN_BINDING_REQUEST) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700298 LOG(LS_INFO) << "Received STUN ping "
299 << " id=" << rtc::hex_encode(msg->transaction_id())
300 << " from unknown address " << addr.ToSensitiveString();
301
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000302 // Check for role conflicts.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700303 if (!MaybeIceRoleConflict(addr, msg.get(), remote_username)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000304 LOG(LS_INFO) << "Received conflicting role from the peer.";
305 return;
306 }
307
308 SignalUnknownAddress(this, addr, proto, msg.get(), remote_username, false);
309 } else {
310 // NOTE(tschmelcher): STUN_BINDING_RESPONSE is benign. It occurs if we
311 // pruned a connection for this port while it had STUN requests in flight,
312 // because we then get back responses for them, which this code correctly
313 // does not handle.
314 if (msg->type() != STUN_BINDING_RESPONSE) {
315 LOG_J(LS_ERROR, this) << "Received unexpected STUN message type ("
316 << msg->type() << ") from unknown address ("
317 << addr.ToSensitiveString() << ")";
318 }
319 }
320}
321
322void Port::OnReadyToSend() {
323 AddressMap::iterator iter = connections_.begin();
324 for (; iter != connections_.end(); ++iter) {
325 iter->second->OnReadyToSend();
326 }
327}
328
329size_t Port::AddPrflxCandidate(const Candidate& local) {
330 candidates_.push_back(local);
331 return (candidates_.size() - 1);
332}
333
kwiberg6baec032016-03-15 11:09:39 -0700334bool Port::GetStunMessage(const char* data,
335 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000336 const rtc::SocketAddress& addr,
kwiberg3ec46792016-04-27 07:22:53 -0700337 std::unique_ptr<IceMessage>* out_msg,
kwiberg6baec032016-03-15 11:09:39 -0700338 std::string* out_username) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000339 // NOTE: This could clearly be optimized to avoid allocating any memory.
340 // However, at the data rates we'll be looking at on the client side,
341 // this probably isn't worth worrying about.
342 ASSERT(out_msg != NULL);
343 ASSERT(out_username != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000344 out_username->clear();
345
346 // Don't bother parsing the packet if we can tell it's not STUN.
347 // In ICE mode, all STUN packets will have a valid fingerprint.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700348 if (!StunMessage::ValidateFingerprint(data, size)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000349 return false;
350 }
351
352 // Parse the request message. If the packet is not a complete and correct
353 // STUN message, then ignore it.
kwiberg3ec46792016-04-27 07:22:53 -0700354 std::unique_ptr<IceMessage> stun_msg(new IceMessage());
jbauchf1f87202016-03-30 06:43:37 -0700355 rtc::ByteBufferReader buf(data, size);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000356 if (!stun_msg->Read(&buf) || (buf.Length() > 0)) {
357 return false;
358 }
359
360 if (stun_msg->type() == STUN_BINDING_REQUEST) {
361 // Check for the presence of USERNAME and MESSAGE-INTEGRITY (if ICE) first.
362 // If not present, fail with a 400 Bad Request.
363 if (!stun_msg->GetByteString(STUN_ATTR_USERNAME) ||
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700364 !stun_msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000365 LOG_J(LS_ERROR, this) << "Received STUN request without username/M-I "
366 << "from " << addr.ToSensitiveString();
367 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_BAD_REQUEST,
368 STUN_ERROR_REASON_BAD_REQUEST);
369 return true;
370 }
371
372 // If the username is bad or unknown, fail with a 401 Unauthorized.
373 std::string local_ufrag;
374 std::string remote_ufrag;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700375 if (!ParseStunUsername(stun_msg.get(), &local_ufrag, &remote_ufrag) ||
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000376 local_ufrag != username_fragment()) {
377 LOG_J(LS_ERROR, this) << "Received STUN request with bad local username "
378 << local_ufrag << " from "
379 << addr.ToSensitiveString();
380 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
381 STUN_ERROR_REASON_UNAUTHORIZED);
382 return true;
383 }
384
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000385 // If ICE, and the MESSAGE-INTEGRITY is bad, fail with a 401 Unauthorized
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700386 if (!stun_msg->ValidateMessageIntegrity(data, size, password_)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000387 LOG_J(LS_ERROR, this) << "Received STUN request with bad M-I "
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +0000388 << "from " << addr.ToSensitiveString()
389 << ", password_=" << password_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000390 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
391 STUN_ERROR_REASON_UNAUTHORIZED);
392 return true;
393 }
394 out_username->assign(remote_ufrag);
395 } else if ((stun_msg->type() == STUN_BINDING_RESPONSE) ||
396 (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE)) {
397 if (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE) {
398 if (const StunErrorCodeAttribute* error_code = stun_msg->GetErrorCode()) {
399 LOG_J(LS_ERROR, this) << "Received STUN binding error:"
400 << " class=" << error_code->eclass()
401 << " number=" << error_code->number()
402 << " reason='" << error_code->reason() << "'"
403 << " from " << addr.ToSensitiveString();
404 // Return message to allow error-specific processing
405 } else {
406 LOG_J(LS_ERROR, this) << "Received STUN binding error without a error "
407 << "code from " << addr.ToSensitiveString();
408 return true;
409 }
410 }
411 // NOTE: Username should not be used in verifying response messages.
412 out_username->clear();
413 } else if (stun_msg->type() == STUN_BINDING_INDICATION) {
414 LOG_J(LS_VERBOSE, this) << "Received STUN binding indication:"
415 << " from " << addr.ToSensitiveString();
416 out_username->clear();
417 // No stun attributes will be verified, if it's stun indication message.
418 // Returning from end of the this method.
419 } else {
420 LOG_J(LS_ERROR, this) << "Received STUN packet with invalid type ("
421 << stun_msg->type() << ") from "
422 << addr.ToSensitiveString();
423 return true;
424 }
425
426 // Return the STUN message found.
kwiberg6baec032016-03-15 11:09:39 -0700427 *out_msg = std::move(stun_msg);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000428 return true;
429}
430
431bool Port::IsCompatibleAddress(const rtc::SocketAddress& addr) {
432 int family = ip().family();
433 // We use single-stack sockets, so families must match.
434 if (addr.family() != family) {
435 return false;
436 }
437 // Link-local IPv6 ports can only connect to other link-local IPv6 ports.
Peter Thatcherb8b01432015-07-07 16:45:53 -0700438 if (family == AF_INET6 &&
439 (IPIsLinkLocal(ip()) != IPIsLinkLocal(addr.ipaddr()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000440 return false;
441 }
442 return true;
443}
444
445bool Port::ParseStunUsername(const StunMessage* stun_msg,
446 std::string* local_ufrag,
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700447 std::string* remote_ufrag) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000448 // The packet must include a username that either begins or ends with our
449 // fragment. It should begin with our fragment if it is a request and it
450 // should end with our fragment if it is a response.
451 local_ufrag->clear();
452 remote_ufrag->clear();
453 const StunByteStringAttribute* username_attr =
454 stun_msg->GetByteString(STUN_ATTR_USERNAME);
455 if (username_attr == NULL)
456 return false;
457
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700458 // RFRAG:LFRAG
459 const std::string username = username_attr->GetString();
460 size_t colon_pos = username.find(":");
461 if (colon_pos == std::string::npos) {
462 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000463 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000464
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700465 *local_ufrag = username.substr(0, colon_pos);
466 *remote_ufrag = username.substr(colon_pos + 1, username.size());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000467 return true;
468}
469
470bool Port::MaybeIceRoleConflict(
471 const rtc::SocketAddress& addr, IceMessage* stun_msg,
472 const std::string& remote_ufrag) {
473 // Validate ICE_CONTROLLING or ICE_CONTROLLED attributes.
474 bool ret = true;
475 IceRole remote_ice_role = ICEROLE_UNKNOWN;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200476 uint64_t remote_tiebreaker = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000477 const StunUInt64Attribute* stun_attr =
478 stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
479 if (stun_attr) {
480 remote_ice_role = ICEROLE_CONTROLLING;
481 remote_tiebreaker = stun_attr->value();
482 }
483
484 // If |remote_ufrag| is same as port local username fragment and
485 // tie breaker value received in the ping message matches port
486 // tiebreaker value this must be a loopback call.
487 // We will treat this as valid scenario.
488 if (remote_ice_role == ICEROLE_CONTROLLING &&
489 username_fragment() == remote_ufrag &&
490 remote_tiebreaker == IceTiebreaker()) {
491 return true;
492 }
493
494 stun_attr = stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
495 if (stun_attr) {
496 remote_ice_role = ICEROLE_CONTROLLED;
497 remote_tiebreaker = stun_attr->value();
498 }
499
500 switch (ice_role_) {
501 case ICEROLE_CONTROLLING:
502 if (ICEROLE_CONTROLLING == remote_ice_role) {
503 if (remote_tiebreaker >= tiebreaker_) {
504 SignalRoleConflict(this);
505 } else {
506 // Send Role Conflict (487) error response.
507 SendBindingErrorResponse(stun_msg, addr,
508 STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
509 ret = false;
510 }
511 }
512 break;
513 case ICEROLE_CONTROLLED:
514 if (ICEROLE_CONTROLLED == 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 default:
526 ASSERT(false);
527 }
528 return ret;
529}
530
531void Port::CreateStunUsername(const std::string& remote_username,
532 std::string* stun_username_attr_str) const {
533 stun_username_attr_str->clear();
534 *stun_username_attr_str = remote_username;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700535 stun_username_attr_str->append(":");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000536 stun_username_attr_str->append(username_fragment());
537}
538
539void Port::SendBindingResponse(StunMessage* request,
540 const rtc::SocketAddress& addr) {
541 ASSERT(request->type() == STUN_BINDING_REQUEST);
542
543 // Retrieve the username from the request.
544 const StunByteStringAttribute* username_attr =
545 request->GetByteString(STUN_ATTR_USERNAME);
546 ASSERT(username_attr != NULL);
547 if (username_attr == NULL) {
548 // No valid username, skip the response.
549 return;
550 }
551
552 // Fill in the response message.
553 StunMessage response;
554 response.SetType(STUN_BINDING_RESPONSE);
555 response.SetTransactionID(request->transaction_id());
556 const StunUInt32Attribute* retransmit_attr =
557 request->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
558 if (retransmit_attr) {
559 // Inherit the incoming retransmit value in the response so the other side
560 // can see our view of lost pings.
561 response.AddAttribute(new StunUInt32Attribute(
562 STUN_ATTR_RETRANSMIT_COUNT, retransmit_attr->value()));
563
564 if (retransmit_attr->value() > CONNECTION_WRITE_CONNECT_FAILURES) {
565 LOG_J(LS_INFO, this)
566 << "Received a remote ping with high retransmit count: "
567 << retransmit_attr->value();
568 }
569 }
570
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700571 response.AddAttribute(
572 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, addr));
573 response.AddMessageIntegrity(password_);
574 response.AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000575
576 // Send the response message.
jbauchf1f87202016-03-30 06:43:37 -0700577 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000578 response.Write(&buf);
579 rtc::PacketOptions options(DefaultDscpValue());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700580 auto err = SendTo(buf.Data(), buf.Length(), addr, options, false);
581 if (err < 0) {
582 LOG_J(LS_ERROR, this)
583 << "Failed to send STUN ping response"
584 << ", to=" << addr.ToSensitiveString()
585 << ", err=" << err
586 << ", id=" << rtc::hex_encode(response.transaction_id());
587 } else {
588 // Log at LS_INFO if we send a stun ping response on an unwritable
589 // connection.
honghaiz9b5ee9c2015-11-11 13:19:17 -0800590 Connection* conn = GetConnection(addr);
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700591 rtc::LoggingSeverity sev = (conn && !conn->writable()) ?
592 rtc::LS_INFO : rtc::LS_VERBOSE;
593 LOG_JV(sev, this)
594 << "Sent STUN ping response"
595 << ", to=" << addr.ToSensitiveString()
596 << ", id=" << rtc::hex_encode(response.transaction_id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000597 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000598}
599
600void Port::SendBindingErrorResponse(StunMessage* request,
601 const rtc::SocketAddress& addr,
602 int error_code, const std::string& reason) {
603 ASSERT(request->type() == STUN_BINDING_REQUEST);
604
605 // Fill in the response message.
606 StunMessage response;
607 response.SetType(STUN_BINDING_ERROR_RESPONSE);
608 response.SetTransactionID(request->transaction_id());
609
610 // When doing GICE, we need to write out the error code incorrectly to
611 // maintain backwards compatiblility.
612 StunErrorCodeAttribute* error_attr = StunAttribute::CreateErrorCode();
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700613 error_attr->SetCode(error_code);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000614 error_attr->SetReason(reason);
615 response.AddAttribute(error_attr);
616
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700617 // Per Section 10.1.2, certain error cases don't get a MESSAGE-INTEGRITY,
618 // because we don't have enough information to determine the shared secret.
619 if (error_code != STUN_ERROR_BAD_REQUEST &&
620 error_code != STUN_ERROR_UNAUTHORIZED)
621 response.AddMessageIntegrity(password_);
622 response.AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000623
624 // Send the response message.
jbauchf1f87202016-03-30 06:43:37 -0700625 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000626 response.Write(&buf);
627 rtc::PacketOptions options(DefaultDscpValue());
628 SendTo(buf.Data(), buf.Length(), addr, options, false);
629 LOG_J(LS_INFO, this) << "Sending STUN binding error: reason=" << reason
630 << " to " << addr.ToSensitiveString();
631}
632
633void Port::OnMessage(rtc::Message *pmsg) {
honghaizd0b31432015-09-30 12:42:17 -0700634 ASSERT(pmsg->message_id == MSG_DEAD);
635 if (dead()) {
636 Destroy();
637 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000638}
639
honghaize3c6c822016-02-17 13:00:28 -0800640void Port::OnNetworkInactive(const rtc::Network* network) {
641 ASSERT(network == network_);
642 SignalNetworkInactive(this);
643}
644
Honghai Zhang351d77b2016-05-20 15:08:29 -0700645void Port::OnNetworkTypeChanged(const rtc::Network* network) {
646 ASSERT(network == network_);
647
648 UpdateNetworkCost();
649}
650
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000651std::string Port::ToString() const {
652 std::stringstream ss;
honghaize3c6c822016-02-17 13:00:28 -0800653 ss << "Port[" << std::hex << this << std::dec << ":" << content_name_ << ":"
654 << component_ << ":" << generation_ << ":" << type_ << ":"
655 << network_->ToString() << "]";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000656 return ss.str();
657}
658
Honghai Zhang351d77b2016-05-20 15:08:29 -0700659// TODO(honghaiz): Make the network cost configurable from user setting.
660void Port::UpdateNetworkCost() {
661 uint16_t new_cost = network_->GetCost();
662 if (network_cost_ == new_cost) {
663 return;
664 }
665 LOG(LS_INFO) << "Network cost changed from " << network_cost_
666 << " to " << new_cost
667 << ". Number of candidates created: " << candidates_.size()
668 << ". Number of connections created: " << connections_.size();
669 network_cost_ = new_cost;
670 for (cricket::Candidate& candidate : candidates_) {
671 candidate.set_network_cost(network_cost_);
672 }
673 // Network cost change will affect the connection selection criteria.
674 // Signal the connection state change on each connection to force a
675 // re-sort in P2PTransportChannel.
676 for (auto kv : connections_) {
677 Connection* conn = kv.second;
678 conn->SignalStateChange(conn);
679 }
680}
681
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000682void Port::EnablePortPackets() {
683 enable_port_packets_ = true;
684}
685
686void Port::OnConnectionDestroyed(Connection* conn) {
687 AddressMap::iterator iter =
688 connections_.find(conn->remote_candidate().address());
689 ASSERT(iter != connections_.end());
690 connections_.erase(iter);
691
honghaizd0b31432015-09-30 12:42:17 -0700692 // On the controlled side, ports time out after all connections fail.
693 // Note: If a new connection is added after this message is posted, but it
694 // fails and is removed before kPortTimeoutDelay, then this message will
695 // still cause the Port to be destroyed.
696 if (dead()) {
697 thread_->PostDelayed(timeout_delay_, this, MSG_DEAD);
698 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000699}
700
701void Port::Destroy() {
702 ASSERT(connections_.empty());
703 LOG_J(LS_INFO, this) << "Port deleted";
704 SignalDestroyed(this);
705 delete this;
706}
707
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000708const std::string Port::username_fragment() const {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700709 return ice_username_fragment_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000710}
711
712// A ConnectionRequest is a simple STUN ping used to determine writability.
713class ConnectionRequest : public StunRequest {
714 public:
715 explicit ConnectionRequest(Connection* connection)
716 : StunRequest(new IceMessage()),
717 connection_(connection) {
718 }
719
720 virtual ~ConnectionRequest() {
721 }
722
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700723 void Prepare(StunMessage* request) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000724 request->SetType(STUN_BINDING_REQUEST);
725 std::string username;
726 connection_->port()->CreateStunUsername(
727 connection_->remote_candidate().username(), &username);
728 request->AddAttribute(
729 new StunByteStringAttribute(STUN_ATTR_USERNAME, username));
730
731 // connection_ already holds this ping, so subtract one from count.
732 if (connection_->port()->send_retransmit_count_attribute()) {
733 request->AddAttribute(new StunUInt32Attribute(
734 STUN_ATTR_RETRANSMIT_COUNT,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200735 static_cast<uint32_t>(connection_->pings_since_last_response_.size() -
736 1)));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000737 }
honghaiza0c44ea2016-03-23 16:07:48 -0700738 uint32_t network_info = connection_->port()->Network()->id();
739 network_info = (network_info << 16) | connection_->port()->network_cost();
740 request->AddAttribute(
741 new StunUInt32Attribute(STUN_ATTR_NETWORK_INFO, network_info));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000742
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700743 // Adding ICE_CONTROLLED or ICE_CONTROLLING attribute based on the role.
744 if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLING) {
745 request->AddAttribute(new StunUInt64Attribute(
746 STUN_ATTR_ICE_CONTROLLING, connection_->port()->IceTiebreaker()));
747 // Since we are trying aggressive nomination, sending USE-CANDIDATE
748 // attribute in every ping.
749 // If we are dealing with a ice-lite end point, nomination flag
750 // in Connection will be set to false by default. Once the connection
751 // becomes "best connection", nomination flag will be turned on.
752 if (connection_->use_candidate_attr()) {
753 request->AddAttribute(new StunByteStringAttribute(
754 STUN_ATTR_USE_CANDIDATE));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000755 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700756 } else if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLED) {
757 request->AddAttribute(new StunUInt64Attribute(
758 STUN_ATTR_ICE_CONTROLLED, connection_->port()->IceTiebreaker()));
759 } else {
760 ASSERT(false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000761 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700762
763 // Adding PRIORITY Attribute.
764 // Changing the type preference to Peer Reflexive and local preference
765 // and component id information is unchanged from the original priority.
766 // priority = (2^24)*(type preference) +
767 // (2^8)*(local preference) +
768 // (2^0)*(256 - component ID)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200769 uint32_t prflx_priority =
770 ICE_TYPE_PREFERENCE_PRFLX << 24 |
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700771 (connection_->local_candidate().priority() & 0x00FFFFFF);
772 request->AddAttribute(
773 new StunUInt32Attribute(STUN_ATTR_PRIORITY, prflx_priority));
774
775 // Adding Message Integrity attribute.
776 request->AddMessageIntegrity(connection_->remote_candidate().password());
777 // Adding Fingerprint.
778 request->AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000779 }
780
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700781 void OnResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000782 connection_->OnConnectionRequestResponse(this, response);
783 }
784
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700785 void OnErrorResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000786 connection_->OnConnectionRequestErrorResponse(this, response);
787 }
788
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700789 void OnTimeout() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000790 connection_->OnConnectionRequestTimeout(this);
791 }
792
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700793 void OnSent() override {
794 connection_->OnConnectionRequestSent(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000795 // Each request is sent only once. After a single delay , the request will
796 // time out.
797 timeout_ = true;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700798 }
799
800 int resend_delay() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000801 return CONNECTION_RESPONSE_TIMEOUT;
802 }
803
804 private:
805 Connection* connection_;
806};
807
808//
809// Connection
810//
811
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000812Connection::Connection(Port* port,
813 size_t index,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000814 const Candidate& remote_candidate)
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000815 : port_(port),
816 local_candidate_index_(index),
817 remote_candidate_(remote_candidate),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000818 write_state_(STATE_WRITE_INIT),
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700819 receiving_(false),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000820 connected_(true),
821 pruned_(false),
822 use_candidate_attr_(false),
honghaiz5a3acd82015-08-20 15:53:17 -0700823 nominated_(false),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000824 remote_ice_mode_(ICEMODE_FULL),
825 requests_(port->thread()),
826 rtt_(DEFAULT_RTT),
827 last_ping_sent_(0),
828 last_ping_received_(0),
829 last_data_received_(0),
830 last_ping_response_received_(0),
Honghai Zhang82d78622016-05-06 11:29:15 -0700831 recv_rate_tracker_(100, 10u),
832 send_rate_tracker_(100, 10u),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000833 sent_packets_discarded_(0),
834 sent_packets_total_(0),
835 reported_(false),
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700836 state_(STATE_WAITING),
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700837 receiving_timeout_(WEAK_CONNECTION_RECEIVE_TIMEOUT),
nisse1bffc1d2016-05-02 08:18:55 -0700838 time_created_ms_(rtc::TimeMillis()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000839 // All of our connections start in WAITING state.
840 // TODO(mallinath) - Start connections from STATE_FROZEN.
841 // Wire up to send stun packets
842 requests_.SignalSendPacket.connect(this, &Connection::OnSendStunPacket);
843 LOG_J(LS_INFO, this) << "Connection created";
844}
845
846Connection::~Connection() {
847}
848
849const Candidate& Connection::local_candidate() const {
850 ASSERT(local_candidate_index_ < port_->Candidates().size());
851 return port_->Candidates()[local_candidate_index_];
852}
853
Honghai Zhangcc411c02016-03-29 17:27:21 -0700854const Candidate& Connection::remote_candidate() const {
855 return remote_candidate_;
856}
857
Peter Boström0c4e06b2015-10-07 12:23:21 +0200858uint64_t Connection::priority() const {
859 uint64_t priority = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000860 // RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs
861 // Let G be the priority for the candidate provided by the controlling
862 // agent. Let D be the priority for the candidate provided by the
863 // controlled agent.
864 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
865 IceRole role = port_->GetIceRole();
866 if (role != ICEROLE_UNKNOWN) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200867 uint32_t g = 0;
868 uint32_t d = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000869 if (role == ICEROLE_CONTROLLING) {
870 g = local_candidate().priority();
871 d = remote_candidate_.priority();
872 } else {
873 g = remote_candidate_.priority();
874 d = local_candidate().priority();
875 }
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000876 priority = std::min(g, d);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000877 priority = priority << 32;
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000878 priority += 2 * std::max(g, d) + (g > d ? 1 : 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000879 }
880 return priority;
881}
882
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000883void Connection::set_write_state(WriteState value) {
884 WriteState old_value = write_state_;
885 write_state_ = value;
886 if (value != old_value) {
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +0000887 LOG_J(LS_VERBOSE, this) << "set_write_state from: " << old_value << " to "
888 << value;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000889 SignalStateChange(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000890 }
891}
892
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700893void Connection::set_receiving(bool value) {
894 if (value != receiving_) {
895 LOG_J(LS_VERBOSE, this) << "set_receiving to " << value;
896 receiving_ = value;
897 SignalStateChange(this);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700898 }
899}
900
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000901void Connection::set_state(State state) {
902 State old_state = state_;
903 state_ = state;
904 if (state != old_state) {
905 LOG_J(LS_VERBOSE, this) << "set_state";
906 }
907}
908
909void Connection::set_connected(bool value) {
910 bool old_value = connected_;
911 connected_ = value;
912 if (value != old_value) {
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700913 LOG_J(LS_VERBOSE, this) << "set_connected from: " << old_value << " to "
914 << value;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000915 }
916}
917
918void Connection::set_use_candidate_attr(bool enable) {
919 use_candidate_attr_ = enable;
920}
921
922void Connection::OnSendStunPacket(const void* data, size_t size,
923 StunRequest* req) {
924 rtc::PacketOptions options(port_->DefaultDscpValue());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700925 auto err = port_->SendTo(
926 data, size, remote_candidate_.address(), options, false);
927 if (err < 0) {
928 LOG_J(LS_WARNING, this) << "Failed to send STUN ping "
929 << " err=" << err
930 << " id=" << rtc::hex_encode(req->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000931 }
932}
933
934void Connection::OnReadPacket(
935 const char* data, size_t size, const rtc::PacketTime& packet_time) {
kwiberg3ec46792016-04-27 07:22:53 -0700936 std::unique_ptr<IceMessage> msg;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000937 std::string remote_ufrag;
938 const rtc::SocketAddress& addr(remote_candidate_.address());
kwiberg6baec032016-03-15 11:09:39 -0700939 if (!port_->GetStunMessage(data, size, addr, &msg, &remote_ufrag)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000940 // The packet did not parse as a valid STUN message
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700941 // This is a data packet, pass it along.
942 set_receiving(true);
nisse1bffc1d2016-05-02 08:18:55 -0700943 last_data_received_ = rtc::TimeMillis();
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700944 recv_rate_tracker_.AddSamples(size);
945 SignalReadPacket(this, data, size, packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000946
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700947 // If timed out sending writability checks, start up again
948 if (!pruned_ && (write_state_ == STATE_WRITE_TIMEOUT)) {
949 LOG(LS_WARNING) << "Received a data packet on a timed-out Connection. "
950 << "Resetting state to STATE_WRITE_INIT.";
951 set_write_state(STATE_WRITE_INIT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000952 }
953 } else if (!msg) {
954 // The packet was STUN, but failed a check and was handled internally.
955 } else {
956 // The packet is STUN and passed the Port checks.
957 // Perform our own checks to ensure this packet is valid.
honghaizd0b31432015-09-30 12:42:17 -0700958 // If this is a STUN request, then update the receiving bit and respond.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000959 // If this is a STUN response, then update the writable bit.
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700960 // Log at LS_INFO if we receive a ping on an unwritable connection.
961 rtc::LoggingSeverity sev = (!writable() ? rtc::LS_INFO : rtc::LS_VERBOSE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000962 switch (msg->type()) {
963 case STUN_BINDING_REQUEST:
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700964 LOG_JV(sev, this) << "Received STUN ping"
965 << ", id=" << rtc::hex_encode(msg->transaction_id());
966
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000967 if (remote_ufrag == remote_candidate_.username()) {
honghaiz9b5ee9c2015-11-11 13:19:17 -0800968 HandleBindingRequest(msg.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000969 } else {
970 // The packet had the right local username, but the remote username
971 // was not the right one for the remote address.
972 LOG_J(LS_ERROR, this)
973 << "Received STUN request with bad remote username "
974 << remote_ufrag;
975 port_->SendBindingErrorResponse(msg.get(), addr,
976 STUN_ERROR_UNAUTHORIZED,
977 STUN_ERROR_REASON_UNAUTHORIZED);
978
979 }
980 break;
981
982 // Response from remote peer. Does it match request sent?
983 // This doesn't just check, it makes callbacks if transaction
984 // id's match.
985 case STUN_BINDING_RESPONSE:
986 case STUN_BINDING_ERROR_RESPONSE:
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700987 if (msg->ValidateMessageIntegrity(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000988 data, size, remote_candidate().password())) {
989 requests_.CheckResponse(msg.get());
990 }
991 // Otherwise silently discard the response message.
992 break;
993
honghaizd0b31432015-09-30 12:42:17 -0700994 // Remote end point sent an STUN indication instead of regular binding
995 // request. In this case |last_ping_received_| will be updated but no
996 // response will be sent.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000997 case STUN_BINDING_INDICATION:
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700998 ReceivedPing();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000999 break;
1000
1001 default:
1002 ASSERT(false);
1003 break;
1004 }
1005 }
1006}
1007
honghaiz9b5ee9c2015-11-11 13:19:17 -08001008void Connection::HandleBindingRequest(IceMessage* msg) {
1009 // This connection should now be receiving.
1010 ReceivedPing();
1011
1012 const rtc::SocketAddress& remote_addr = remote_candidate_.address();
1013 const std::string& remote_ufrag = remote_candidate_.username();
1014 // Check for role conflicts.
1015 if (!port_->MaybeIceRoleConflict(remote_addr, msg, remote_ufrag)) {
1016 // Received conflicting role from the peer.
1017 LOG(LS_INFO) << "Received conflicting role from the peer.";
1018 return;
1019 }
1020
1021 // This is a validated stun request from remote peer.
1022 port_->SendBindingResponse(msg, remote_addr);
1023
1024 // If it timed out on writing check, start up again
1025 if (!pruned_ && write_state_ == STATE_WRITE_TIMEOUT) {
1026 set_write_state(STATE_WRITE_INIT);
1027 }
1028
1029 if (port_->GetIceRole() == ICEROLE_CONTROLLED) {
1030 const StunByteStringAttribute* use_candidate_attr =
1031 msg->GetByteString(STUN_ATTR_USE_CANDIDATE);
1032 if (use_candidate_attr) {
1033 set_nominated(true);
1034 SignalNominated(this);
1035 }
1036 }
Honghai Zhang351d77b2016-05-20 15:08:29 -07001037 // Set the remote cost if the network_info attribute is available.
1038 // Note: If packets are re-ordered, we may get incorrect network cost
1039 // temporarily, but it should get the correct value shortly after that.
1040 const StunUInt32Attribute* network_attr =
1041 msg->GetUInt32(STUN_ATTR_NETWORK_INFO);
1042 if (network_attr) {
1043 uint32_t network_info = network_attr->value();
1044 uint16_t network_cost = static_cast<uint16_t>(network_info);
1045 if (network_cost != remote_candidate_.network_cost()) {
1046 remote_candidate_.set_network_cost(network_cost);
1047 // Network cost change will affect the connection ranking, so signal
1048 // state change to force a re-sort in P2PTransportChannel.
1049 SignalStateChange(this);
1050 }
1051 }
honghaiz9b5ee9c2015-11-11 13:19:17 -08001052}
1053
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001054void Connection::OnReadyToSend() {
1055 if (write_state_ == STATE_WRITABLE) {
1056 SignalReadyToSend(this);
1057 }
1058}
1059
1060void Connection::Prune() {
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001061 if (!pruned_ || active()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001062 LOG_J(LS_VERBOSE, this) << "Connection pruned";
1063 pruned_ = true;
1064 requests_.Clear();
1065 set_write_state(STATE_WRITE_TIMEOUT);
1066 }
1067}
1068
1069void Connection::Destroy() {
1070 LOG_J(LS_VERBOSE, this) << "Connection destroyed";
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001071 port_->thread()->Post(this, MSG_DELETE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001072}
1073
deadbeef376e1232015-11-25 09:00:08 -08001074void Connection::FailAndDestroy() {
1075 set_state(Connection::STATE_FAILED);
1076 Destroy();
1077}
1078
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001079void Connection::PrintPingsSinceLastResponse(std::string* s, size_t max) {
1080 std::ostringstream oss;
1081 oss << std::boolalpha;
1082 if (pings_since_last_response_.size() > max) {
1083 for (size_t i = 0; i < max; i++) {
1084 const SentPing& ping = pings_since_last_response_[i];
1085 oss << rtc::hex_encode(ping.id) << " ";
1086 }
1087 oss << "... " << (pings_since_last_response_.size() - max) << " more";
1088 } else {
1089 for (const SentPing& ping : pings_since_last_response_) {
1090 oss << rtc::hex_encode(ping.id) << " ";
1091 }
1092 }
1093 *s = oss.str();
1094}
1095
honghaiz34b11eb2016-03-16 08:55:44 -07001096void Connection::UpdateState(int64_t now) {
1097 int rtt = ConservativeRTTEstimate(rtt_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001098
Peter Thatcherb2d26232015-05-15 11:25:14 -07001099 if (LOG_CHECK_LEVEL(LS_VERBOSE)) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001100 std::string pings;
1101 PrintPingsSinceLastResponse(&pings, 5);
1102 LOG_J(LS_VERBOSE, this) << "UpdateState()"
1103 << ", ms since last received response="
1104 << now - last_ping_response_received_
1105 << ", ms since last received data="
1106 << now - last_data_received_
1107 << ", rtt=" << rtt
1108 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001109 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001110
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001111 // Check the writable state. (The order of these checks is important.)
1112 //
1113 // Before becoming unwritable, we allow for a fixed number of pings to fail
1114 // (i.e., receive no response). We also have to give the response time to
1115 // get back, so we include a conservative estimate of this.
1116 //
1117 // Before timing out writability, we give a fixed amount of time. This is to
1118 // allow for changes in network conditions.
1119
1120 if ((write_state_ == STATE_WRITABLE) &&
1121 TooManyFailures(pings_since_last_response_,
1122 CONNECTION_WRITE_CONNECT_FAILURES,
1123 rtt,
1124 now) &&
1125 TooLongWithoutResponse(pings_since_last_response_,
1126 CONNECTION_WRITE_CONNECT_TIMEOUT,
1127 now)) {
Peter Boström0c4e06b2015-10-07 12:23:21 +02001128 uint32_t max_pings = CONNECTION_WRITE_CONNECT_FAILURES;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001129 LOG_J(LS_INFO, this) << "Unwritable after " << max_pings
1130 << " ping failures and "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001131 << now - pings_since_last_response_[0].sent_time
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001132 << " ms without a response,"
1133 << " ms since last received ping="
1134 << now - last_ping_received_
1135 << " ms since last received data="
1136 << now - last_data_received_
1137 << " rtt=" << rtt;
1138 set_write_state(STATE_WRITE_UNRELIABLE);
1139 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001140 if ((write_state_ == STATE_WRITE_UNRELIABLE ||
1141 write_state_ == STATE_WRITE_INIT) &&
1142 TooLongWithoutResponse(pings_since_last_response_,
1143 CONNECTION_WRITE_TIMEOUT,
1144 now)) {
1145 LOG_J(LS_INFO, this) << "Timed out after "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001146 << now - pings_since_last_response_[0].sent_time
1147 << " ms without a response"
1148 << ", rtt=" << rtt;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001149 set_write_state(STATE_WRITE_TIMEOUT);
1150 }
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001151
1152 // Check the receiving state.
honghaiz34b11eb2016-03-16 08:55:44 -07001153 int64_t last_recv_time = last_received();
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001154 bool receiving = now <= last_recv_time + receiving_timeout_;
1155 set_receiving(receiving);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001156 if (dead(now)) {
1157 Destroy();
1158 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001159}
1160
honghaiz34b11eb2016-03-16 08:55:44 -07001161void Connection::Ping(int64_t now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001162 last_ping_sent_ = now;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001163 ConnectionRequest *req = new ConnectionRequest(this);
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001164 pings_since_last_response_.push_back(SentPing(req->id(), now));
1165 LOG_J(LS_VERBOSE, this) << "Sending STUN ping "
1166 << ", id=" << rtc::hex_encode(req->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001167 requests_.Send(req);
1168 state_ = STATE_INPROGRESS;
1169}
1170
1171void Connection::ReceivedPing() {
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001172 set_receiving(true);
nisse1bffc1d2016-05-02 08:18:55 -07001173 last_ping_received_ = rtc::TimeMillis();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001174}
1175
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001176void Connection::ReceivedPingResponse() {
1177 // We've already validated that this is a STUN binding response with
1178 // the correct local and remote username for this connection.
1179 // So if we're not already, become writable. We may be bringing a pruned
1180 // connection back to life, but if we don't really want it, we can always
1181 // prune it again.
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001182 set_receiving(true);
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001183 set_write_state(STATE_WRITABLE);
1184 set_state(STATE_SUCCEEDED);
1185 pings_since_last_response_.clear();
nisse1bffc1d2016-05-02 08:18:55 -07001186 last_ping_response_received_ = rtc::TimeMillis();
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001187}
1188
honghaiz34b11eb2016-03-16 08:55:44 -07001189bool Connection::dead(int64_t now) const {
honghaiz37389b42016-01-04 21:57:33 -08001190 if (last_received() > 0) {
1191 // If it has ever received anything, we keep it alive until it hasn't
1192 // received anything for DEAD_CONNECTION_RECEIVE_TIMEOUT. This covers the
1193 // normal case of a successfully used connection that stops working. This
1194 // also allows a remote peer to continue pinging over a locally inactive
1195 // (pruned) connection.
1196 return (now > (last_received() + DEAD_CONNECTION_RECEIVE_TIMEOUT));
1197 }
1198
1199 if (active()) {
1200 // If it has never received anything, keep it alive as long as it is
1201 // actively pinging and not pruned. Otherwise, the connection might be
1202 // deleted before it has a chance to ping. This is the normal case for a
1203 // new connection that is pinging but hasn't received anything yet.
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001204 return false;
1205 }
1206
honghaiz37389b42016-01-04 21:57:33 -08001207 // If it has never received anything and is not actively pinging (pruned), we
1208 // keep it around for at least MIN_CONNECTION_LIFETIME to prevent connections
1209 // from being pruned too quickly during a network change event when two
1210 // networks would be up simultaneously but only for a brief period.
1211 return now > (time_created_ms_ + MIN_CONNECTION_LIFETIME);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001212}
1213
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +00001214std::string Connection::ToDebugId() const {
1215 std::stringstream ss;
1216 ss << std::hex << this;
1217 return ss.str();
1218}
1219
honghaize1a0c942016-02-16 14:54:56 -08001220uint32_t Connection::ComputeNetworkCost() const {
1221 // TODO(honghaiz): Will add rtt as part of the network cost.
Honghai Zhang351d77b2016-05-20 15:08:29 -07001222 return port()->network_cost() + remote_candidate_.network_cost();
honghaize1a0c942016-02-16 14:54:56 -08001223}
1224
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001225std::string Connection::ToString() const {
1226 const char CONNECT_STATE_ABBREV[2] = {
1227 '-', // not connected (false)
1228 'C', // connected (true)
1229 };
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001230 const char RECEIVE_STATE_ABBREV[2] = {
1231 '-', // not receiving (false)
1232 'R', // receiving (true)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001233 };
1234 const char WRITE_STATE_ABBREV[4] = {
1235 'W', // STATE_WRITABLE
1236 'w', // STATE_WRITE_UNRELIABLE
1237 '-', // STATE_WRITE_INIT
1238 'x', // STATE_WRITE_TIMEOUT
1239 };
1240 const std::string ICESTATE[4] = {
1241 "W", // STATE_WAITING
1242 "I", // STATE_INPROGRESS
1243 "S", // STATE_SUCCEEDED
1244 "F" // STATE_FAILED
1245 };
1246 const Candidate& local = local_candidate();
1247 const Candidate& remote = remote_candidate();
1248 std::stringstream ss;
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +00001249 ss << "Conn[" << ToDebugId()
1250 << ":" << port_->content_name()
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001251 << ":" << local.id() << ":" << local.component()
1252 << ":" << local.generation()
1253 << ":" << local.type() << ":" << local.protocol()
1254 << ":" << local.address().ToSensitiveString()
1255 << "->" << remote.id() << ":" << remote.component()
1256 << ":" << remote.priority()
1257 << ":" << remote.type() << ":"
1258 << remote.protocol() << ":" << remote.address().ToSensitiveString() << "|"
1259 << CONNECT_STATE_ABBREV[connected()]
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001260 << RECEIVE_STATE_ABBREV[receiving()]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001261 << WRITE_STATE_ABBREV[write_state()]
1262 << ICESTATE[state()] << "|"
1263 << priority() << "|";
1264 if (rtt_ < DEFAULT_RTT) {
1265 ss << rtt_ << "]";
1266 } else {
1267 ss << "-]";
1268 }
1269 return ss.str();
1270}
1271
1272std::string Connection::ToSensitiveString() const {
1273 return ToString();
1274}
1275
1276void Connection::OnConnectionRequestResponse(ConnectionRequest* request,
1277 StunMessage* response) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001278 // Log at LS_INFO if we receive a ping response on an unwritable
1279 // connection.
1280 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1281
honghaiz34b11eb2016-03-16 08:55:44 -07001282 int rtt = request->Elapsed();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001283
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001284 ReceivedPingResponse();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001285
Peter Thatcherb2d26232015-05-15 11:25:14 -07001286 if (LOG_CHECK_LEVEL_V(sev)) {
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001287 bool use_candidate = (
1288 response->GetByteString(STUN_ATTR_USE_CANDIDATE) != nullptr);
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001289 std::string pings;
1290 PrintPingsSinceLastResponse(&pings, 5);
1291 LOG_JV(sev, this) << "Received STUN ping response"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001292 << ", id=" << rtc::hex_encode(request->id())
1293 << ", code=0" // Makes logging easier to parse.
1294 << ", rtt=" << rtt
1295 << ", use_candidate=" << use_candidate
1296 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001297 }
1298
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001299 rtt_ = (RTT_RATIO * rtt_ + rtt) / (RTT_RATIO + 1);
1300
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001301 MaybeAddPrflxCandidate(request, response);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001302}
1303
1304void Connection::OnConnectionRequestErrorResponse(ConnectionRequest* request,
1305 StunMessage* response) {
1306 const StunErrorCodeAttribute* error_attr = response->GetErrorCode();
1307 int error_code = STUN_ERROR_GLOBAL_FAILURE;
1308 if (error_attr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001309 error_code = error_attr->code();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001310 }
1311
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001312 LOG_J(LS_INFO, this) << "Received STUN error response"
1313 << " id=" << rtc::hex_encode(request->id())
1314 << " code=" << error_code
1315 << " rtt=" << request->Elapsed();
1316
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001317 if (error_code == STUN_ERROR_UNKNOWN_ATTRIBUTE ||
1318 error_code == STUN_ERROR_SERVER_ERROR ||
1319 error_code == STUN_ERROR_UNAUTHORIZED) {
1320 // Recoverable error, retry
1321 } else if (error_code == STUN_ERROR_STALE_CREDENTIALS) {
1322 // Race failure, retry
1323 } else if (error_code == STUN_ERROR_ROLE_CONFLICT) {
1324 HandleRoleConflictFromPeer();
1325 } else {
1326 // This is not a valid connection.
1327 LOG_J(LS_ERROR, this) << "Received STUN error response, code="
1328 << error_code << "; killing connection";
deadbeef376e1232015-11-25 09:00:08 -08001329 FailAndDestroy();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001330 }
1331}
1332
1333void Connection::OnConnectionRequestTimeout(ConnectionRequest* request) {
1334 // Log at LS_INFO if we miss a ping on a writable connection.
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001335 rtc::LoggingSeverity sev = writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1336 LOG_JV(sev, this) << "Timing-out STUN ping "
1337 << rtc::hex_encode(request->id())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001338 << " after " << request->Elapsed() << " ms";
1339}
1340
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001341void Connection::OnConnectionRequestSent(ConnectionRequest* request) {
1342 // Log at LS_INFO if we send a ping on an unwritable connection.
1343 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001344 bool use_candidate = use_candidate_attr();
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001345 LOG_JV(sev, this) << "Sent STUN ping"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001346 << ", id=" << rtc::hex_encode(request->id())
1347 << ", use_candidate=" << use_candidate;
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001348}
1349
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001350void Connection::HandleRoleConflictFromPeer() {
1351 port_->SignalRoleConflict(port_);
1352}
1353
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001354void Connection::MaybeSetRemoteIceCredentialsAndGeneration(
1355 const std::string& ice_ufrag,
1356 const std::string& ice_pwd,
1357 int generation) {
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001358 if (remote_candidate_.username() == ice_ufrag &&
1359 remote_candidate_.password().empty()) {
1360 remote_candidate_.set_password(ice_pwd);
1361 }
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -07001362 // TODO(deadbeef): A value of '0' for the generation is used for both
1363 // generation 0 and "generation unknown". It should be changed to an
1364 // rtc::Optional to fix this.
1365 if (remote_candidate_.username() == ice_ufrag &&
1366 remote_candidate_.password() == ice_pwd &&
1367 remote_candidate_.generation() == 0) {
1368 remote_candidate_.set_generation(generation);
1369 }
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001370}
1371
1372void Connection::MaybeUpdatePeerReflexiveCandidate(
1373 const Candidate& new_candidate) {
1374 if (remote_candidate_.type() == PRFLX_PORT_TYPE &&
1375 new_candidate.type() != PRFLX_PORT_TYPE &&
1376 remote_candidate_.protocol() == new_candidate.protocol() &&
1377 remote_candidate_.address() == new_candidate.address() &&
1378 remote_candidate_.username() == new_candidate.username() &&
1379 remote_candidate_.password() == new_candidate.password() &&
1380 remote_candidate_.generation() == new_candidate.generation()) {
1381 remote_candidate_ = new_candidate;
1382 }
1383}
1384
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001385void Connection::OnMessage(rtc::Message *pmsg) {
1386 ASSERT(pmsg->message_id == MSG_DELETE);
honghaizd0b31432015-09-30 12:42:17 -07001387 LOG_J(LS_INFO, this) << "Connection deleted";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001388 SignalDestroyed(this);
1389 delete this;
1390}
1391
honghaiz34b11eb2016-03-16 08:55:44 -07001392int64_t Connection::last_received() const {
Peter Thatcher54360512015-07-08 11:08:35 -07001393 return std::max(last_data_received_,
1394 std::max(last_ping_received_, last_ping_response_received_));
1395}
1396
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001397size_t Connection::recv_bytes_second() {
Tim Psiakiad13d2f2015-11-10 16:34:50 -08001398 return round(recv_rate_tracker_.ComputeRate());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001399}
1400
1401size_t Connection::recv_total_bytes() {
Tim Psiaki63046262015-09-14 10:38:08 -07001402 return recv_rate_tracker_.TotalSampleCount();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001403}
1404
1405size_t Connection::sent_bytes_second() {
Tim Psiakiad13d2f2015-11-10 16:34:50 -08001406 return round(send_rate_tracker_.ComputeRate());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001407}
1408
1409size_t Connection::sent_total_bytes() {
Tim Psiaki63046262015-09-14 10:38:08 -07001410 return send_rate_tracker_.TotalSampleCount();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001411}
1412
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001413size_t Connection::sent_discarded_packets() {
1414 return sent_packets_discarded_;
1415}
1416
1417size_t Connection::sent_total_packets() {
1418 return sent_packets_total_;
1419}
1420
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001421void Connection::MaybeAddPrflxCandidate(ConnectionRequest* request,
1422 StunMessage* response) {
1423 // RFC 5245
1424 // The agent checks the mapped address from the STUN response. If the
1425 // transport address does not match any of the local candidates that the
1426 // agent knows about, the mapped address represents a new candidate -- a
1427 // peer reflexive candidate.
1428 const StunAddressAttribute* addr =
1429 response->GetAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
1430 if (!addr) {
1431 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1432 << "No MAPPED-ADDRESS or XOR-MAPPED-ADDRESS found in the "
1433 << "stun response message";
1434 return;
1435 }
1436
1437 bool known_addr = false;
1438 for (size_t i = 0; i < port_->Candidates().size(); ++i) {
1439 if (port_->Candidates()[i].address() == addr->GetAddress()) {
1440 known_addr = true;
1441 break;
1442 }
1443 }
1444 if (known_addr) {
1445 return;
1446 }
1447
1448 // RFC 5245
1449 // Its priority is set equal to the value of the PRIORITY attribute
1450 // in the Binding request.
1451 const StunUInt32Attribute* priority_attr =
1452 request->msg()->GetUInt32(STUN_ATTR_PRIORITY);
1453 if (!priority_attr) {
1454 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1455 << "No STUN_ATTR_PRIORITY found in the "
1456 << "stun response message";
1457 return;
1458 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001459 const uint32_t priority = priority_attr->value();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001460 std::string id = rtc::CreateRandomString(8);
1461
1462 Candidate new_local_candidate;
1463 new_local_candidate.set_id(id);
1464 new_local_candidate.set_component(local_candidate().component());
1465 new_local_candidate.set_type(PRFLX_PORT_TYPE);
1466 new_local_candidate.set_protocol(local_candidate().protocol());
1467 new_local_candidate.set_address(addr->GetAddress());
1468 new_local_candidate.set_priority(priority);
1469 new_local_candidate.set_username(local_candidate().username());
1470 new_local_candidate.set_password(local_candidate().password());
1471 new_local_candidate.set_network_name(local_candidate().network_name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001472 new_local_candidate.set_network_type(local_candidate().network_type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001473 new_local_candidate.set_related_address(local_candidate().address());
Honghai Zhang80f1db92016-01-27 11:54:45 -08001474 new_local_candidate.set_foundation(ComputeFoundation(
1475 PRFLX_PORT_TYPE, local_candidate().protocol(),
1476 local_candidate().relay_protocol(), local_candidate().address()));
honghaiza0c44ea2016-03-23 16:07:48 -07001477 new_local_candidate.set_network_id(local_candidate().network_id());
1478 new_local_candidate.set_network_cost(local_candidate().network_cost());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001479
1480 // Change the local candidate of this Connection to the new prflx candidate.
1481 local_candidate_index_ = port_->AddPrflxCandidate(new_local_candidate);
1482
1483 // SignalStateChange to force a re-sort in P2PTransportChannel as this
1484 // Connection's local candidate has changed.
1485 SignalStateChange(this);
1486}
1487
deadbeef376e1232015-11-25 09:00:08 -08001488ProxyConnection::ProxyConnection(Port* port,
1489 size_t index,
1490 const Candidate& remote_candidate)
1491 : Connection(port, index, remote_candidate) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001492
1493int ProxyConnection::Send(const void* data, size_t size,
1494 const rtc::PacketOptions& options) {
1495 if (write_state_ == STATE_WRITE_INIT || write_state_ == STATE_WRITE_TIMEOUT) {
1496 error_ = EWOULDBLOCK;
1497 return SOCKET_ERROR;
1498 }
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001499 sent_packets_total_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001500 int sent = port_->SendTo(data, size, remote_candidate_.address(),
1501 options, true);
1502 if (sent <= 0) {
1503 ASSERT(sent < 0);
1504 error_ = port_->GetError();
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001505 sent_packets_discarded_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001506 } else {
Tim Psiaki63046262015-09-14 10:38:08 -07001507 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001508 }
1509 return sent;
1510}
1511
1512} // namespace cricket