blob: a5c7770f553d78314df54ebe9c27d0e877762953 [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
569 // (if one exists) should now be readable.
570 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) {
633 ASSERT(pmsg->message_id == MSG_CHECKTIMEOUT);
634 CheckTimeout();
635}
636
637std::string Port::ToString() const {
638 std::stringstream ss;
639 ss << "Port[" << content_name_ << ":" << component_
640 << ":" << generation_ << ":" << type_
641 << ":" << network_->ToString() << "]";
642 return ss.str();
643}
644
645void Port::EnablePortPackets() {
646 enable_port_packets_ = true;
647}
648
649void Port::OnConnectionDestroyed(Connection* conn) {
650 AddressMap::iterator iter =
651 connections_.find(conn->remote_candidate().address());
652 ASSERT(iter != connections_.end());
653 connections_.erase(iter);
654
655 // On the controlled side, ports time out, but only after all connections
656 // fail. Note: If a new connection is added after this message is posted,
657 // but it fails and is removed before kPortTimeoutDelay, then this message
658 // will still cause the Port to be destroyed.
659 if (ice_role_ == ICEROLE_CONTROLLED)
660 thread_->PostDelayed(timeout_delay_, this, MSG_CHECKTIMEOUT);
661}
662
663void Port::Destroy() {
664 ASSERT(connections_.empty());
665 LOG_J(LS_INFO, this) << "Port deleted";
666 SignalDestroyed(this);
667 delete this;
668}
669
670void Port::CheckTimeout() {
671 ASSERT(ice_role_ == ICEROLE_CONTROLLED);
672 // If this port has no connections, then there's no reason to keep it around.
673 // When the connections time out (both read and write), they will delete
674 // themselves, so if we have any connections, they are either readable or
675 // writable (or still connecting).
676 if (connections_.empty())
677 Destroy();
678}
679
680const std::string Port::username_fragment() const {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700681 return ice_username_fragment_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000682}
683
684// A ConnectionRequest is a simple STUN ping used to determine writability.
685class ConnectionRequest : public StunRequest {
686 public:
687 explicit ConnectionRequest(Connection* connection)
688 : StunRequest(new IceMessage()),
689 connection_(connection) {
690 }
691
692 virtual ~ConnectionRequest() {
693 }
694
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700695 void Prepare(StunMessage* request) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000696 request->SetType(STUN_BINDING_REQUEST);
697 std::string username;
698 connection_->port()->CreateStunUsername(
699 connection_->remote_candidate().username(), &username);
700 request->AddAttribute(
701 new StunByteStringAttribute(STUN_ATTR_USERNAME, username));
702
703 // connection_ already holds this ping, so subtract one from count.
704 if (connection_->port()->send_retransmit_count_attribute()) {
705 request->AddAttribute(new StunUInt32Attribute(
706 STUN_ATTR_RETRANSMIT_COUNT,
707 static_cast<uint32>(
708 connection_->pings_since_last_response_.size() - 1)));
709 }
710
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700711 // Adding ICE_CONTROLLED or ICE_CONTROLLING attribute based on the role.
712 if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLING) {
713 request->AddAttribute(new StunUInt64Attribute(
714 STUN_ATTR_ICE_CONTROLLING, connection_->port()->IceTiebreaker()));
715 // Since we are trying aggressive nomination, sending USE-CANDIDATE
716 // attribute in every ping.
717 // If we are dealing with a ice-lite end point, nomination flag
718 // in Connection will be set to false by default. Once the connection
719 // becomes "best connection", nomination flag will be turned on.
720 if (connection_->use_candidate_attr()) {
721 request->AddAttribute(new StunByteStringAttribute(
722 STUN_ATTR_USE_CANDIDATE));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000723 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700724 } else if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLED) {
725 request->AddAttribute(new StunUInt64Attribute(
726 STUN_ATTR_ICE_CONTROLLED, connection_->port()->IceTiebreaker()));
727 } else {
728 ASSERT(false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000729 }
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700730
731 // Adding PRIORITY Attribute.
732 // Changing the type preference to Peer Reflexive and local preference
733 // and component id information is unchanged from the original priority.
734 // priority = (2^24)*(type preference) +
735 // (2^8)*(local preference) +
736 // (2^0)*(256 - component ID)
737 uint32 prflx_priority = ICE_TYPE_PREFERENCE_PRFLX << 24 |
738 (connection_->local_candidate().priority() & 0x00FFFFFF);
739 request->AddAttribute(
740 new StunUInt32Attribute(STUN_ATTR_PRIORITY, prflx_priority));
741
742 // Adding Message Integrity attribute.
743 request->AddMessageIntegrity(connection_->remote_candidate().password());
744 // Adding Fingerprint.
745 request->AddFingerprint();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000746 }
747
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700748 void OnResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000749 connection_->OnConnectionRequestResponse(this, response);
750 }
751
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700752 void OnErrorResponse(StunMessage* response) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000753 connection_->OnConnectionRequestErrorResponse(this, response);
754 }
755
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700756 void OnTimeout() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000757 connection_->OnConnectionRequestTimeout(this);
758 }
759
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700760 void OnSent() override {
761 connection_->OnConnectionRequestSent(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000762 // Each request is sent only once. After a single delay , the request will
763 // time out.
764 timeout_ = true;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700765 }
766
767 int resend_delay() override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000768 return CONNECTION_RESPONSE_TIMEOUT;
769 }
770
771 private:
772 Connection* connection_;
773};
774
775//
776// Connection
777//
778
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000779Connection::Connection(Port* port,
780 size_t index,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000781 const Candidate& remote_candidate)
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000782 : port_(port),
783 local_candidate_index_(index),
784 remote_candidate_(remote_candidate),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000785 write_state_(STATE_WRITE_INIT),
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700786 receiving_(false),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000787 connected_(true),
788 pruned_(false),
789 use_candidate_attr_(false),
honghaiz5a3acd82015-08-20 15:53:17 -0700790 nominated_(false),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000791 remote_ice_mode_(ICEMODE_FULL),
792 requests_(port->thread()),
793 rtt_(DEFAULT_RTT),
794 last_ping_sent_(0),
795 last_ping_received_(0),
796 last_data_received_(0),
797 last_ping_response_received_(0),
Tim Psiaki63046262015-09-14 10:38:08 -0700798 recv_rate_tracker_(100u, 10u),
799 send_rate_tracker_(100u, 10u),
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000800 sent_packets_discarded_(0),
801 sent_packets_total_(0),
802 reported_(false),
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700803 state_(STATE_WAITING),
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700804 receiving_timeout_(WEAK_CONNECTION_RECEIVE_TIMEOUT),
805 time_created_ms_(rtc::Time()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000806 // All of our connections start in WAITING state.
807 // TODO(mallinath) - Start connections from STATE_FROZEN.
808 // Wire up to send stun packets
809 requests_.SignalSendPacket.connect(this, &Connection::OnSendStunPacket);
810 LOG_J(LS_INFO, this) << "Connection created";
811}
812
813Connection::~Connection() {
814}
815
816const Candidate& Connection::local_candidate() const {
817 ASSERT(local_candidate_index_ < port_->Candidates().size());
818 return port_->Candidates()[local_candidate_index_];
819}
820
821uint64 Connection::priority() const {
822 uint64 priority = 0;
823 // RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs
824 // Let G be the priority for the candidate provided by the controlling
825 // agent. Let D be the priority for the candidate provided by the
826 // controlled agent.
827 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
828 IceRole role = port_->GetIceRole();
829 if (role != ICEROLE_UNKNOWN) {
830 uint32 g = 0;
831 uint32 d = 0;
832 if (role == ICEROLE_CONTROLLING) {
833 g = local_candidate().priority();
834 d = remote_candidate_.priority();
835 } else {
836 g = remote_candidate_.priority();
837 d = local_candidate().priority();
838 }
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000839 priority = std::min(g, d);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000840 priority = priority << 32;
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000841 priority += 2 * std::max(g, d) + (g > d ? 1 : 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000842 }
843 return priority;
844}
845
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000846void Connection::set_write_state(WriteState value) {
847 WriteState old_value = write_state_;
848 write_state_ = value;
849 if (value != old_value) {
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +0000850 LOG_J(LS_VERBOSE, this) << "set_write_state from: " << old_value << " to "
851 << value;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000852 SignalStateChange(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000853 }
854}
855
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700856void Connection::set_receiving(bool value) {
857 if (value != receiving_) {
858 LOG_J(LS_VERBOSE, this) << "set_receiving to " << value;
859 receiving_ = value;
860 SignalStateChange(this);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700861 }
862}
863
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000864void Connection::set_state(State state) {
865 State old_state = state_;
866 state_ = state;
867 if (state != old_state) {
868 LOG_J(LS_VERBOSE, this) << "set_state";
869 }
870}
871
872void Connection::set_connected(bool value) {
873 bool old_value = connected_;
874 connected_ = value;
875 if (value != old_value) {
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700876 LOG_J(LS_VERBOSE, this) << "set_connected from: " << old_value << " to "
877 << value;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000878 }
879}
880
881void Connection::set_use_candidate_attr(bool enable) {
882 use_candidate_attr_ = enable;
883}
884
885void Connection::OnSendStunPacket(const void* data, size_t size,
886 StunRequest* req) {
887 rtc::PacketOptions options(port_->DefaultDscpValue());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700888 auto err = port_->SendTo(
889 data, size, remote_candidate_.address(), options, false);
890 if (err < 0) {
891 LOG_J(LS_WARNING, this) << "Failed to send STUN ping "
892 << " err=" << err
893 << " id=" << rtc::hex_encode(req->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000894 }
895}
896
897void Connection::OnReadPacket(
898 const char* data, size_t size, const rtc::PacketTime& packet_time) {
899 rtc::scoped_ptr<IceMessage> msg;
900 std::string remote_ufrag;
901 const rtc::SocketAddress& addr(remote_candidate_.address());
902 if (!port_->GetStunMessage(data, size, addr, msg.accept(), &remote_ufrag)) {
903 // The packet did not parse as a valid STUN message
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700904 // This is a data packet, pass it along.
905 set_receiving(true);
906 last_data_received_ = rtc::Time();
907 recv_rate_tracker_.AddSamples(size);
908 SignalReadPacket(this, data, size, packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000909
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700910 // If timed out sending writability checks, start up again
911 if (!pruned_ && (write_state_ == STATE_WRITE_TIMEOUT)) {
912 LOG(LS_WARNING) << "Received a data packet on a timed-out Connection. "
913 << "Resetting state to STATE_WRITE_INIT.";
914 set_write_state(STATE_WRITE_INIT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000915 }
916 } else if (!msg) {
917 // The packet was STUN, but failed a check and was handled internally.
918 } else {
919 // The packet is STUN and passed the Port checks.
920 // Perform our own checks to ensure this packet is valid.
921 // If this is a STUN request, then update the readable bit and respond.
922 // If this is a STUN response, then update the writable bit.
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700923 // Log at LS_INFO if we receive a ping on an unwritable connection.
924 rtc::LoggingSeverity sev = (!writable() ? rtc::LS_INFO : rtc::LS_VERBOSE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000925 switch (msg->type()) {
926 case STUN_BINDING_REQUEST:
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700927 LOG_JV(sev, this) << "Received STUN ping"
928 << ", id=" << rtc::hex_encode(msg->transaction_id());
929
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000930 if (remote_ufrag == remote_candidate_.username()) {
931 // Check for role conflicts.
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700932 if (!port_->MaybeIceRoleConflict(addr, msg.get(), remote_ufrag)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000933 // Received conflicting role from the peer.
934 LOG(LS_INFO) << "Received conflicting role from the peer.";
935 return;
936 }
937
938 // Incoming, validated stun request from remote peer.
939 // This call will also set the connection readable.
940 port_->SendBindingResponse(msg.get(), addr);
941
942 // If timed out sending writability checks, start up again
943 if (!pruned_ && (write_state_ == STATE_WRITE_TIMEOUT))
944 set_write_state(STATE_WRITE_INIT);
945
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700946 if (port_->GetIceRole() == ICEROLE_CONTROLLED) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000947 const StunByteStringAttribute* use_candidate_attr =
948 msg->GetByteString(STUN_ATTR_USE_CANDIDATE);
honghaiz5a3acd82015-08-20 15:53:17 -0700949 if (use_candidate_attr) {
950 set_nominated(true);
951 SignalNominated(this);
952 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000953 }
954 } else {
955 // The packet had the right local username, but the remote username
956 // was not the right one for the remote address.
957 LOG_J(LS_ERROR, this)
958 << "Received STUN request with bad remote username "
959 << remote_ufrag;
960 port_->SendBindingErrorResponse(msg.get(), addr,
961 STUN_ERROR_UNAUTHORIZED,
962 STUN_ERROR_REASON_UNAUTHORIZED);
963
964 }
965 break;
966
967 // Response from remote peer. Does it match request sent?
968 // This doesn't just check, it makes callbacks if transaction
969 // id's match.
970 case STUN_BINDING_RESPONSE:
971 case STUN_BINDING_ERROR_RESPONSE:
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700972 if (msg->ValidateMessageIntegrity(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000973 data, size, remote_candidate().password())) {
974 requests_.CheckResponse(msg.get());
975 }
976 // Otherwise silently discard the response message.
977 break;
978
979 // Remote end point sent an STUN indication instead of regular
980 // binding request. In this case |last_ping_received_| will be updated.
981 // Otherwise we can mark connection to read timeout. No response will be
982 // sent in this scenario.
983 case STUN_BINDING_INDICATION:
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700984 ReceivedPing();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000985 break;
986
987 default:
988 ASSERT(false);
989 break;
990 }
991 }
992}
993
994void Connection::OnReadyToSend() {
995 if (write_state_ == STATE_WRITABLE) {
996 SignalReadyToSend(this);
997 }
998}
999
1000void Connection::Prune() {
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001001 if (!pruned_ || active()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001002 LOG_J(LS_VERBOSE, this) << "Connection pruned";
1003 pruned_ = true;
1004 requests_.Clear();
1005 set_write_state(STATE_WRITE_TIMEOUT);
1006 }
1007}
1008
1009void Connection::Destroy() {
1010 LOG_J(LS_VERBOSE, this) << "Connection destroyed";
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001011 port_->thread()->Post(this, MSG_DELETE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001012}
1013
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001014void Connection::PrintPingsSinceLastResponse(std::string* s, size_t max) {
1015 std::ostringstream oss;
1016 oss << std::boolalpha;
1017 if (pings_since_last_response_.size() > max) {
1018 for (size_t i = 0; i < max; i++) {
1019 const SentPing& ping = pings_since_last_response_[i];
1020 oss << rtc::hex_encode(ping.id) << " ";
1021 }
1022 oss << "... " << (pings_since_last_response_.size() - max) << " more";
1023 } else {
1024 for (const SentPing& ping : pings_since_last_response_) {
1025 oss << rtc::hex_encode(ping.id) << " ";
1026 }
1027 }
1028 *s = oss.str();
1029}
1030
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001031void Connection::UpdateState(uint32 now) {
1032 uint32 rtt = ConservativeRTTEstimate(rtt_);
1033
Peter Thatcherb2d26232015-05-15 11:25:14 -07001034 if (LOG_CHECK_LEVEL(LS_VERBOSE)) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001035 std::string pings;
1036 PrintPingsSinceLastResponse(&pings, 5);
1037 LOG_J(LS_VERBOSE, this) << "UpdateState()"
1038 << ", ms since last received response="
1039 << now - last_ping_response_received_
1040 << ", ms since last received data="
1041 << now - last_data_received_
1042 << ", rtt=" << rtt
1043 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001044 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001045
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001046 // Check the writable state. (The order of these checks is important.)
1047 //
1048 // Before becoming unwritable, we allow for a fixed number of pings to fail
1049 // (i.e., receive no response). We also have to give the response time to
1050 // get back, so we include a conservative estimate of this.
1051 //
1052 // Before timing out writability, we give a fixed amount of time. This is to
1053 // allow for changes in network conditions.
1054
1055 if ((write_state_ == STATE_WRITABLE) &&
1056 TooManyFailures(pings_since_last_response_,
1057 CONNECTION_WRITE_CONNECT_FAILURES,
1058 rtt,
1059 now) &&
1060 TooLongWithoutResponse(pings_since_last_response_,
1061 CONNECTION_WRITE_CONNECT_TIMEOUT,
1062 now)) {
1063 uint32 max_pings = CONNECTION_WRITE_CONNECT_FAILURES;
1064 LOG_J(LS_INFO, this) << "Unwritable after " << max_pings
1065 << " ping failures and "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001066 << now - pings_since_last_response_[0].sent_time
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001067 << " ms without a response,"
1068 << " ms since last received ping="
1069 << now - last_ping_received_
1070 << " ms since last received data="
1071 << now - last_data_received_
1072 << " rtt=" << rtt;
1073 set_write_state(STATE_WRITE_UNRELIABLE);
1074 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001075 if ((write_state_ == STATE_WRITE_UNRELIABLE ||
1076 write_state_ == STATE_WRITE_INIT) &&
1077 TooLongWithoutResponse(pings_since_last_response_,
1078 CONNECTION_WRITE_TIMEOUT,
1079 now)) {
1080 LOG_J(LS_INFO, this) << "Timed out after "
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001081 << now - pings_since_last_response_[0].sent_time
1082 << " ms without a response"
1083 << ", rtt=" << rtt;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001084 set_write_state(STATE_WRITE_TIMEOUT);
1085 }
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001086
1087 // Check the receiving state.
1088 uint32 last_recv_time = last_received();
1089 bool receiving = now <= last_recv_time + receiving_timeout_;
1090 set_receiving(receiving);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001091 if (dead(now)) {
1092 Destroy();
1093 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001094}
1095
1096void Connection::Ping(uint32 now) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001097 last_ping_sent_ = now;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001098 ConnectionRequest *req = new ConnectionRequest(this);
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001099 pings_since_last_response_.push_back(SentPing(req->id(), now));
1100 LOG_J(LS_VERBOSE, this) << "Sending STUN ping "
1101 << ", id=" << rtc::hex_encode(req->id());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001102 requests_.Send(req);
1103 state_ = STATE_INPROGRESS;
1104}
1105
1106void Connection::ReceivedPing() {
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001107 set_receiving(true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001108 last_ping_received_ = rtc::Time();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001109}
1110
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001111void Connection::ReceivedPingResponse() {
1112 // We've already validated that this is a STUN binding response with
1113 // the correct local and remote username for this connection.
1114 // So if we're not already, become writable. We may be bringing a pruned
1115 // connection back to life, but if we don't really want it, we can always
1116 // prune it again.
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001117 set_receiving(true);
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001118 set_write_state(STATE_WRITABLE);
1119 set_state(STATE_SUCCEEDED);
1120 pings_since_last_response_.clear();
1121 last_ping_response_received_ = rtc::Time();
1122}
1123
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001124bool Connection::dead(uint32 now) const {
1125 if (now < (time_created_ms_ + MIN_CONNECTION_LIFETIME)) {
1126 // A connection that hasn't passed its minimum lifetime is still alive.
1127 // We do this to prevent connections from being pruned too quickly
1128 // during a network change event when two networks would be up
1129 // simultaneously but only for a brief period.
1130 return false;
1131 }
1132
1133 if (receiving_) {
1134 // A connection that is receiving is alive.
1135 return false;
1136 }
1137
1138 // A connection is alive until it is inactive.
1139 return !active();
1140
1141 // TODO(honghaiz): Move from using the write state to using the receiving
1142 // state with something like the following:
1143 // return (now > (last_received() + DEAD_CONNECTION_RECEIVE_TIMEOUT));
1144}
1145
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +00001146std::string Connection::ToDebugId() const {
1147 std::stringstream ss;
1148 ss << std::hex << this;
1149 return ss.str();
1150}
1151
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001152std::string Connection::ToString() const {
1153 const char CONNECT_STATE_ABBREV[2] = {
1154 '-', // not connected (false)
1155 'C', // connected (true)
1156 };
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001157 const char RECEIVE_STATE_ABBREV[2] = {
1158 '-', // not receiving (false)
1159 'R', // receiving (true)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001160 };
1161 const char WRITE_STATE_ABBREV[4] = {
1162 'W', // STATE_WRITABLE
1163 'w', // STATE_WRITE_UNRELIABLE
1164 '-', // STATE_WRITE_INIT
1165 'x', // STATE_WRITE_TIMEOUT
1166 };
1167 const std::string ICESTATE[4] = {
1168 "W", // STATE_WAITING
1169 "I", // STATE_INPROGRESS
1170 "S", // STATE_SUCCEEDED
1171 "F" // STATE_FAILED
1172 };
1173 const Candidate& local = local_candidate();
1174 const Candidate& remote = remote_candidate();
1175 std::stringstream ss;
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +00001176 ss << "Conn[" << ToDebugId()
1177 << ":" << port_->content_name()
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001178 << ":" << local.id() << ":" << local.component()
1179 << ":" << local.generation()
1180 << ":" << local.type() << ":" << local.protocol()
1181 << ":" << local.address().ToSensitiveString()
1182 << "->" << remote.id() << ":" << remote.component()
1183 << ":" << remote.priority()
1184 << ":" << remote.type() << ":"
1185 << remote.protocol() << ":" << remote.address().ToSensitiveString() << "|"
1186 << CONNECT_STATE_ABBREV[connected()]
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001187 << RECEIVE_STATE_ABBREV[receiving()]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001188 << WRITE_STATE_ABBREV[write_state()]
1189 << ICESTATE[state()] << "|"
1190 << priority() << "|";
1191 if (rtt_ < DEFAULT_RTT) {
1192 ss << rtt_ << "]";
1193 } else {
1194 ss << "-]";
1195 }
1196 return ss.str();
1197}
1198
1199std::string Connection::ToSensitiveString() const {
1200 return ToString();
1201}
1202
1203void Connection::OnConnectionRequestResponse(ConnectionRequest* request,
1204 StunMessage* response) {
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001205 // Log at LS_INFO if we receive a ping response on an unwritable
1206 // connection.
1207 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1208
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001209 uint32 rtt = request->Elapsed();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001210
Peter Thatcher1fe120a2015-06-10 11:33:17 -07001211 ReceivedPingResponse();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001212
Peter Thatcherb2d26232015-05-15 11:25:14 -07001213 if (LOG_CHECK_LEVEL_V(sev)) {
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001214 bool use_candidate = (
1215 response->GetByteString(STUN_ATTR_USE_CANDIDATE) != nullptr);
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001216 std::string pings;
1217 PrintPingsSinceLastResponse(&pings, 5);
1218 LOG_JV(sev, this) << "Received STUN ping response"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001219 << ", id=" << rtc::hex_encode(request->id())
1220 << ", code=0" // Makes logging easier to parse.
1221 << ", rtt=" << rtt
1222 << ", use_candidate=" << use_candidate
1223 << ", pings_since_last_response=" << pings;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001224 }
1225
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001226 rtt_ = (RTT_RATIO * rtt_ + rtt) / (RTT_RATIO + 1);
1227
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001228 MaybeAddPrflxCandidate(request, response);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001229}
1230
1231void Connection::OnConnectionRequestErrorResponse(ConnectionRequest* request,
1232 StunMessage* response) {
1233 const StunErrorCodeAttribute* error_attr = response->GetErrorCode();
1234 int error_code = STUN_ERROR_GLOBAL_FAILURE;
1235 if (error_attr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001236 error_code = error_attr->code();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001237 }
1238
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001239 LOG_J(LS_INFO, this) << "Received STUN error response"
1240 << " id=" << rtc::hex_encode(request->id())
1241 << " code=" << error_code
1242 << " rtt=" << request->Elapsed();
1243
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001244 if (error_code == STUN_ERROR_UNKNOWN_ATTRIBUTE ||
1245 error_code == STUN_ERROR_SERVER_ERROR ||
1246 error_code == STUN_ERROR_UNAUTHORIZED) {
1247 // Recoverable error, retry
1248 } else if (error_code == STUN_ERROR_STALE_CREDENTIALS) {
1249 // Race failure, retry
1250 } else if (error_code == STUN_ERROR_ROLE_CONFLICT) {
1251 HandleRoleConflictFromPeer();
1252 } else {
1253 // This is not a valid connection.
1254 LOG_J(LS_ERROR, this) << "Received STUN error response, code="
1255 << error_code << "; killing connection";
1256 set_state(STATE_FAILED);
Honghai Zhang2b342bf2015-09-30 09:51:58 -07001257 Destroy();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001258 }
1259}
1260
1261void Connection::OnConnectionRequestTimeout(ConnectionRequest* request) {
1262 // Log at LS_INFO if we miss a ping on a writable connection.
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001263 rtc::LoggingSeverity sev = writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1264 LOG_JV(sev, this) << "Timing-out STUN ping "
1265 << rtc::hex_encode(request->id())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001266 << " after " << request->Elapsed() << " ms";
1267}
1268
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001269void Connection::OnConnectionRequestSent(ConnectionRequest* request) {
1270 // Log at LS_INFO if we send a ping on an unwritable connection.
1271 rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001272 bool use_candidate = use_candidate_attr();
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001273 LOG_JV(sev, this) << "Sent STUN ping"
Peter Thatcher42af6ca2015-05-15 12:23:27 -07001274 << ", id=" << rtc::hex_encode(request->id())
1275 << ", use_candidate=" << use_candidate;
Peter Thatcher1cf6f812015-05-15 10:40:45 -07001276}
1277
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001278void Connection::HandleRoleConflictFromPeer() {
1279 port_->SignalRoleConflict(port_);
1280}
1281
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +00001282void Connection::MaybeSetRemoteIceCredentials(const std::string& ice_ufrag,
1283 const std::string& ice_pwd) {
1284 if (remote_candidate_.username() == ice_ufrag &&
1285 remote_candidate_.password().empty()) {
1286 remote_candidate_.set_password(ice_pwd);
1287 }
1288}
1289
1290void Connection::MaybeUpdatePeerReflexiveCandidate(
1291 const Candidate& new_candidate) {
1292 if (remote_candidate_.type() == PRFLX_PORT_TYPE &&
1293 new_candidate.type() != PRFLX_PORT_TYPE &&
1294 remote_candidate_.protocol() == new_candidate.protocol() &&
1295 remote_candidate_.address() == new_candidate.address() &&
1296 remote_candidate_.username() == new_candidate.username() &&
1297 remote_candidate_.password() == new_candidate.password() &&
1298 remote_candidate_.generation() == new_candidate.generation()) {
1299 remote_candidate_ = new_candidate;
1300 }
1301}
1302
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001303void Connection::OnMessage(rtc::Message *pmsg) {
1304 ASSERT(pmsg->message_id == MSG_DELETE);
henrike@webrtc.org43e033e2014-11-10 19:40:29 +00001305 LOG_J(LS_INFO, this) << "Connection deleted due to read or write timeout";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001306 SignalDestroyed(this);
1307 delete this;
1308}
1309
Peter Thatcher54360512015-07-08 11:08:35 -07001310uint32 Connection::last_received() {
1311 return std::max(last_data_received_,
1312 std::max(last_ping_received_, last_ping_response_received_));
1313}
1314
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001315size_t Connection::recv_bytes_second() {
Tim Psiaki63046262015-09-14 10:38:08 -07001316 return recv_rate_tracker_.ComputeRate();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001317}
1318
1319size_t Connection::recv_total_bytes() {
Tim Psiaki63046262015-09-14 10:38:08 -07001320 return recv_rate_tracker_.TotalSampleCount();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001321}
1322
1323size_t Connection::sent_bytes_second() {
Tim Psiaki63046262015-09-14 10:38:08 -07001324 return send_rate_tracker_.ComputeRate();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001325}
1326
1327size_t Connection::sent_total_bytes() {
Tim Psiaki63046262015-09-14 10:38:08 -07001328 return send_rate_tracker_.TotalSampleCount();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001329}
1330
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001331size_t Connection::sent_discarded_packets() {
1332 return sent_packets_discarded_;
1333}
1334
1335size_t Connection::sent_total_packets() {
1336 return sent_packets_total_;
1337}
1338
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001339void Connection::MaybeAddPrflxCandidate(ConnectionRequest* request,
1340 StunMessage* response) {
1341 // RFC 5245
1342 // The agent checks the mapped address from the STUN response. If the
1343 // transport address does not match any of the local candidates that the
1344 // agent knows about, the mapped address represents a new candidate -- a
1345 // peer reflexive candidate.
1346 const StunAddressAttribute* addr =
1347 response->GetAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
1348 if (!addr) {
1349 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1350 << "No MAPPED-ADDRESS or XOR-MAPPED-ADDRESS found in the "
1351 << "stun response message";
1352 return;
1353 }
1354
1355 bool known_addr = false;
1356 for (size_t i = 0; i < port_->Candidates().size(); ++i) {
1357 if (port_->Candidates()[i].address() == addr->GetAddress()) {
1358 known_addr = true;
1359 break;
1360 }
1361 }
1362 if (known_addr) {
1363 return;
1364 }
1365
1366 // RFC 5245
1367 // Its priority is set equal to the value of the PRIORITY attribute
1368 // in the Binding request.
1369 const StunUInt32Attribute* priority_attr =
1370 request->msg()->GetUInt32(STUN_ATTR_PRIORITY);
1371 if (!priority_attr) {
1372 LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1373 << "No STUN_ATTR_PRIORITY found in the "
1374 << "stun response message";
1375 return;
1376 }
1377 const uint32 priority = priority_attr->value();
1378 std::string id = rtc::CreateRandomString(8);
1379
1380 Candidate new_local_candidate;
1381 new_local_candidate.set_id(id);
1382 new_local_candidate.set_component(local_candidate().component());
1383 new_local_candidate.set_type(PRFLX_PORT_TYPE);
1384 new_local_candidate.set_protocol(local_candidate().protocol());
1385 new_local_candidate.set_address(addr->GetAddress());
1386 new_local_candidate.set_priority(priority);
1387 new_local_candidate.set_username(local_candidate().username());
1388 new_local_candidate.set_password(local_candidate().password());
1389 new_local_candidate.set_network_name(local_candidate().network_name());
guoweis@webrtc.org950c5182014-12-16 23:01:31 +00001390 new_local_candidate.set_network_type(local_candidate().network_type());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001391 new_local_candidate.set_related_address(local_candidate().address());
1392 new_local_candidate.set_foundation(
1393 ComputeFoundation(PRFLX_PORT_TYPE, local_candidate().protocol(),
1394 local_candidate().address()));
1395
1396 // Change the local candidate of this Connection to the new prflx candidate.
1397 local_candidate_index_ = port_->AddPrflxCandidate(new_local_candidate);
1398
1399 // SignalStateChange to force a re-sort in P2PTransportChannel as this
1400 // Connection's local candidate has changed.
1401 SignalStateChange(this);
1402}
1403
1404ProxyConnection::ProxyConnection(Port* port, size_t index,
1405 const Candidate& candidate)
1406 : Connection(port, index, candidate), error_(0) {
1407}
1408
1409int ProxyConnection::Send(const void* data, size_t size,
1410 const rtc::PacketOptions& options) {
1411 if (write_state_ == STATE_WRITE_INIT || write_state_ == STATE_WRITE_TIMEOUT) {
1412 error_ = EWOULDBLOCK;
1413 return SOCKET_ERROR;
1414 }
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001415 sent_packets_total_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001416 int sent = port_->SendTo(data, size, remote_candidate_.address(),
1417 options, true);
1418 if (sent <= 0) {
1419 ASSERT(sent < 0);
1420 error_ = port_->GetError();
guoweis@webrtc.org930e0042014-11-17 19:42:14 +00001421 sent_packets_discarded_++;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001422 } else {
Tim Psiaki63046262015-09-14 10:38:08 -07001423 send_rate_tracker_.AddSamples(sent);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001424 }
1425 return sent;
1426}
1427
1428} // namespace cricket