blob: ce2855106caa8c9384271f3b1687c343061a5ce9 [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"
23#include "webrtc/base/scoped_ptr.h"
24#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,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000033 uint32 maximum_failures,
34 uint32 rtt_estimate,
35 uint32 now) {
36
37 // If we haven't sent that many pings, then we can't have failed that many.
38 if (pings_since_last_response.size() < maximum_failures)
39 return false;
40
41 // Check if the window in which we would expect a response to the ping has
42 // already elapsed.
Peter Thatcher1cf6f812015-05-15 10:40:45 -070043 uint32 expected_response_time =
44 pings_since_last_response[maximum_failures - 1].sent_time + rtt_estimate;
45 return now > expected_response_time;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000046}
47
48// Determines whether we have gone too long without seeing any response.
49inline bool TooLongWithoutResponse(
Peter Thatcher1cf6f812015-05-15 10:40:45 -070050 const std::vector<cricket::Connection::SentPing>& pings_since_last_response,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000051 uint32 maximum_time,
52 uint32 now) {
53
54 if (pings_since_last_response.size() == 0)
55 return false;
56
Peter Thatcher1cf6f812015-05-15 10:40:45 -070057 auto first = pings_since_last_response[0];
58 return now > (first.sent_time + maximum_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000059}
60
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000061// We will restrict RTT estimates (when used for determining state) to be
62// within a reasonable range.
63const uint32 MINIMUM_RTT = 100; // 0.1 seconds
64const uint32 MAXIMUM_RTT = 3000; // 3 seconds
65
66// When we don't have any RTT data, we have to pick something reasonable. We
67// use a large value just in case the connection is really slow.
68const uint32 DEFAULT_RTT = MAXIMUM_RTT;
69
70// Computes our estimate of the RTT given the current estimate.
71inline uint32 ConservativeRTTEstimate(uint32 rtt) {
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000072 return std::max(MINIMUM_RTT, std::min(MAXIMUM_RTT, 2 * rtt));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000073}
74
75// Weighting of the old rtt value to new data.
76const int RTT_RATIO = 3; // 3 : 1
77
78// The delay before we begin checking if this port is useless.
79const int kPortTimeoutDelay = 30 * 1000; // 30 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000080}
81
82namespace cricket {
83
84// TODO(ronghuawu): Use "host", "srflx", "prflx" and "relay". But this requires
85// the signaling part be updated correspondingly as well.
86const char LOCAL_PORT_TYPE[] = "local";
87const char STUN_PORT_TYPE[] = "stun";
88const char PRFLX_PORT_TYPE[] = "prflx";
89const char RELAY_PORT_TYPE[] = "relay";
90
91const char UDP_PROTOCOL_NAME[] = "udp";
92const char TCP_PROTOCOL_NAME[] = "tcp";
93const char SSLTCP_PROTOCOL_NAME[] = "ssltcp";
94
95static const char* const PROTO_NAMES[] = { UDP_PROTOCOL_NAME,
96 TCP_PROTOCOL_NAME,
97 SSLTCP_PROTOCOL_NAME };
98
99const char* ProtoToString(ProtocolType proto) {
100 return PROTO_NAMES[proto];
101}
102
103bool StringToProto(const char* value, ProtocolType* proto) {
104 for (size_t i = 0; i <= PROTO_LAST; ++i) {
105 if (_stricmp(PROTO_NAMES[i], value) == 0) {
106 *proto = static_cast<ProtocolType>(i);
107 return true;
108 }
109 }
110 return false;
111}
112
113// RFC 6544, TCP candidate encoding rules.
114const int DISCARD_PORT = 9;
115const char TCPTYPE_ACTIVE_STR[] = "active";
116const char TCPTYPE_PASSIVE_STR[] = "passive";
117const char TCPTYPE_SIMOPEN_STR[] = "so";
118
119// Foundation: An arbitrary string that is the same for two candidates
120// that have the same type, base IP address, protocol (UDP, TCP,
121// etc.), and STUN or TURN server. If any of these are different,
122// then the foundation will be different. Two candidate pairs with
123// the same foundation pairs are likely to have similar network
124// characteristics. Foundations are used in the frozen algorithm.
125static std::string ComputeFoundation(
126 const std::string& type,
127 const std::string& protocol,
128 const rtc::SocketAddress& base_address) {
129 std::ostringstream ost;
130 ost << type << base_address.ipaddr().ToString() << protocol;
131 return rtc::ToString<uint32>(rtc::ComputeCrc32(ost.str()));
132}
133
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000134Port::Port(rtc::Thread* thread,
135 rtc::PacketSocketFactory* factory,
136 rtc::Network* network,
137 const rtc::IPAddress& ip,
138 const std::string& username_fragment,
139 const std::string& password)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000140 : thread_(thread),
141 factory_(factory),
142 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),
155 shared_socket_(true),
156 candidate_filter_(CF_ALL) {
157 Construct();
158}
159
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000160Port::Port(rtc::Thread* thread,
161 const std::string& type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000162 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000163 rtc::Network* network,
164 const rtc::IPAddress& ip,
165 uint16 min_port,
166 uint16 max_port,
167 const std::string& username_fragment,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000168 const std::string& password)
169 : thread_(thread),
170 factory_(factory),
171 type_(type),
172 send_retransmit_count_attribute_(false),
173 network_(network),
174 ip_(ip),
175 min_port_(min_port),
176 max_port_(max_port),
177 component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
178 generation_(0),
179 ice_username_fragment_(username_fragment),
180 password_(password),
181 timeout_delay_(kPortTimeoutDelay),
182 enable_port_packets_(false),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000183 ice_role_(ICEROLE_UNKNOWN),
184 tiebreaker_(0),
185 shared_socket_(false),
186 candidate_filter_(CF_ALL) {
187 ASSERT(factory_ != NULL);
188 Construct();
189}
190
191void Port::Construct() {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700192 // TODO(pthatcher): Remove this old behavior once we're sure no one
193 // relies on it. If the username_fragment and password are empty,
194 // we should just create one.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000195 if (ice_username_fragment_.empty()) {
196 ASSERT(password_.empty());
197 ice_username_fragment_ = rtc::CreateRandomString(ICE_UFRAG_LENGTH);
198 password_ = rtc::CreateRandomString(ICE_PWD_LENGTH);
199 }
200 LOG_J(LS_INFO, this) << "Port created";
201}
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
215 for (uint32 i = 0; i < list.size(); i++)
216 delete list[i];
217}
218
219Connection* Port::GetConnection(const rtc::SocketAddress& remote_addr) {
220 AddressMap::const_iterator iter = connections_.find(remote_addr);
221 if (iter != connections_.end())
222 return iter->second;
223 else
224 return NULL;
225}
226
227void Port::AddAddress(const rtc::SocketAddress& address,
228 const rtc::SocketAddress& base_address,
229 const rtc::SocketAddress& related_address,
230 const std::string& protocol,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700231 const std::string& relay_protocol,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000232 const std::string& tcptype,
233 const std::string& type,
234 uint32 type_preference,
235 uint32 relay_preference,
236 bool final) {
237 if (protocol == TCP_PROTOCOL_NAME && type == LOCAL_PORT_TYPE) {
238 ASSERT(!tcptype.empty());
239 }
240
241 Candidate c;
242 c.set_id(rtc::CreateRandomString(8));
243 c.set_component(component_);
244 c.set_type(type);
245 c.set_protocol(protocol);
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700246 c.set_relay_protocol(relay_protocol);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000247 c.set_tcptype(tcptype);
248 c.set_address(address);
249 c.set_priority(c.GetPriority(type_preference, network_->preference(),
250 relay_preference));
251 c.set_username(username_fragment());
252 c.set_password(password_);
253 c.set_network_name(network_->name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +0000254 c.set_network_type(network_->type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000255 c.set_generation(generation_);
256 c.set_related_address(related_address);
257 c.set_foundation(ComputeFoundation(type, protocol, base_address));
258 candidates_.push_back(c);
259 SignalCandidateReady(this, c);
260
261 if (final) {
262 SignalPortComplete(this);
263 }
264}
265
266void Port::AddConnection(Connection* conn) {
267 connections_[conn->remote_candidate().address()] = conn;
268 conn->SignalDestroyed.connect(this, &Port::OnConnectionDestroyed);
269 SignalConnectionCreated(this, conn);
270}
271
272void Port::OnReadPacket(
273 const char* data, size_t size, const rtc::SocketAddress& addr,
274 ProtocolType proto) {
275 // If the user has enabled port packets, just hand this over.
276 if (enable_port_packets_) {
277 SignalReadPacket(this, data, size, addr);
278 return;
279 }
280
281 // If this is an authenticated STUN request, then signal unknown address and
282 // send back a proper binding response.
283 rtc::scoped_ptr<IceMessage> msg;
284 std::string remote_username;
285 if (!GetStunMessage(data, size, addr, msg.accept(), &remote_username)) {
286 LOG_J(LS_ERROR, this) << "Received non-STUN packet from unknown address ("
287 << addr.ToSensitiveString() << ")";
288 } else if (!msg) {
289 // STUN message handled already
290 } else if (msg->type() == STUN_BINDING_REQUEST) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700291 LOG(LS_INFO) << "Received STUN ping "
292 << " id=" << rtc::hex_encode(msg->transaction_id())
293 << " from unknown address " << addr.ToSensitiveString();
294
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000295 // Check for role conflicts.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700296 if (!MaybeIceRoleConflict(addr, msg.get(), remote_username)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000297 LOG(LS_INFO) << "Received conflicting role from the peer.";
298 return;
299 }
300
301 SignalUnknownAddress(this, addr, proto, msg.get(), remote_username, false);
302 } else {
303 // NOTE(tschmelcher): STUN_BINDING_RESPONSE is benign. It occurs if we
304 // pruned a connection for this port while it had STUN requests in flight,
305 // because we then get back responses for them, which this code correctly
306 // does not handle.
307 if (msg->type() != STUN_BINDING_RESPONSE) {
308 LOG_J(LS_ERROR, this) << "Received unexpected STUN message type ("
309 << msg->type() << ") from unknown address ("
310 << addr.ToSensitiveString() << ")";
311 }
312 }
313}
314
315void Port::OnReadyToSend() {
316 AddressMap::iterator iter = connections_.begin();
317 for (; iter != connections_.end(); ++iter) {
318 iter->second->OnReadyToSend();
319 }
320}
321
322size_t Port::AddPrflxCandidate(const Candidate& local) {
323 candidates_.push_back(local);
324 return (candidates_.size() - 1);
325}
326
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000327bool Port::GetStunMessage(const char* data, size_t size,
328 const rtc::SocketAddress& addr,
329 IceMessage** out_msg, std::string* out_username) {
330 // NOTE: This could clearly be optimized to avoid allocating any memory.
331 // However, at the data rates we'll be looking at on the client side,
332 // this probably isn't worth worrying about.
333 ASSERT(out_msg != NULL);
334 ASSERT(out_username != NULL);
335 *out_msg = NULL;
336 out_username->clear();
337
338 // Don't bother parsing the packet if we can tell it's not STUN.
339 // In ICE mode, all STUN packets will have a valid fingerprint.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700340 if (!StunMessage::ValidateFingerprint(data, size)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000341 return false;
342 }
343
344 // Parse the request message. If the packet is not a complete and correct
345 // STUN message, then ignore it.
346 rtc::scoped_ptr<IceMessage> stun_msg(new IceMessage());
347 rtc::ByteBuffer buf(data, size);
348 if (!stun_msg->Read(&buf) || (buf.Length() > 0)) {
349 return false;
350 }
351
352 if (stun_msg->type() == STUN_BINDING_REQUEST) {
353 // Check for the presence of USERNAME and MESSAGE-INTEGRITY (if ICE) first.
354 // If not present, fail with a 400 Bad Request.
355 if (!stun_msg->GetByteString(STUN_ATTR_USERNAME) ||
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700356 !stun_msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000357 LOG_J(LS_ERROR, this) << "Received STUN request without username/M-I "
358 << "from " << addr.ToSensitiveString();
359 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_BAD_REQUEST,
360 STUN_ERROR_REASON_BAD_REQUEST);
361 return true;
362 }
363
364 // If the username is bad or unknown, fail with a 401 Unauthorized.
365 std::string local_ufrag;
366 std::string remote_ufrag;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700367 if (!ParseStunUsername(stun_msg.get(), &local_ufrag, &remote_ufrag) ||
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000368 local_ufrag != username_fragment()) {
369 LOG_J(LS_ERROR, this) << "Received STUN request with bad local username "
370 << local_ufrag << " from "
371 << addr.ToSensitiveString();
372 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
373 STUN_ERROR_REASON_UNAUTHORIZED);
374 return true;
375 }
376
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000377 // If ICE, and the MESSAGE-INTEGRITY is bad, fail with a 401 Unauthorized
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700378 if (!stun_msg->ValidateMessageIntegrity(data, size, password_)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000379 LOG_J(LS_ERROR, this) << "Received STUN request with bad M-I "
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +0000380 << "from " << addr.ToSensitiveString()
381 << ", password_=" << password_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000382 SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
383 STUN_ERROR_REASON_UNAUTHORIZED);
384 return true;
385 }
386 out_username->assign(remote_ufrag);
387 } else if ((stun_msg->type() == STUN_BINDING_RESPONSE) ||
388 (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE)) {
389 if (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE) {
390 if (const StunErrorCodeAttribute* error_code = stun_msg->GetErrorCode()) {
391 LOG_J(LS_ERROR, this) << "Received STUN binding error:"
392 << " class=" << error_code->eclass()
393 << " number=" << error_code->number()
394 << " reason='" << error_code->reason() << "'"
395 << " from " << addr.ToSensitiveString();
396 // Return message to allow error-specific processing
397 } else {
398 LOG_J(LS_ERROR, this) << "Received STUN binding error without a error "
399 << "code from " << addr.ToSensitiveString();
400 return true;
401 }
402 }
403 // NOTE: Username should not be used in verifying response messages.
404 out_username->clear();
405 } else if (stun_msg->type() == STUN_BINDING_INDICATION) {
406 LOG_J(LS_VERBOSE, this) << "Received STUN binding indication:"
407 << " from " << addr.ToSensitiveString();
408 out_username->clear();
409 // No stun attributes will be verified, if it's stun indication message.
410 // Returning from end of the this method.
411 } else {
412 LOG_J(LS_ERROR, this) << "Received STUN packet with invalid type ("
413 << stun_msg->type() << ") from "
414 << addr.ToSensitiveString();
415 return true;
416 }
417
418 // Return the STUN message found.
419 *out_msg = stun_msg.release();
420 return true;
421}
422
423bool Port::IsCompatibleAddress(const rtc::SocketAddress& addr) {
424 int family = ip().family();
425 // We use single-stack sockets, so families must match.
426 if (addr.family() != family) {
427 return false;
428 }
429 // Link-local IPv6 ports can only connect to other link-local IPv6 ports.
Peter Thatcherb8b01432015-07-07 16:45:53 -0700430 if (family == AF_INET6 &&
431 (IPIsLinkLocal(ip()) != IPIsLinkLocal(addr.ipaddr()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000432 return false;
433 }
434 return true;
435}
436
437bool Port::ParseStunUsername(const StunMessage* stun_msg,
438 std::string* local_ufrag,
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700439 std::string* remote_ufrag) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000440 // The packet must include a username that either begins or ends with our
441 // fragment. It should begin with our fragment if it is a request and it
442 // should end with our fragment if it is a response.
443 local_ufrag->clear();
444 remote_ufrag->clear();
445 const StunByteStringAttribute* username_attr =
446 stun_msg->GetByteString(STUN_ATTR_USERNAME);
447 if (username_attr == NULL)
448 return false;
449
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700450 // RFRAG:LFRAG
451 const std::string username = username_attr->GetString();
452 size_t colon_pos = username.find(":");
453 if (colon_pos == std::string::npos) {
454 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000455 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000456
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700457 *local_ufrag = username.substr(0, colon_pos);
458 *remote_ufrag = username.substr(colon_pos + 1, username.size());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000459 return true;
460}
461
462bool Port::MaybeIceRoleConflict(
463 const rtc::SocketAddress& addr, IceMessage* stun_msg,
464 const std::string& remote_ufrag) {
465 // Validate ICE_CONTROLLING or ICE_CONTROLLED attributes.
466 bool ret = true;
467 IceRole remote_ice_role = ICEROLE_UNKNOWN;
468 uint64 remote_tiebreaker = 0;
469 const StunUInt64Attribute* stun_attr =
470 stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
471 if (stun_attr) {
472 remote_ice_role = ICEROLE_CONTROLLING;
473 remote_tiebreaker = stun_attr->value();
474 }
475
476 // If |remote_ufrag| is same as port local username fragment and
477 // tie breaker value received in the ping message matches port
478 // tiebreaker value this must be a loopback call.
479 // We will treat this as valid scenario.
480 if (remote_ice_role == ICEROLE_CONTROLLING &&
481 username_fragment() == remote_ufrag &&
482 remote_tiebreaker == IceTiebreaker()) {
483 return true;
484 }
485
486 stun_attr = stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
487 if (stun_attr) {
488 remote_ice_role = ICEROLE_CONTROLLED;
489 remote_tiebreaker = stun_attr->value();
490 }
491
492 switch (ice_role_) {
493 case ICEROLE_CONTROLLING:
494 if (ICEROLE_CONTROLLING == remote_ice_role) {
495 if (remote_tiebreaker >= tiebreaker_) {
496 SignalRoleConflict(this);
497 } else {
498 // Send Role Conflict (487) error response.
499 SendBindingErrorResponse(stun_msg, addr,
500 STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
501 ret = false;
502 }
503 }
504 break;
505 case ICEROLE_CONTROLLED:
506 if (ICEROLE_CONTROLLED == remote_ice_role) {
507 if (remote_tiebreaker < tiebreaker_) {
508 SignalRoleConflict(this);
509 } else {
510 // Send Role Conflict (487) error response.
511 SendBindingErrorResponse(stun_msg, addr,
512 STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
513 ret = false;
514 }
515 }
516 break;
517 default:
518 ASSERT(false);
519 }
520 return ret;
521}
522
523void Port::CreateStunUsername(const std::string& remote_username,
524 std::string* stun_username_attr_str) const {
525 stun_username_attr_str->clear();
526 *stun_username_attr_str = remote_username;
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700527 stun_username_attr_str->append(":");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000528 stun_username_attr_str->append(username_fragment());
529}
530
531void Port::SendBindingResponse(StunMessage* request,
532 const rtc::SocketAddress& addr) {
533 ASSERT(request->type() == STUN_BINDING_REQUEST);
534
535 // Retrieve the username from the request.
536 const StunByteStringAttribute* username_attr =
537 request->GetByteString(STUN_ATTR_USERNAME);
538 ASSERT(username_attr != NULL);
539 if (username_attr == NULL) {
540 // No valid username, skip the response.
541 return;
542 }
543
544 // Fill in the response message.
545 StunMessage response;
546 response.SetType(STUN_BINDING_RESPONSE);
547 response.SetTransactionID(request->transaction_id());
548 const StunUInt32Attribute* retransmit_attr =
549 request->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
550 if (retransmit_attr) {
551 // Inherit the incoming retransmit value in the response so the other side
552 // can see our view of lost pings.
553 response.AddAttribute(new StunUInt32Attribute(
554 STUN_ATTR_RETRANSMIT_COUNT, retransmit_attr->value()));
555
556 if (retransmit_attr->value() > CONNECTION_WRITE_CONNECT_FAILURES) {
557 LOG_J(LS_INFO, this)
558 << "Received a remote ping with high retransmit count: "
559 << retransmit_attr->value();
560 }
561 }
562
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700563 response.AddAttribute(
564 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, addr));
565 response.AddMessageIntegrity(password_);
566 response.AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000567
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700568 // The fact that we received a successful request means that this connection
honghaizd0b31432015-09-30 12:42:17 -0700569 // (if one exists) should now be receiving.
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700570 Connection* conn = GetConnection(addr);
571
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000572 // Send the response message.
573 rtc::ByteBuffer buf;
574 response.Write(&buf);
575 rtc::PacketOptions options(DefaultDscpValue());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700576 auto err = SendTo(buf.Data(), buf.Length(), addr, options, false);
577 if (err < 0) {
578 LOG_J(LS_ERROR, this)
579 << "Failed to send STUN ping response"
580 << ", to=" << addr.ToSensitiveString()
581 << ", err=" << err
582 << ", id=" << rtc::hex_encode(response.transaction_id());
583 } else {
584 // Log at LS_INFO if we send a stun ping response on an unwritable
585 // connection.
586 rtc::LoggingSeverity sev = (conn && !conn->writable()) ?
587 rtc::LS_INFO : rtc::LS_VERBOSE;
588 LOG_JV(sev, this)
589 << "Sent STUN ping response"
590 << ", to=" << addr.ToSensitiveString()
591 << ", id=" << rtc::hex_encode(response.transaction_id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000592 }
593
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000594 ASSERT(conn != NULL);
595 if (conn)
596 conn->ReceivedPing();
597}
598
599void Port::SendBindingErrorResponse(StunMessage* request,
600 const rtc::SocketAddress& addr,
601 int error_code, const std::string& reason) {
602 ASSERT(request->type() == STUN_BINDING_REQUEST);
603
604 // Fill in the response message.
605 StunMessage response;
606 response.SetType(STUN_BINDING_ERROR_RESPONSE);
607 response.SetTransactionID(request->transaction_id());
608
609 // When doing GICE, we need to write out the error code incorrectly to
610 // maintain backwards compatiblility.
611 StunErrorCodeAttribute* error_attr = StunAttribute::CreateErrorCode();
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700612 error_attr->SetCode(error_code);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000613 error_attr->SetReason(reason);
614 response.AddAttribute(error_attr);
615
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700616 // Per Section 10.1.2, certain error cases don't get a MESSAGE-INTEGRITY,
617 // because we don't have enough information to determine the shared secret.
618 if (error_code != STUN_ERROR_BAD_REQUEST &&
619 error_code != STUN_ERROR_UNAUTHORIZED)
620 response.AddMessageIntegrity(password_);
621 response.AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000622
623 // Send the response message.
624 rtc::ByteBuffer buf;
625 response.Write(&buf);
626 rtc::PacketOptions options(DefaultDscpValue());
627 SendTo(buf.Data(), buf.Length(), addr, options, false);
628 LOG_J(LS_INFO, this) << "Sending STUN binding error: reason=" << reason
629 << " to " << addr.ToSensitiveString();
630}
631
632void Port::OnMessage(rtc::Message *pmsg) {
honghaizd0b31432015-09-30 12:42:17 -0700633 ASSERT(pmsg->message_id == MSG_DEAD);
634 if (dead()) {
635 Destroy();
636 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000637}
638
639std::string Port::ToString() const {
640 std::stringstream ss;
641 ss << "Port[" << content_name_ << ":" << component_
642 << ":" << generation_ << ":" << type_
643 << ":" << network_->ToString() << "]";
644 return ss.str();
645}
646
647void Port::EnablePortPackets() {
648 enable_port_packets_ = true;
649}
650
651void Port::OnConnectionDestroyed(Connection* conn) {
652 AddressMap::iterator iter =
653 connections_.find(conn->remote_candidate().address());
654 ASSERT(iter != connections_.end());
655 connections_.erase(iter);
656
honghaizd0b31432015-09-30 12:42:17 -0700657 // On the controlled side, ports time out after all connections fail.
658 // Note: If a new connection is added after this message is posted, but it
659 // fails and is removed before kPortTimeoutDelay, then this message will
660 // still cause the Port to be destroyed.
661 if (dead()) {
662 thread_->PostDelayed(timeout_delay_, this, MSG_DEAD);
663 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000664}
665
666void Port::Destroy() {
667 ASSERT(connections_.empty());
668 LOG_J(LS_INFO, this) << "Port deleted";
669 SignalDestroyed(this);
670 delete this;
671}
672
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000673const std::string Port::username_fragment() const {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700674 return ice_username_fragment_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000675}
676
677// A ConnectionRequest is a simple STUN ping used to determine writability.
678class ConnectionRequest : public StunRequest {
679 public:
680 explicit ConnectionRequest(Connection* connection)
681 : StunRequest(new IceMessage()),
682 connection_(connection) {
683 }
684
685 virtual ~ConnectionRequest() {
686 }
687
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700688 void Prepare(StunMessage* request) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000689 request->SetType(STUN_BINDING_REQUEST);
690 std::string username;
691 connection_->port()->CreateStunUsername(
692 connection_->remote_candidate().username(), &username);
693 request->AddAttribute(
694 new StunByteStringAttribute(STUN_ATTR_USERNAME, username));
695
696 // connection_ already holds this ping, so subtract one from count.
697 if (connection_->port()->send_retransmit_count_attribute()) {
698 request->AddAttribute(new StunUInt32Attribute(
699 STUN_ATTR_RETRANSMIT_COUNT,
700 static_cast<uint32>(
701 connection_->pings_since_last_response_.size() - 1)));
702 }
703
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700704 // Adding ICE_CONTROLLED or ICE_CONTROLLING attribute based on the role.
705 if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLING) {
706 request->AddAttribute(new StunUInt64Attribute(
707 STUN_ATTR_ICE_CONTROLLING, connection_->port()->IceTiebreaker()));
708 // Since we are trying aggressive nomination, sending USE-CANDIDATE
709 // attribute in every ping.
710 // If we are dealing with a ice-lite end point, nomination flag
711 // in Connection will be set to false by default. Once the connection
712 // becomes "best connection", nomination flag will be turned on.
713 if (connection_->use_candidate_attr()) {
714 request->AddAttribute(new StunByteStringAttribute(
715 STUN_ATTR_USE_CANDIDATE));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000716 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700717 } else if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLED) {
718 request->AddAttribute(new StunUInt64Attribute(
719 STUN_ATTR_ICE_CONTROLLED, connection_->port()->IceTiebreaker()));
720 } else {
721 ASSERT(false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000722 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700723
724 // Adding PRIORITY Attribute.
725 // Changing the type preference to Peer Reflexive and local preference
726 // and component id information is unchanged from the original priority.
727 // priority = (2^24)*(type preference) +
728 // (2^8)*(local preference) +
729 // (2^0)*(256 - component ID)
730 uint32 prflx_priority = ICE_TYPE_PREFERENCE_PRFLX << 24 |
731 (connection_->local_candidate().priority() & 0x00FFFFFF);
732 request->AddAttribute(
733 new StunUInt32Attribute(STUN_ATTR_PRIORITY, prflx_priority));
734
735 // Adding Message Integrity attribute.
736 request->AddMessageIntegrity(connection_->remote_candidate().password());
737 // Adding Fingerprint.
738 request->AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000739 }
740
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700741 void OnResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000742 connection_->OnConnectionRequestResponse(this, response);
743 }
744
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700745 void OnErrorResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000746 connection_->OnConnectionRequestErrorResponse(this, response);
747 }
748
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700749 void OnTimeout() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000750 connection_->OnConnectionRequestTimeout(this);
751 }
752
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700753 void OnSent() override {
754 connection_->OnConnectionRequestSent(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000755 // Each request is sent only once. After a single delay , the request will
756 // time out.
757 timeout_ = true;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700758 }
759
760 int resend_delay() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000761 return CONNECTION_RESPONSE_TIMEOUT;
762 }
763
764 private:
765 Connection* connection_;
766};
767
768//
769// Connection
770//
771
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000772Connection::Connection(Port* port,
773 size_t index,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000774 const Candidate& remote_candidate)
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000775 : port_(port),
776 local_candidate_index_(index),
777 remote_candidate_(remote_candidate),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000778 write_state_(STATE_WRITE_INIT),
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700779 receiving_(false),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000780 connected_(true),
781 pruned_(false),
782 use_candidate_attr_(false),
honghaiz5a3acd82015-08-20 15:53:17 -0700783 nominated_(false),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000784 remote_ice_mode_(ICEMODE_FULL),
785 requests_(port->thread()),
786 rtt_(DEFAULT_RTT),
787 last_ping_sent_(0),
788 last_ping_received_(0),
789 last_data_received_(0),
790 last_ping_response_received_(0),
Tim Psiaki63046262015-09-14 10:38:08 -0700791 recv_rate_tracker_(100u, 10u),
792 send_rate_tracker_(100u, 10u),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000793 sent_packets_discarded_(0),
794 sent_packets_total_(0),
795 reported_(false),
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700796 state_(STATE_WAITING),
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700797 receiving_timeout_(WEAK_CONNECTION_RECEIVE_TIMEOUT),
798 time_created_ms_(rtc::Time()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000799 // All of our connections start in WAITING state.
800 // TODO(mallinath) - Start connections from STATE_FROZEN.
801 // Wire up to send stun packets
802 requests_.SignalSendPacket.connect(this, &Connection::OnSendStunPacket);
803 LOG_J(LS_INFO, this) << "Connection created";
804}
805
806Connection::~Connection() {
807}
808
809const Candidate& Connection::local_candidate() const {
810 ASSERT(local_candidate_index_ < port_->Candidates().size());
811 return port_->Candidates()[local_candidate_index_];
812}
813
814uint64 Connection::priority() const {
815 uint64 priority = 0;
816 // RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs
817 // Let G be the priority for the candidate provided by the controlling
818 // agent. Let D be the priority for the candidate provided by the
819 // controlled agent.
820 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
821 IceRole role = port_->GetIceRole();
822 if (role != ICEROLE_UNKNOWN) {
823 uint32 g = 0;
824 uint32 d = 0;
825 if (role == ICEROLE_CONTROLLING) {
826 g = local_candidate().priority();
827 d = remote_candidate_.priority();
828 } else {
829 g = remote_candidate_.priority();
830 d = local_candidate().priority();
831 }
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000832 priority = std::min(g, d);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000833 priority = priority << 32;
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000834 priority += 2 * std::max(g, d) + (g > d ? 1 : 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000835 }
836 return priority;
837}
838
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000839void Connection::set_write_state(WriteState value) {
840 WriteState old_value = write_state_;
841 write_state_ = value;
842 if (value != old_value) {
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +0000843 LOG_J(LS_VERBOSE, this) << "set_write_state from: " << old_value << " to "
844 << value;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000845 SignalStateChange(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000846 }
847}
848
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700849void Connection::set_receiving(bool value) {
850 if (value != receiving_) {
851 LOG_J(LS_VERBOSE, this) << "set_receiving to " << value;
852 receiving_ = value;
853 SignalStateChange(this);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700854 }
855}
856
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000857void Connection::set_state(State state) {
858 State old_state = state_;
859 state_ = state;
860 if (state != old_state) {
861 LOG_J(LS_VERBOSE, this) << "set_state";
862 }
863}
864
865void Connection::set_connected(bool value) {
866 bool old_value = connected_;
867 connected_ = value;
868 if (value != old_value) {
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700869 LOG_J(LS_VERBOSE, this) << "set_connected from: " << old_value << " to "
870 << value;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000871 }
872}
873
874void Connection::set_use_candidate_attr(bool enable) {
875 use_candidate_attr_ = enable;
876}
877
878void Connection::OnSendStunPacket(const void* data, size_t size,
879 StunRequest* req) {
880 rtc::PacketOptions options(port_->DefaultDscpValue());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700881 auto err = port_->SendTo(
882 data, size, remote_candidate_.address(), options, false);
883 if (err < 0) {
884 LOG_J(LS_WARNING, this) << "Failed to send STUN ping "
885 << " err=" << err
886 << " id=" << rtc::hex_encode(req->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000887 }
888}
889
890void Connection::OnReadPacket(
891 const char* data, size_t size, const rtc::PacketTime& packet_time) {
892 rtc::scoped_ptr<IceMessage> msg;
893 std::string remote_ufrag;
894 const rtc::SocketAddress& addr(remote_candidate_.address());
895 if (!port_->GetStunMessage(data, size, addr, msg.accept(), &remote_ufrag)) {
896 // The packet did not parse as a valid STUN message
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700897 // This is a data packet, pass it along.
898 set_receiving(true);
899 last_data_received_ = rtc::Time();
900 recv_rate_tracker_.AddSamples(size);
901 SignalReadPacket(this, data, size, packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000902
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700903 // If timed out sending writability checks, start up again
904 if (!pruned_ && (write_state_ == STATE_WRITE_TIMEOUT)) {
905 LOG(LS_WARNING) << "Received a data packet on a timed-out Connection. "
906 << "Resetting state to STATE_WRITE_INIT.";
907 set_write_state(STATE_WRITE_INIT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000908 }
909 } else if (!msg) {
910 // The packet was STUN, but failed a check and was handled internally.
911 } else {
912 // The packet is STUN and passed the Port checks.
913 // Perform our own checks to ensure this packet is valid.
honghaizd0b31432015-09-30 12:42:17 -0700914 // If this is a STUN request, then update the receiving bit and respond.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000915 // If this is a STUN response, then update the writable bit.
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700916 // Log at LS_INFO if we receive a ping on an unwritable connection.
917 rtc::LoggingSeverity sev = (!writable() ? rtc::LS_INFO : rtc::LS_VERBOSE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000918 switch (msg->type()) {
919 case STUN_BINDING_REQUEST:
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700920 LOG_JV(sev, this) << "Received STUN ping"
921 << ", id=" << rtc::hex_encode(msg->transaction_id());
922
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000923 if (remote_ufrag == remote_candidate_.username()) {
924 // Check for role conflicts.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700925 if (!port_->MaybeIceRoleConflict(addr, msg.get(), remote_ufrag)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000926 // Received conflicting role from the peer.
927 LOG(LS_INFO) << "Received conflicting role from the peer.";
928 return;
929 }
930
931 // Incoming, validated stun request from remote peer.
honghaizd0b31432015-09-30 12:42:17 -0700932 // This call will also set the connection receiving.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000933 port_->SendBindingResponse(msg.get(), addr);
934
935 // If timed out sending writability checks, start up again
936 if (!pruned_ && (write_state_ == STATE_WRITE_TIMEOUT))
937 set_write_state(STATE_WRITE_INIT);
938
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700939 if (port_->GetIceRole() == ICEROLE_CONTROLLED) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000940 const StunByteStringAttribute* use_candidate_attr =
941 msg->GetByteString(STUN_ATTR_USE_CANDIDATE);
honghaiz5a3acd82015-08-20 15:53:17 -0700942 if (use_candidate_attr) {
943 set_nominated(true);
944 SignalNominated(this);
945 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000946 }
947 } else {
948 // The packet had the right local username, but the remote username
949 // was not the right one for the remote address.
950 LOG_J(LS_ERROR, this)
951 << "Received STUN request with bad remote username "
952 << remote_ufrag;
953 port_->SendBindingErrorResponse(msg.get(), addr,
954 STUN_ERROR_UNAUTHORIZED,
955 STUN_ERROR_REASON_UNAUTHORIZED);
956
957 }
958 break;
959
960 // Response from remote peer. Does it match request sent?
961 // This doesn't just check, it makes callbacks if transaction
962 // id's match.
963 case STUN_BINDING_RESPONSE:
964 case STUN_BINDING_ERROR_RESPONSE:
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700965 if (msg->ValidateMessageIntegrity(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000966 data, size, remote_candidate().password())) {
967 requests_.CheckResponse(msg.get());
968 }
969 // Otherwise silently discard the response message.
970 break;
971
honghaizd0b31432015-09-30 12:42:17 -0700972 // Remote end point sent an STUN indication instead of regular binding
973 // request. In this case |last_ping_received_| will be updated but no
974 // response will be sent.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000975 case STUN_BINDING_INDICATION:
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700976 ReceivedPing();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000977 break;
978
979 default:
980 ASSERT(false);
981 break;
982 }
983 }
984}
985
986void Connection::OnReadyToSend() {
987 if (write_state_ == STATE_WRITABLE) {
988 SignalReadyToSend(this);
989 }
990}
991
992void Connection::Prune() {
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700993 if (!pruned_ || active()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000994 LOG_J(LS_VERBOSE, this) << "Connection pruned";
995 pruned_ = true;
996 requests_.Clear();
997 set_write_state(STATE_WRITE_TIMEOUT);
998 }
999}
1000
1001void Connection::Destroy() {
1002 LOG_J(LS_VERBOSE, this) << "Connection destroyed";
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001003 port_->thread()->Post(this, MSG_DELETE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001004}
1005
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001006void Connection::PrintPingsSinceLastResponse(std::string* s, size_t max) {
1007 std::ostringstream oss;
1008 oss << std::boolalpha;
1009 if (pings_since_last_response_.size() > max) {
1010 for (size_t i = 0; i < max; i++) {
1011 const SentPing& ping = pings_since_last_response_[i];
1012 oss << rtc::hex_encode(ping.id) << " ";
1013 }
1014 oss << "... " << (pings_since_last_response_.size() - max) << " more";
1015 } else {
1016 for (const SentPing& ping : pings_since_last_response_) {
1017 oss << rtc::hex_encode(ping.id) << " ";
1018 }
1019 }
1020 *s = oss.str();
1021}
1022
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001023void Connection::UpdateState(uint32 now) {
1024 uint32 rtt = ConservativeRTTEstimate(rtt_);
1025
Peter Thatcherb2d26232015-05-15 11:25:14 -07001026 if (LOG_CHECK_LEVEL(LS_VERBOSE)) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001027 std::string pings;
1028 PrintPingsSinceLastResponse(&pings, 5);
1029 LOG_J(LS_VERBOSE, this) << "UpdateState()"
1030 << ", ms since last received response="
1031 << now - last_ping_response_received_
1032 << ", ms since last received data="
1033 << now - last_data_received_
1034 << ", rtt=" << rtt
1035 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001036 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001037
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001038 // Check the writable state. (The order of these checks is important.)
1039 //
1040 // Before becoming unwritable, we allow for a fixed number of pings to fail
1041 // (i.e., receive no response). We also have to give the response time to
1042 // get back, so we include a conservative estimate of this.
1043 //
1044 // Before timing out writability, we give a fixed amount of time. This is to
1045 // allow for changes in network conditions.
1046
1047 if ((write_state_ == STATE_WRITABLE) &&
1048 TooManyFailures(pings_since_last_response_,
1049 CONNECTION_WRITE_CONNECT_FAILURES,
1050 rtt,
1051 now) &&
1052 TooLongWithoutResponse(pings_since_last_response_,
1053 CONNECTION_WRITE_CONNECT_TIMEOUT,
1054 now)) {
1055 uint32 max_pings = CONNECTION_WRITE_CONNECT_FAILURES;
1056 LOG_J(LS_INFO, this) << "Unwritable after " << max_pings
1057 << " ping failures and "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001058 << now - pings_since_last_response_[0].sent_time
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001059 << " ms without a response,"
1060 << " ms since last received ping="
1061 << now - last_ping_received_
1062 << " ms since last received data="
1063 << now - last_data_received_
1064 << " rtt=" << rtt;
1065 set_write_state(STATE_WRITE_UNRELIABLE);
1066 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001067 if ((write_state_ == STATE_WRITE_UNRELIABLE ||
1068 write_state_ == STATE_WRITE_INIT) &&
1069 TooLongWithoutResponse(pings_since_last_response_,
1070 CONNECTION_WRITE_TIMEOUT,
1071 now)) {
1072 LOG_J(LS_INFO, this) << "Timed out after "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001073 << now - pings_since_last_response_[0].sent_time
1074 << " ms without a response"
1075 << ", rtt=" << rtt;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001076 set_write_state(STATE_WRITE_TIMEOUT);
1077 }
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001078
1079 // Check the receiving state.
1080 uint32 last_recv_time = last_received();
1081 bool receiving = now <= last_recv_time + receiving_timeout_;
1082 set_receiving(receiving);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001083 if (dead(now)) {
1084 Destroy();
1085 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001086}
1087
1088void Connection::Ping(uint32 now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001089 last_ping_sent_ = now;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001090 ConnectionRequest *req = new ConnectionRequest(this);
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001091 pings_since_last_response_.push_back(SentPing(req->id(), now));
1092 LOG_J(LS_VERBOSE, this) << "Sending STUN ping "
1093 << ", id=" << rtc::hex_encode(req->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001094 requests_.Send(req);
1095 state_ = STATE_INPROGRESS;
1096}
1097
1098void Connection::ReceivedPing() {
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001099 set_receiving(true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001100 last_ping_received_ = rtc::Time();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001101}
1102
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001103void Connection::ReceivedPingResponse() {
1104 // We've already validated that this is a STUN binding response with
1105 // the correct local and remote username for this connection.
1106 // So if we're not already, become writable. We may be bringing a pruned
1107 // connection back to life, but if we don't really want it, we can always
1108 // prune it again.
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001109 set_receiving(true);
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001110 set_write_state(STATE_WRITABLE);
1111 set_state(STATE_SUCCEEDED);
1112 pings_since_last_response_.clear();
1113 last_ping_response_received_ = rtc::Time();
1114}
1115
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001116bool Connection::dead(uint32 now) const {
1117 if (now < (time_created_ms_ + MIN_CONNECTION_LIFETIME)) {
1118 // A connection that hasn't passed its minimum lifetime is still alive.
1119 // We do this to prevent connections from being pruned too quickly
1120 // during a network change event when two networks would be up
1121 // simultaneously but only for a brief period.
1122 return false;
1123 }
1124
1125 if (receiving_) {
1126 // A connection that is receiving is alive.
1127 return false;
1128 }
1129
1130 // A connection is alive until it is inactive.
1131 return !active();
1132
1133 // TODO(honghaiz): Move from using the write state to using the receiving
1134 // state with something like the following:
1135 // return (now > (last_received() + DEAD_CONNECTION_RECEIVE_TIMEOUT));
1136}
1137
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +00001138std::string Connection::ToDebugId() const {
1139 std::stringstream ss;
1140 ss << std::hex << this;
1141 return ss.str();
1142}
1143
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001144std::string Connection::ToString() const {
1145 const char CONNECT_STATE_ABBREV[2] = {
1146 '-', // not connected (false)
1147 'C', // connected (true)
1148 };
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001149 const char RECEIVE_STATE_ABBREV[2] = {
1150 '-', // not receiving (false)
1151 'R', // receiving (true)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001152 };
1153 const char WRITE_STATE_ABBREV[4] = {
1154 'W', // STATE_WRITABLE
1155 'w', // STATE_WRITE_UNRELIABLE
1156 '-', // STATE_WRITE_INIT
1157 'x', // STATE_WRITE_TIMEOUT
1158 };
1159 const std::string ICESTATE[4] = {
1160 "W", // STATE_WAITING
1161 "I", // STATE_INPROGRESS
1162 "S", // STATE_SUCCEEDED
1163 "F" // STATE_FAILED
1164 };
1165 const Candidate& local = local_candidate();
1166 const Candidate& remote = remote_candidate();
1167 std::stringstream ss;
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +00001168 ss << "Conn[" << ToDebugId()
1169 << ":" << port_->content_name()
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001170 << ":" << local.id() << ":" << local.component()
1171 << ":" << local.generation()
1172 << ":" << local.type() << ":" << local.protocol()
1173 << ":" << local.address().ToSensitiveString()
1174 << "->" << remote.id() << ":" << remote.component()
1175 << ":" << remote.priority()
1176 << ":" << remote.type() << ":"
1177 << remote.protocol() << ":" << remote.address().ToSensitiveString() << "|"
1178 << CONNECT_STATE_ABBREV[connected()]
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001179 << RECEIVE_STATE_ABBREV[receiving()]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001180 << WRITE_STATE_ABBREV[write_state()]
1181 << ICESTATE[state()] << "|"
1182 << priority() << "|";
1183 if (rtt_ < DEFAULT_RTT) {
1184 ss << rtt_ << "]";
1185 } else {
1186 ss << "-]";
1187 }
1188 return ss.str();
1189}
1190
1191std::string Connection::ToSensitiveString() const {
1192 return ToString();
1193}
1194
1195void Connection::OnConnectionRequestResponse(ConnectionRequest* request,
1196 StunMessage* response) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001197 // Log at LS_INFO if we receive a ping response on an unwritable
1198 // connection.
1199 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1200
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001201 uint32 rtt = request->Elapsed();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001202
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001203 ReceivedPingResponse();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001204
Peter Thatcherb2d26232015-05-15 11:25:14 -07001205 if (LOG_CHECK_LEVEL_V(sev)) {
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001206 bool use_candidate = (
1207 response->GetByteString(STUN_ATTR_USE_CANDIDATE) != nullptr);
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001208 std::string pings;
1209 PrintPingsSinceLastResponse(&pings, 5);
1210 LOG_JV(sev, this) << "Received STUN ping response"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001211 << ", id=" << rtc::hex_encode(request->id())
1212 << ", code=0" // Makes logging easier to parse.
1213 << ", rtt=" << rtt
1214 << ", use_candidate=" << use_candidate
1215 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001216 }
1217
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001218 rtt_ = (RTT_RATIO * rtt_ + rtt) / (RTT_RATIO + 1);
1219
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001220 MaybeAddPrflxCandidate(request, response);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001221}
1222
1223void Connection::OnConnectionRequestErrorResponse(ConnectionRequest* request,
1224 StunMessage* response) {
1225 const StunErrorCodeAttribute* error_attr = response->GetErrorCode();
1226 int error_code = STUN_ERROR_GLOBAL_FAILURE;
1227 if (error_attr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001228 error_code = error_attr->code();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001229 }
1230
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001231 LOG_J(LS_INFO, this) << "Received STUN error response"
1232 << " id=" << rtc::hex_encode(request->id())
1233 << " code=" << error_code
1234 << " rtt=" << request->Elapsed();
1235
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001236 if (error_code == STUN_ERROR_UNKNOWN_ATTRIBUTE ||
1237 error_code == STUN_ERROR_SERVER_ERROR ||
1238 error_code == STUN_ERROR_UNAUTHORIZED) {
1239 // Recoverable error, retry
1240 } else if (error_code == STUN_ERROR_STALE_CREDENTIALS) {
1241 // Race failure, retry
1242 } else if (error_code == STUN_ERROR_ROLE_CONFLICT) {
1243 HandleRoleConflictFromPeer();
1244 } else {
1245 // This is not a valid connection.
1246 LOG_J(LS_ERROR, this) << "Received STUN error response, code="
1247 << error_code << "; killing connection";
1248 set_state(STATE_FAILED);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001249 Destroy();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001250 }
1251}
1252
1253void Connection::OnConnectionRequestTimeout(ConnectionRequest* request) {
1254 // Log at LS_INFO if we miss a ping on a writable connection.
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001255 rtc::LoggingSeverity sev = writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1256 LOG_JV(sev, this) << "Timing-out STUN ping "
1257 << rtc::hex_encode(request->id())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001258 << " after " << request->Elapsed() << " ms";
1259}
1260
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001261void Connection::OnConnectionRequestSent(ConnectionRequest* request) {
1262 // Log at LS_INFO if we send a ping on an unwritable connection.
1263 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001264 bool use_candidate = use_candidate_attr();
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001265 LOG_JV(sev, this) << "Sent STUN ping"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001266 << ", id=" << rtc::hex_encode(request->id())
1267 << ", use_candidate=" << use_candidate;
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001268}
1269
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001270void Connection::HandleRoleConflictFromPeer() {
1271 port_->SignalRoleConflict(port_);
1272}
1273
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001274void Connection::MaybeSetRemoteIceCredentials(const std::string& ice_ufrag,
1275 const std::string& ice_pwd) {
1276 if (remote_candidate_.username() == ice_ufrag &&
1277 remote_candidate_.password().empty()) {
1278 remote_candidate_.set_password(ice_pwd);
1279 }
1280}
1281
1282void Connection::MaybeUpdatePeerReflexiveCandidate(
1283 const Candidate& new_candidate) {
1284 if (remote_candidate_.type() == PRFLX_PORT_TYPE &&
1285 new_candidate.type() != PRFLX_PORT_TYPE &&
1286 remote_candidate_.protocol() == new_candidate.protocol() &&
1287 remote_candidate_.address() == new_candidate.address() &&
1288 remote_candidate_.username() == new_candidate.username() &&
1289 remote_candidate_.password() == new_candidate.password() &&
1290 remote_candidate_.generation() == new_candidate.generation()) {
1291 remote_candidate_ = new_candidate;
1292 }
1293}
1294
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001295void Connection::OnMessage(rtc::Message *pmsg) {
1296 ASSERT(pmsg->message_id == MSG_DELETE);
honghaizd0b31432015-09-30 12:42:17 -07001297 LOG_J(LS_INFO, this) << "Connection deleted";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001298 SignalDestroyed(this);
1299 delete this;
1300}
1301
Peter Thatcher54360512015-07-08 11:08:35 -07001302uint32 Connection::last_received() {
1303 return std::max(last_data_received_,
1304 std::max(last_ping_received_, last_ping_response_received_));
1305}
1306
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001307size_t Connection::recv_bytes_second() {
Tim Psiaki63046262015-09-14 10:38:08 -07001308 return recv_rate_tracker_.ComputeRate();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001309}
1310
1311size_t Connection::recv_total_bytes() {
Tim Psiaki63046262015-09-14 10:38:08 -07001312 return recv_rate_tracker_.TotalSampleCount();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001313}
1314
1315size_t Connection::sent_bytes_second() {
Tim Psiaki63046262015-09-14 10:38:08 -07001316 return send_rate_tracker_.ComputeRate();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001317}
1318
1319size_t Connection::sent_total_bytes() {
Tim Psiaki63046262015-09-14 10:38:08 -07001320 return send_rate_tracker_.TotalSampleCount();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001321}
1322
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001323size_t Connection::sent_discarded_packets() {
1324 return sent_packets_discarded_;
1325}
1326
1327size_t Connection::sent_total_packets() {
1328 return sent_packets_total_;
1329}
1330
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001331void Connection::MaybeAddPrflxCandidate(ConnectionRequest* request,
1332 StunMessage* response) {
1333 // RFC 5245
1334 // The agent checks the mapped address from the STUN response. If the
1335 // transport address does not match any of the local candidates that the
1336 // agent knows about, the mapped address represents a new candidate -- a
1337 // peer reflexive candidate.
1338 const StunAddressAttribute* addr =
1339 response->GetAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
1340 if (!addr) {
1341 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1342 << "No MAPPED-ADDRESS or XOR-MAPPED-ADDRESS found in the "
1343 << "stun response message";
1344 return;
1345 }
1346
1347 bool known_addr = false;
1348 for (size_t i = 0; i < port_->Candidates().size(); ++i) {
1349 if (port_->Candidates()[i].address() == addr->GetAddress()) {
1350 known_addr = true;
1351 break;
1352 }
1353 }
1354 if (known_addr) {
1355 return;
1356 }
1357
1358 // RFC 5245
1359 // Its priority is set equal to the value of the PRIORITY attribute
1360 // in the Binding request.
1361 const StunUInt32Attribute* priority_attr =
1362 request->msg()->GetUInt32(STUN_ATTR_PRIORITY);
1363 if (!priority_attr) {
1364 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1365 << "No STUN_ATTR_PRIORITY found in the "
1366 << "stun response message";
1367 return;
1368 }
1369 const uint32 priority = priority_attr->value();
1370 std::string id = rtc::CreateRandomString(8);
1371
1372 Candidate new_local_candidate;
1373 new_local_candidate.set_id(id);
1374 new_local_candidate.set_component(local_candidate().component());
1375 new_local_candidate.set_type(PRFLX_PORT_TYPE);
1376 new_local_candidate.set_protocol(local_candidate().protocol());
1377 new_local_candidate.set_address(addr->GetAddress());
1378 new_local_candidate.set_priority(priority);
1379 new_local_candidate.set_username(local_candidate().username());
1380 new_local_candidate.set_password(local_candidate().password());
1381 new_local_candidate.set_network_name(local_candidate().network_name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001382 new_local_candidate.set_network_type(local_candidate().network_type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001383 new_local_candidate.set_related_address(local_candidate().address());
1384 new_local_candidate.set_foundation(
1385 ComputeFoundation(PRFLX_PORT_TYPE, local_candidate().protocol(),
1386 local_candidate().address()));
1387
1388 // Change the local candidate of this Connection to the new prflx candidate.
1389 local_candidate_index_ = port_->AddPrflxCandidate(new_local_candidate);
1390
1391 // SignalStateChange to force a re-sort in P2PTransportChannel as this
1392 // Connection's local candidate has changed.
1393 SignalStateChange(this);
1394}
1395
1396ProxyConnection::ProxyConnection(Port* port, size_t index,
1397 const Candidate& candidate)
1398 : Connection(port, index, candidate), error_(0) {
1399}
1400
1401int ProxyConnection::Send(const void* data, size_t size,
1402 const rtc::PacketOptions& options) {
1403 if (write_state_ == STATE_WRITE_INIT || write_state_ == STATE_WRITE_TIMEOUT) {
1404 error_ = EWOULDBLOCK;
1405 return SOCKET_ERROR;
1406 }
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001407 sent_packets_total_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001408 int sent = port_->SendTo(data, size, remote_candidate_.address(),
1409 options, true);
1410 if (sent <= 0) {
1411 ASSERT(sent < 0);
1412 error_ = port_->GetError();
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001413 sent_packets_discarded_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001414 } else {
Tim Psiaki63046262015-09-14 10:38:08 -07001415 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001416 }
1417 return sent;
1418}
1419
1420} // namespace cricket