1 /*
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/checks.h"
20 #include "webrtc/base/crc32.h"
21 #include "webrtc/base/helpers.h"
22 #include "webrtc/base/logging.h"
23 #include "webrtc/base/messagedigest.h"
24 #include "webrtc/base/network.h"
25 #include "webrtc/base/stringencode.h"
26 #include "webrtc/base/stringutils.h"
27 
28 namespace {
29 
30 // Determines whether we have seen at least the given maximum number of
31 // pings fail to have a response.
TooManyFailures(const std::vector<cricket::Connection::SentPing> & pings_since_last_response,uint32_t maximum_failures,int rtt_estimate,int64_t now)32 inline bool TooManyFailures(
33     const std::vector<cricket::Connection::SentPing>& pings_since_last_response,
34     uint32_t maximum_failures,
35     int rtt_estimate,
36     int64_t now) {
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.
43   int64_t expected_response_time =
44       pings_since_last_response[maximum_failures - 1].sent_time + rtt_estimate;
45   return now > expected_response_time;
46 }
47 
48 // Determines whether we have gone too long without seeing any response.
TooLongWithoutResponse(const std::vector<cricket::Connection::SentPing> & pings_since_last_response,int64_t maximum_time,int64_t now)49 inline bool TooLongWithoutResponse(
50     const std::vector<cricket::Connection::SentPing>& pings_since_last_response,
51     int64_t maximum_time,
52     int64_t now) {
53   if (pings_since_last_response.size() == 0)
54     return false;
55 
56   auto first = pings_since_last_response[0];
57   return now > (first.sent_time + maximum_time);
58 }
59 
60 // We will restrict RTT estimates (when used for determining state) to be
61 // within a reasonable range.
62 const int MINIMUM_RTT = 100;   // 0.1 seconds
63 const int MAXIMUM_RTT = 3000;  // 3 seconds
64 
65 // When we don't have any RTT data, we have to pick something reasonable.  We
66 // use a large value just in case the connection is really slow.
67 const int DEFAULT_RTT = MAXIMUM_RTT;
68 
69 // Computes our estimate of the RTT given the current estimate.
ConservativeRTTEstimate(int rtt)70 inline int ConservativeRTTEstimate(int rtt) {
71   return std::max(MINIMUM_RTT, std::min(MAXIMUM_RTT, 2 * rtt));
72 }
73 
74 // Weighting of the old rtt value to new data.
75 const int RTT_RATIO = 3;  // 3 : 1
76 
77 // The delay before we begin checking if this port is useless.
78 const int kPortTimeoutDelay = 30 * 1000;  // 30 seconds
79 }  // namespace
80 
81 namespace cricket {
82 
83 // TODO(ronghuawu): Use "host", "srflx", "prflx" and "relay". But this requires
84 // the signaling part be updated correspondingly as well.
85 const char LOCAL_PORT_TYPE[] = "local";
86 const char STUN_PORT_TYPE[] = "stun";
87 const char PRFLX_PORT_TYPE[] = "prflx";
88 const char RELAY_PORT_TYPE[] = "relay";
89 
90 const char UDP_PROTOCOL_NAME[] = "udp";
91 const char TCP_PROTOCOL_NAME[] = "tcp";
92 const char SSLTCP_PROTOCOL_NAME[] = "ssltcp";
93 const char TLS_PROTOCOL_NAME[] = "tls";
94 
95 static const char* const PROTO_NAMES[] = {UDP_PROTOCOL_NAME, TCP_PROTOCOL_NAME,
96                                           SSLTCP_PROTOCOL_NAME,
97                                           TLS_PROTOCOL_NAME};
98 
ProtoToString(ProtocolType proto)99 const char* ProtoToString(ProtocolType proto) {
100   return PROTO_NAMES[proto];
101 }
102 
StringToProto(const char * value,ProtocolType * proto)103 bool 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.
114 const int DISCARD_PORT = 9;
115 const char TCPTYPE_ACTIVE_STR[] = "active";
116 const char TCPTYPE_PASSIVE_STR[] = "passive";
117 const 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.
ComputeFoundation(const std::string & type,const std::string & protocol,const std::string & relay_protocol,const rtc::SocketAddress & base_address)125 static std::string ComputeFoundation(const std::string& type,
126                                      const std::string& protocol,
127                                      const std::string& relay_protocol,
128                                      const rtc::SocketAddress& base_address) {
129   std::ostringstream ost;
130   ost << type << base_address.ipaddr().ToString() << protocol << relay_protocol;
131   return rtc::ToString<uint32_t>(rtc::ComputeCrc32(ost.str()));
132 }
133 
Port(rtc::Thread * thread,const std::string & type,rtc::PacketSocketFactory * factory,rtc::Network * network,const rtc::IPAddress & ip,const std::string & username_fragment,const std::string & password)134 Port::Port(rtc::Thread* thread,
135            const std::string& type,
136            rtc::PacketSocketFactory* factory,
137            rtc::Network* network,
138            const rtc::IPAddress& ip,
139            const std::string& username_fragment,
140            const std::string& password)
141     : thread_(thread),
142       factory_(factory),
143       type_(type),
144       send_retransmit_count_attribute_(false),
145       network_(network),
146       ip_(ip),
147       min_port_(0),
148       max_port_(0),
149       component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
150       generation_(0),
151       ice_username_fragment_(username_fragment),
152       password_(password),
153       timeout_delay_(kPortTimeoutDelay),
154       enable_port_packets_(false),
155       ice_role_(ICEROLE_UNKNOWN),
156       tiebreaker_(0),
157       shared_socket_(true) {
158   Construct();
159 }
160 
Port(rtc::Thread * thread,const std::string & type,rtc::PacketSocketFactory * factory,rtc::Network * network,const rtc::IPAddress & ip,uint16_t min_port,uint16_t max_port,const std::string & username_fragment,const std::string & password)161 Port::Port(rtc::Thread* thread,
162            const std::string& type,
163            rtc::PacketSocketFactory* factory,
164            rtc::Network* network,
165            const rtc::IPAddress& ip,
166            uint16_t min_port,
167            uint16_t max_port,
168            const std::string& username_fragment,
169            const std::string& password)
170     : thread_(thread),
171       factory_(factory),
172       type_(type),
173       send_retransmit_count_attribute_(false),
174       network_(network),
175       ip_(ip),
176       min_port_(min_port),
177       max_port_(max_port),
178       component_(ICE_CANDIDATE_COMPONENT_DEFAULT),
179       generation_(0),
180       ice_username_fragment_(username_fragment),
181       password_(password),
182       timeout_delay_(kPortTimeoutDelay),
183       enable_port_packets_(false),
184       ice_role_(ICEROLE_UNKNOWN),
185       tiebreaker_(0),
186       shared_socket_(false) {
187   RTC_DCHECK(factory_ != NULL);
188   Construct();
189 }
190 
Construct()191 void Port::Construct() {
192   // 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.
195   if (ice_username_fragment_.empty()) {
196     RTC_DCHECK(password_.empty());
197     ice_username_fragment_ = rtc::CreateRandomString(ICE_UFRAG_LENGTH);
198     password_ = rtc::CreateRandomString(ICE_PWD_LENGTH);
199   }
200   network_->SignalTypeChanged.connect(this, &Port::OnNetworkTypeChanged);
201   network_cost_ = network_->GetCost();
202 
203   thread_->PostDelayed(RTC_FROM_HERE, timeout_delay_, this,
204                        MSG_DESTROY_IF_DEAD);
205   LOG_J(LS_INFO, this) << "Port created with network cost " << network_cost_;
206 }
207 
~Port()208 Port::~Port() {
209   // Delete all of the remaining connections.  We copy the list up front
210   // because each deletion will cause it to be modified.
211 
212   std::vector<Connection*> list;
213 
214   AddressMap::iterator iter = connections_.begin();
215   while (iter != connections_.end()) {
216     list.push_back(iter->second);
217     ++iter;
218   }
219 
220   for (uint32_t i = 0; i < list.size(); i++)
221     delete list[i];
222 }
223 
SetIceParameters(int component,const std::string & username_fragment,const std::string & password)224 void Port::SetIceParameters(int component,
225                             const std::string& username_fragment,
226                             const std::string& password) {
227   component_ = component;
228   ice_username_fragment_ = username_fragment;
229   password_ = password;
230   for (Candidate& c : candidates_) {
231     c.set_component(component);
232     c.set_username(username_fragment);
233     c.set_password(password);
234   }
235 }
236 
GetConnection(const rtc::SocketAddress & remote_addr)237 Connection* Port::GetConnection(const rtc::SocketAddress& remote_addr) {
238   AddressMap::const_iterator iter = connections_.find(remote_addr);
239   if (iter != connections_.end())
240     return iter->second;
241   else
242     return NULL;
243 }
244 
AddAddress(const rtc::SocketAddress & address,const rtc::SocketAddress & base_address,const rtc::SocketAddress & related_address,const std::string & protocol,const std::string & relay_protocol,const std::string & tcptype,const std::string & type,uint32_t type_preference,uint32_t relay_preference,bool final)245 void Port::AddAddress(const rtc::SocketAddress& address,
246                       const rtc::SocketAddress& base_address,
247                       const rtc::SocketAddress& related_address,
248                       const std::string& protocol,
249                       const std::string& relay_protocol,
250                       const std::string& tcptype,
251                       const std::string& type,
252                       uint32_t type_preference,
253                       uint32_t relay_preference,
254                       bool final) {
255   if (protocol == TCP_PROTOCOL_NAME && type == LOCAL_PORT_TYPE) {
256     RTC_DCHECK(!tcptype.empty());
257   }
258 
259   std::string foundation =
260       ComputeFoundation(type, protocol, relay_protocol, base_address);
261   Candidate c(component_, protocol, address, 0U, username_fragment(), password_,
262               type, generation_, foundation, network_->id(), network_cost_);
263   c.set_priority(
264       c.GetPriority(type_preference, network_->preference(), relay_preference));
265   c.set_relay_protocol(relay_protocol);
266   c.set_tcptype(tcptype);
267   c.set_network_name(network_->name());
268   c.set_network_type(network_->type());
269   c.set_related_address(related_address);
270   candidates_.push_back(c);
271   SignalCandidateReady(this, c);
272 
273   if (final) {
274     SignalPortComplete(this);
275   }
276 }
277 
AddOrReplaceConnection(Connection * conn)278 void Port::AddOrReplaceConnection(Connection* conn) {
279   auto ret = connections_.insert(
280       std::make_pair(conn->remote_candidate().address(), conn));
281   // If there is a different connection on the same remote address, replace
282   // it with the new one and destroy the old one.
283   if (ret.second == false && ret.first->second != conn) {
284     LOG_J(LS_WARNING, this)
285         << "A new connection was created on an existing remote address. "
286         << "New remote candidate: " << conn->remote_candidate().ToString();
287     ret.first->second->SignalDestroyed.disconnect(this);
288     ret.first->second->Destroy();
289     ret.first->second = conn;
290   }
291   conn->SignalDestroyed.connect(this, &Port::OnConnectionDestroyed);
292   SignalConnectionCreated(this, conn);
293 }
294 
OnReadPacket(const char * data,size_t size,const rtc::SocketAddress & addr,ProtocolType proto)295 void Port::OnReadPacket(
296     const char* data, size_t size, const rtc::SocketAddress& addr,
297     ProtocolType proto) {
298   // If the user has enabled port packets, just hand this over.
299   if (enable_port_packets_) {
300     SignalReadPacket(this, data, size, addr);
301     return;
302   }
303 
304   // If this is an authenticated STUN request, then signal unknown address and
305   // send back a proper binding response.
306   std::unique_ptr<IceMessage> msg;
307   std::string remote_username;
308   if (!GetStunMessage(data, size, addr, &msg, &remote_username)) {
309     LOG_J(LS_ERROR, this) << "Received non-STUN packet from unknown address ("
310                           << addr.ToSensitiveString() << ")";
311   } else if (!msg) {
312     // STUN message handled already
313   } else if (msg->type() == STUN_BINDING_REQUEST) {
314     LOG(LS_INFO) << "Received STUN ping "
315                  << " id=" << rtc::hex_encode(msg->transaction_id())
316                  << " from unknown address " << addr.ToSensitiveString();
317 
318     // Check for role conflicts.
319     if (!MaybeIceRoleConflict(addr, msg.get(), remote_username)) {
320       LOG(LS_INFO) << "Received conflicting role from the peer.";
321       return;
322     }
323 
324     SignalUnknownAddress(this, addr, proto, msg.get(), remote_username, false);
325   } else {
326     // NOTE(tschmelcher): STUN_BINDING_RESPONSE is benign. It occurs if we
327     // pruned a connection for this port while it had STUN requests in flight,
328     // because we then get back responses for them, which this code correctly
329     // does not handle.
330     if (msg->type() != STUN_BINDING_RESPONSE) {
331       LOG_J(LS_ERROR, this) << "Received unexpected STUN message type ("
332                             << msg->type() << ") from unknown address ("
333                             << addr.ToSensitiveString() << ")";
334     }
335   }
336 }
337 
OnReadyToSend()338 void Port::OnReadyToSend() {
339   AddressMap::iterator iter = connections_.begin();
340   for (; iter != connections_.end(); ++iter) {
341     iter->second->OnReadyToSend();
342   }
343 }
344 
AddPrflxCandidate(const Candidate & local)345 size_t Port::AddPrflxCandidate(const Candidate& local) {
346   candidates_.push_back(local);
347   return (candidates_.size() - 1);
348 }
349 
GetStunMessage(const char * data,size_t size,const rtc::SocketAddress & addr,std::unique_ptr<IceMessage> * out_msg,std::string * out_username)350 bool Port::GetStunMessage(const char* data,
351                           size_t size,
352                           const rtc::SocketAddress& addr,
353                           std::unique_ptr<IceMessage>* out_msg,
354                           std::string* out_username) {
355   // NOTE: This could clearly be optimized to avoid allocating any memory.
356   //       However, at the data rates we'll be looking at on the client side,
357   //       this probably isn't worth worrying about.
358   RTC_DCHECK(out_msg != NULL);
359   RTC_DCHECK(out_username != NULL);
360   out_username->clear();
361 
362   // Don't bother parsing the packet if we can tell it's not STUN.
363   // In ICE mode, all STUN packets will have a valid fingerprint.
364   if (!StunMessage::ValidateFingerprint(data, size)) {
365     return false;
366   }
367 
368   // Parse the request message.  If the packet is not a complete and correct
369   // STUN message, then ignore it.
370   std::unique_ptr<IceMessage> stun_msg(new IceMessage());
371   rtc::ByteBufferReader buf(data, size);
372   if (!stun_msg->Read(&buf) || (buf.Length() > 0)) {
373     return false;
374   }
375 
376   if (stun_msg->type() == STUN_BINDING_REQUEST) {
377     // Check for the presence of USERNAME and MESSAGE-INTEGRITY (if ICE) first.
378     // If not present, fail with a 400 Bad Request.
379     if (!stun_msg->GetByteString(STUN_ATTR_USERNAME) ||
380         !stun_msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY)) {
381       LOG_J(LS_ERROR, this) << "Received STUN request without username/M-I "
382                             << "from " << addr.ToSensitiveString();
383       SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_BAD_REQUEST,
384                                STUN_ERROR_REASON_BAD_REQUEST);
385       return true;
386     }
387 
388     // If the username is bad or unknown, fail with a 401 Unauthorized.
389     std::string local_ufrag;
390     std::string remote_ufrag;
391     if (!ParseStunUsername(stun_msg.get(), &local_ufrag, &remote_ufrag) ||
392         local_ufrag != username_fragment()) {
393       LOG_J(LS_ERROR, this) << "Received STUN request with bad local username "
394                             << local_ufrag << " from "
395                             << addr.ToSensitiveString();
396       SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
397                                STUN_ERROR_REASON_UNAUTHORIZED);
398       return true;
399     }
400 
401     // If ICE, and the MESSAGE-INTEGRITY is bad, fail with a 401 Unauthorized
402     if (!stun_msg->ValidateMessageIntegrity(data, size, password_)) {
403       LOG_J(LS_ERROR, this) << "Received STUN request with bad M-I "
404                             << "from " << addr.ToSensitiveString()
405                             << ", password_=" << password_;
406       SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED,
407                                STUN_ERROR_REASON_UNAUTHORIZED);
408       return true;
409     }
410     out_username->assign(remote_ufrag);
411   } else if ((stun_msg->type() == STUN_BINDING_RESPONSE) ||
412              (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE)) {
413     if (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE) {
414       if (const StunErrorCodeAttribute* error_code = stun_msg->GetErrorCode()) {
415         LOG_J(LS_ERROR, this) << "Received STUN binding error:"
416                               << " class=" << error_code->eclass()
417                               << " number=" << error_code->number()
418                               << " reason='" << error_code->reason() << "'"
419                               << " from " << addr.ToSensitiveString();
420         // Return message to allow error-specific processing
421       } else {
422         LOG_J(LS_ERROR, this) << "Received STUN binding error without a error "
423                               << "code from " << addr.ToSensitiveString();
424         return true;
425       }
426     }
427     // NOTE: Username should not be used in verifying response messages.
428     out_username->clear();
429   } else if (stun_msg->type() == STUN_BINDING_INDICATION) {
430     LOG_J(LS_VERBOSE, this) << "Received STUN binding indication:"
431                             << " from " << addr.ToSensitiveString();
432     out_username->clear();
433     // No stun attributes will be verified, if it's stun indication message.
434     // Returning from end of the this method.
435   } else {
436     LOG_J(LS_ERROR, this) << "Received STUN packet with invalid type ("
437                           << stun_msg->type() << ") from "
438                           << addr.ToSensitiveString();
439     return true;
440   }
441 
442   // Return the STUN message found.
443   *out_msg = std::move(stun_msg);
444   return true;
445 }
446 
IsCompatibleAddress(const rtc::SocketAddress & addr)447 bool Port::IsCompatibleAddress(const rtc::SocketAddress& addr) {
448   int family = ip().family();
449   // We use single-stack sockets, so families must match.
450   if (addr.family() != family) {
451     return false;
452   }
453   // Link-local IPv6 ports can only connect to other link-local IPv6 ports.
454   if (family == AF_INET6 &&
455       (IPIsLinkLocal(ip()) != IPIsLinkLocal(addr.ipaddr()))) {
456     return false;
457   }
458   return true;
459 }
460 
ParseStunUsername(const StunMessage * stun_msg,std::string * local_ufrag,std::string * remote_ufrag) const461 bool Port::ParseStunUsername(const StunMessage* stun_msg,
462                              std::string* local_ufrag,
463                              std::string* remote_ufrag) const {
464   // The packet must include a username that either begins or ends with our
465   // fragment.  It should begin with our fragment if it is a request and it
466   // should end with our fragment if it is a response.
467   local_ufrag->clear();
468   remote_ufrag->clear();
469   const StunByteStringAttribute* username_attr =
470         stun_msg->GetByteString(STUN_ATTR_USERNAME);
471   if (username_attr == NULL)
472     return false;
473 
474   // RFRAG:LFRAG
475   const std::string username = username_attr->GetString();
476   size_t colon_pos = username.find(":");
477   if (colon_pos == std::string::npos) {
478     return false;
479   }
480 
481   *local_ufrag = username.substr(0, colon_pos);
482   *remote_ufrag = username.substr(colon_pos + 1, username.size());
483   return true;
484 }
485 
MaybeIceRoleConflict(const rtc::SocketAddress & addr,IceMessage * stun_msg,const std::string & remote_ufrag)486 bool Port::MaybeIceRoleConflict(
487     const rtc::SocketAddress& addr, IceMessage* stun_msg,
488     const std::string& remote_ufrag) {
489   // Validate ICE_CONTROLLING or ICE_CONTROLLED attributes.
490   bool ret = true;
491   IceRole remote_ice_role = ICEROLE_UNKNOWN;
492   uint64_t remote_tiebreaker = 0;
493   const StunUInt64Attribute* stun_attr =
494       stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
495   if (stun_attr) {
496     remote_ice_role = ICEROLE_CONTROLLING;
497     remote_tiebreaker = stun_attr->value();
498   }
499 
500   // If |remote_ufrag| is same as port local username fragment and
501   // tie breaker value received in the ping message matches port
502   // tiebreaker value this must be a loopback call.
503   // We will treat this as valid scenario.
504   if (remote_ice_role == ICEROLE_CONTROLLING &&
505       username_fragment() == remote_ufrag &&
506       remote_tiebreaker == IceTiebreaker()) {
507     return true;
508   }
509 
510   stun_attr = stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
511   if (stun_attr) {
512     remote_ice_role = ICEROLE_CONTROLLED;
513     remote_tiebreaker = stun_attr->value();
514   }
515 
516   switch (ice_role_) {
517     case ICEROLE_CONTROLLING:
518       if (ICEROLE_CONTROLLING == remote_ice_role) {
519         if (remote_tiebreaker >= tiebreaker_) {
520           SignalRoleConflict(this);
521         } else {
522           // Send Role Conflict (487) error response.
523           SendBindingErrorResponse(stun_msg, addr,
524               STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
525           ret = false;
526         }
527       }
528       break;
529     case ICEROLE_CONTROLLED:
530       if (ICEROLE_CONTROLLED == remote_ice_role) {
531         if (remote_tiebreaker < tiebreaker_) {
532           SignalRoleConflict(this);
533         } else {
534           // Send Role Conflict (487) error response.
535           SendBindingErrorResponse(stun_msg, addr,
536               STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT);
537           ret = false;
538         }
539       }
540       break;
541     default:
542       RTC_NOTREACHED();
543   }
544   return ret;
545 }
546 
CreateStunUsername(const std::string & remote_username,std::string * stun_username_attr_str) const547 void Port::CreateStunUsername(const std::string& remote_username,
548                               std::string* stun_username_attr_str) const {
549   stun_username_attr_str->clear();
550   *stun_username_attr_str = remote_username;
551   stun_username_attr_str->append(":");
552   stun_username_attr_str->append(username_fragment());
553 }
554 
SendBindingResponse(StunMessage * request,const rtc::SocketAddress & addr)555 void Port::SendBindingResponse(StunMessage* request,
556                                const rtc::SocketAddress& addr) {
557   RTC_DCHECK(request->type() == STUN_BINDING_REQUEST);
558 
559   // Retrieve the username from the request.
560   const StunByteStringAttribute* username_attr =
561       request->GetByteString(STUN_ATTR_USERNAME);
562   RTC_DCHECK(username_attr != NULL);
563   if (username_attr == NULL) {
564     // No valid username, skip the response.
565     return;
566   }
567 
568   // Fill in the response message.
569   StunMessage response;
570   response.SetType(STUN_BINDING_RESPONSE);
571   response.SetTransactionID(request->transaction_id());
572   const StunUInt32Attribute* retransmit_attr =
573       request->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
574   if (retransmit_attr) {
575     // Inherit the incoming retransmit value in the response so the other side
576     // can see our view of lost pings.
577     response.AddAttribute(new StunUInt32Attribute(
578         STUN_ATTR_RETRANSMIT_COUNT, retransmit_attr->value()));
579 
580     if (retransmit_attr->value() > CONNECTION_WRITE_CONNECT_FAILURES) {
581       LOG_J(LS_INFO, this)
582           << "Received a remote ping with high retransmit count: "
583           << retransmit_attr->value();
584     }
585   }
586 
587   response.AddAttribute(
588       new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, addr));
589   response.AddMessageIntegrity(password_);
590   response.AddFingerprint();
591 
592   // Send the response message.
593   rtc::ByteBufferWriter buf;
594   response.Write(&buf);
595   rtc::PacketOptions options(DefaultDscpValue());
596   auto err = SendTo(buf.Data(), buf.Length(), addr, options, false);
597   if (err < 0) {
598     LOG_J(LS_ERROR, this)
599         << "Failed to send STUN ping response"
600         << ", to=" << addr.ToSensitiveString()
601         << ", err=" << err
602         << ", id=" << rtc::hex_encode(response.transaction_id());
603   } else {
604     // Log at LS_INFO if we send a stun ping response on an unwritable
605     // connection.
606     Connection* conn = GetConnection(addr);
607     rtc::LoggingSeverity sev = (conn && !conn->writable()) ?
608         rtc::LS_INFO : rtc::LS_VERBOSE;
609     LOG_JV(sev, this)
610         << "Sent STUN ping response"
611         << ", to=" << addr.ToSensitiveString()
612         << ", id=" << rtc::hex_encode(response.transaction_id());
613 
614     conn->stats_.sent_ping_responses++;
615   }
616 }
617 
SendBindingErrorResponse(StunMessage * request,const rtc::SocketAddress & addr,int error_code,const std::string & reason)618 void Port::SendBindingErrorResponse(StunMessage* request,
619                                     const rtc::SocketAddress& addr,
620                                     int error_code, const std::string& reason) {
621   RTC_DCHECK(request->type() == STUN_BINDING_REQUEST);
622 
623   // Fill in the response message.
624   StunMessage response;
625   response.SetType(STUN_BINDING_ERROR_RESPONSE);
626   response.SetTransactionID(request->transaction_id());
627 
628   // When doing GICE, we need to write out the error code incorrectly to
629   // maintain backwards compatiblility.
630   StunErrorCodeAttribute* error_attr = StunAttribute::CreateErrorCode();
631   error_attr->SetCode(error_code);
632   error_attr->SetReason(reason);
633   response.AddAttribute(error_attr);
634 
635   // Per Section 10.1.2, certain error cases don't get a MESSAGE-INTEGRITY,
636   // because we don't have enough information to determine the shared secret.
637   if (error_code != STUN_ERROR_BAD_REQUEST &&
638       error_code != STUN_ERROR_UNAUTHORIZED)
639     response.AddMessageIntegrity(password_);
640   response.AddFingerprint();
641 
642   // Send the response message.
643   rtc::ByteBufferWriter buf;
644   response.Write(&buf);
645   rtc::PacketOptions options(DefaultDscpValue());
646   SendTo(buf.Data(), buf.Length(), addr, options, false);
647   LOG_J(LS_INFO, this) << "Sending STUN binding error: reason=" << reason
648                        << " to " << addr.ToSensitiveString();
649 }
650 
KeepAliveUntilPruned()651 void Port::KeepAliveUntilPruned() {
652   // If it is pruned, we won't bring it up again.
653   if (state_ == State::INIT) {
654     state_ = State::KEEP_ALIVE_UNTIL_PRUNED;
655   }
656 }
657 
Prune()658 void Port::Prune() {
659   state_ = State::PRUNED;
660   thread_->Post(RTC_FROM_HERE, this, MSG_DESTROY_IF_DEAD);
661 }
662 
OnMessage(rtc::Message * pmsg)663 void Port::OnMessage(rtc::Message *pmsg) {
664   RTC_DCHECK(pmsg->message_id == MSG_DESTROY_IF_DEAD);
665   bool dead =
666       (state_ == State::INIT || state_ == State::PRUNED) &&
667       connections_.empty() &&
668       rtc::TimeMillis() - last_time_all_connections_removed_ >= timeout_delay_;
669   if (dead) {
670     Destroy();
671   }
672 }
673 
OnNetworkTypeChanged(const rtc::Network * network)674 void Port::OnNetworkTypeChanged(const rtc::Network* network) {
675   RTC_DCHECK(network == network_);
676 
677   UpdateNetworkCost();
678 }
679 
ToString() const680 std::string Port::ToString() const {
681   std::stringstream ss;
682   ss << "Port[" << std::hex << this << std::dec << ":" << content_name_ << ":"
683      << component_ << ":" << generation_ << ":" << type_ << ":"
684      << network_->ToString() << "]";
685   return ss.str();
686 }
687 
688 // TODO(honghaiz): Make the network cost configurable from user setting.
UpdateNetworkCost()689 void Port::UpdateNetworkCost() {
690   uint16_t new_cost = network_->GetCost();
691   if (network_cost_ == new_cost) {
692     return;
693   }
694   LOG(LS_INFO) << "Network cost changed from " << network_cost_
695                << " to " << new_cost
696                << ". Number of candidates created: " << candidates_.size()
697                << ". Number of connections created: " << connections_.size();
698   network_cost_ = new_cost;
699   for (cricket::Candidate& candidate : candidates_) {
700     candidate.set_network_cost(network_cost_);
701   }
702   // Network cost change will affect the connection selection criteria.
703   // Signal the connection state change on each connection to force a
704   // re-sort in P2PTransportChannel.
705   for (auto kv : connections_) {
706     Connection* conn = kv.second;
707     conn->SignalStateChange(conn);
708   }
709 }
710 
EnablePortPackets()711 void Port::EnablePortPackets() {
712   enable_port_packets_ = true;
713 }
714 
OnConnectionDestroyed(Connection * conn)715 void Port::OnConnectionDestroyed(Connection* conn) {
716   AddressMap::iterator iter =
717       connections_.find(conn->remote_candidate().address());
718   RTC_DCHECK(iter != connections_.end());
719   connections_.erase(iter);
720   HandleConnectionDestroyed(conn);
721 
722   // Ports time out after all connections fail if it is not marked as
723   // "keep alive until pruned."
724   // Note: If a new connection is added after this message is posted, but it
725   // fails and is removed before kPortTimeoutDelay, then this message will
726   // not cause the Port to be destroyed.
727   if (connections_.empty()) {
728     last_time_all_connections_removed_ = rtc::TimeMillis();
729     thread_->PostDelayed(RTC_FROM_HERE, timeout_delay_, this,
730                          MSG_DESTROY_IF_DEAD);
731   }
732 }
733 
Destroy()734 void Port::Destroy() {
735   RTC_DCHECK(connections_.empty());
736   LOG_J(LS_INFO, this) << "Port deleted";
737   SignalDestroyed(this);
738   delete this;
739 }
740 
username_fragment() const741 const std::string Port::username_fragment() const {
742   return ice_username_fragment_;
743 }
744 
745 // A ConnectionRequest is a simple STUN ping used to determine writability.
746 class ConnectionRequest : public StunRequest {
747  public:
ConnectionRequest(Connection * connection)748   explicit ConnectionRequest(Connection* connection)
749       : StunRequest(new IceMessage()),
750         connection_(connection) {
751   }
752 
~ConnectionRequest()753   virtual ~ConnectionRequest() {
754   }
755 
Prepare(StunMessage * request)756   void Prepare(StunMessage* request) override {
757     request->SetType(STUN_BINDING_REQUEST);
758     std::string username;
759     connection_->port()->CreateStunUsername(
760         connection_->remote_candidate().username(), &username);
761     request->AddAttribute(
762         new StunByteStringAttribute(STUN_ATTR_USERNAME, username));
763 
764     // connection_ already holds this ping, so subtract one from count.
765     if (connection_->port()->send_retransmit_count_attribute()) {
766       request->AddAttribute(new StunUInt32Attribute(
767           STUN_ATTR_RETRANSMIT_COUNT,
768           static_cast<uint32_t>(connection_->pings_since_last_response_.size() -
769                                 1)));
770     }
771     uint32_t network_info = connection_->port()->Network()->id();
772     network_info = (network_info << 16) | connection_->port()->network_cost();
773     request->AddAttribute(
774         new StunUInt32Attribute(STUN_ATTR_NETWORK_INFO, network_info));
775 
776     // Adding ICE_CONTROLLED or ICE_CONTROLLING attribute based on the role.
777     if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLING) {
778       request->AddAttribute(new StunUInt64Attribute(
779           STUN_ATTR_ICE_CONTROLLING, connection_->port()->IceTiebreaker()));
780       // We should have either USE_CANDIDATE attribute or ICE_NOMINATION
781       // attribute but not both. That was enforced in p2ptransportchannel.
782       if (connection_->use_candidate_attr()) {
783         request->AddAttribute(new StunByteStringAttribute(
784             STUN_ATTR_USE_CANDIDATE));
785       }
786       if (connection_->nomination() &&
787           connection_->nomination() != connection_->acked_nomination()) {
788         request->AddAttribute(new StunUInt32Attribute(
789             STUN_ATTR_NOMINATION, connection_->nomination()));
790       }
791     } else if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLED) {
792       request->AddAttribute(new StunUInt64Attribute(
793           STUN_ATTR_ICE_CONTROLLED, connection_->port()->IceTiebreaker()));
794     } else {
795       RTC_NOTREACHED();
796     }
797 
798     // Adding PRIORITY Attribute.
799     // Changing the type preference to Peer Reflexive and local preference
800     // and component id information is unchanged from the original priority.
801     // priority = (2^24)*(type preference) +
802     //           (2^8)*(local preference) +
803     //           (2^0)*(256 - component ID)
804     uint32_t type_preference =
805         (connection_->local_candidate().protocol() == TCP_PROTOCOL_NAME)
806             ? ICE_TYPE_PREFERENCE_PRFLX_TCP
807             : ICE_TYPE_PREFERENCE_PRFLX;
808     uint32_t prflx_priority =
809         type_preference << 24 |
810         (connection_->local_candidate().priority() & 0x00FFFFFF);
811     request->AddAttribute(
812         new StunUInt32Attribute(STUN_ATTR_PRIORITY, prflx_priority));
813 
814     // Adding Message Integrity attribute.
815     request->AddMessageIntegrity(connection_->remote_candidate().password());
816     // Adding Fingerprint.
817     request->AddFingerprint();
818   }
819 
OnResponse(StunMessage * response)820   void OnResponse(StunMessage* response) override {
821     connection_->OnConnectionRequestResponse(this, response);
822   }
823 
OnErrorResponse(StunMessage * response)824   void OnErrorResponse(StunMessage* response) override {
825     connection_->OnConnectionRequestErrorResponse(this, response);
826   }
827 
OnTimeout()828   void OnTimeout() override {
829     connection_->OnConnectionRequestTimeout(this);
830   }
831 
OnSent()832   void OnSent() override {
833     connection_->OnConnectionRequestSent(this);
834     // Each request is sent only once.  After a single delay , the request will
835     // time out.
836     timeout_ = true;
837   }
838 
resend_delay()839   int resend_delay() override {
840     return CONNECTION_RESPONSE_TIMEOUT;
841   }
842 
843  private:
844   Connection* connection_;
845 };
846 
847 //
848 // Connection
849 //
850 
Connection(Port * port,size_t index,const Candidate & remote_candidate)851 Connection::Connection(Port* port,
852                        size_t index,
853                        const Candidate& remote_candidate)
854     : port_(port),
855       local_candidate_index_(index),
856       remote_candidate_(remote_candidate),
857       recv_rate_tracker_(100, 10u),
858       send_rate_tracker_(100, 10u),
859       write_state_(STATE_WRITE_INIT),
860       receiving_(false),
861       connected_(true),
862       pruned_(false),
863       use_candidate_attr_(false),
864       remote_ice_mode_(ICEMODE_FULL),
865       requests_(port->thread()),
866       rtt_(DEFAULT_RTT),
867       last_ping_sent_(0),
868       last_ping_received_(0),
869       last_data_received_(0),
870       last_ping_response_received_(0),
871       reported_(false),
872       state_(IceCandidatePairState::WAITING),
873       receiving_timeout_(WEAK_CONNECTION_RECEIVE_TIMEOUT),
874       time_created_ms_(rtc::TimeMillis()) {
875   // All of our connections start in WAITING state.
876   // TODO(mallinath) - Start connections from STATE_FROZEN.
877   // Wire up to send stun packets
878   requests_.SignalSendPacket.connect(this, &Connection::OnSendStunPacket);
879   LOG_J(LS_INFO, this) << "Connection created";
880 }
881 
~Connection()882 Connection::~Connection() {
883 }
884 
local_candidate() const885 const Candidate& Connection::local_candidate() const {
886   RTC_DCHECK(local_candidate_index_ < port_->Candidates().size());
887   return port_->Candidates()[local_candidate_index_];
888 }
889 
remote_candidate() const890 const Candidate& Connection::remote_candidate() const {
891   return remote_candidate_;
892 }
893 
priority() const894 uint64_t Connection::priority() const {
895   uint64_t priority = 0;
896   // RFC 5245 - 5.7.2.  Computing Pair Priority and Ordering Pairs
897   // Let G be the priority for the candidate provided by the controlling
898   // agent.  Let D be the priority for the candidate provided by the
899   // controlled agent.
900   // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
901   IceRole role = port_->GetIceRole();
902   if (role != ICEROLE_UNKNOWN) {
903     uint32_t g = 0;
904     uint32_t d = 0;
905     if (role == ICEROLE_CONTROLLING) {
906       g = local_candidate().priority();
907       d = remote_candidate_.priority();
908     } else {
909       g = remote_candidate_.priority();
910       d = local_candidate().priority();
911     }
912     priority = std::min(g, d);
913     priority = priority << 32;
914     priority += 2 * std::max(g, d) + (g > d ? 1 : 0);
915   }
916   return priority;
917 }
918 
set_write_state(WriteState value)919 void Connection::set_write_state(WriteState value) {
920   WriteState old_value = write_state_;
921   write_state_ = value;
922   if (value != old_value) {
923     LOG_J(LS_VERBOSE, this) << "set_write_state from: " << old_value << " to "
924                             << value;
925     SignalStateChange(this);
926   }
927 }
928 
UpdateReceiving(int64_t now)929 void Connection::UpdateReceiving(int64_t now) {
930   bool receiving =
931       last_received() > 0 && now <= last_received() + receiving_timeout_;
932   if (receiving_ == receiving) {
933     return;
934   }
935   LOG_J(LS_VERBOSE, this) << "set_receiving to " << receiving;
936   receiving_ = receiving;
937   receiving_unchanged_since_ = now;
938   SignalStateChange(this);
939 }
940 
set_state(IceCandidatePairState state)941 void Connection::set_state(IceCandidatePairState state) {
942   IceCandidatePairState old_state = state_;
943   state_ = state;
944   if (state != old_state) {
945     LOG_J(LS_VERBOSE, this) << "set_state";
946   }
947 }
948 
set_connected(bool value)949 void Connection::set_connected(bool value) {
950   bool old_value = connected_;
951   connected_ = value;
952   if (value != old_value) {
953     LOG_J(LS_VERBOSE, this) << "set_connected from: " << old_value << " to "
954                             << value;
955     SignalStateChange(this);
956   }
957 }
958 
set_use_candidate_attr(bool enable)959 void Connection::set_use_candidate_attr(bool enable) {
960   use_candidate_attr_ = enable;
961 }
962 
OnSendStunPacket(const void * data,size_t size,StunRequest * req)963 void Connection::OnSendStunPacket(const void* data, size_t size,
964                                   StunRequest* req) {
965   rtc::PacketOptions options(port_->DefaultDscpValue());
966   auto err = port_->SendTo(
967       data, size, remote_candidate_.address(), options, false);
968   if (err < 0) {
969     LOG_J(LS_WARNING, this) << "Failed to send STUN ping "
970                             << " err=" << err
971                             << " id=" << rtc::hex_encode(req->id());
972   }
973 }
974 
OnReadPacket(const char * data,size_t size,const rtc::PacketTime & packet_time)975 void Connection::OnReadPacket(
976   const char* data, size_t size, const rtc::PacketTime& packet_time) {
977   std::unique_ptr<IceMessage> msg;
978   std::string remote_ufrag;
979   const rtc::SocketAddress& addr(remote_candidate_.address());
980   if (!port_->GetStunMessage(data, size, addr, &msg, &remote_ufrag)) {
981     // The packet did not parse as a valid STUN message
982     // This is a data packet, pass it along.
983     last_data_received_ = rtc::TimeMillis();
984     UpdateReceiving(last_data_received_);
985     recv_rate_tracker_.AddSamples(size);
986     SignalReadPacket(this, data, size, packet_time);
987 
988     // If timed out sending writability checks, start up again
989     if (!pruned_ && (write_state_ == STATE_WRITE_TIMEOUT)) {
990       LOG(LS_WARNING) << "Received a data packet on a timed-out Connection. "
991                       << "Resetting state to STATE_WRITE_INIT.";
992       set_write_state(STATE_WRITE_INIT);
993     }
994   } else if (!msg) {
995     // The packet was STUN, but failed a check and was handled internally.
996   } else {
997     // The packet is STUN and passed the Port checks.
998     // Perform our own checks to ensure this packet is valid.
999     // If this is a STUN request, then update the receiving bit and respond.
1000     // If this is a STUN response, then update the writable bit.
1001     // Log at LS_INFO if we receive a ping on an unwritable connection.
1002     rtc::LoggingSeverity sev = (!writable() ? rtc::LS_INFO : rtc::LS_VERBOSE);
1003     switch (msg->type()) {
1004       case STUN_BINDING_REQUEST:
1005         LOG_JV(sev, this) << "Received STUN ping"
1006                           << ", id=" << rtc::hex_encode(msg->transaction_id());
1007 
1008         if (remote_ufrag == remote_candidate_.username()) {
1009           HandleBindingRequest(msg.get());
1010         } else {
1011           // The packet had the right local username, but the remote username
1012           // was not the right one for the remote address.
1013           LOG_J(LS_ERROR, this)
1014             << "Received STUN request with bad remote username "
1015             << remote_ufrag;
1016           port_->SendBindingErrorResponse(msg.get(), addr,
1017                                           STUN_ERROR_UNAUTHORIZED,
1018                                           STUN_ERROR_REASON_UNAUTHORIZED);
1019 
1020         }
1021         break;
1022 
1023       // Response from remote peer. Does it match request sent?
1024       // This doesn't just check, it makes callbacks if transaction
1025       // id's match.
1026       case STUN_BINDING_RESPONSE:
1027       case STUN_BINDING_ERROR_RESPONSE:
1028         if (msg->ValidateMessageIntegrity(
1029                 data, size, remote_candidate().password())) {
1030           requests_.CheckResponse(msg.get());
1031         }
1032         // Otherwise silently discard the response message.
1033         break;
1034 
1035       // Remote end point sent an STUN indication instead of regular binding
1036       // request. In this case |last_ping_received_| will be updated but no
1037       // response will be sent.
1038       case STUN_BINDING_INDICATION:
1039         ReceivedPing();
1040         break;
1041 
1042       default:
1043         RTC_NOTREACHED();
1044         break;
1045     }
1046   }
1047 }
1048 
HandleBindingRequest(IceMessage * msg)1049 void Connection::HandleBindingRequest(IceMessage* msg) {
1050   // This connection should now be receiving.
1051   ReceivedPing();
1052 
1053   const rtc::SocketAddress& remote_addr = remote_candidate_.address();
1054   const std::string& remote_ufrag = remote_candidate_.username();
1055   // Check for role conflicts.
1056   if (!port_->MaybeIceRoleConflict(remote_addr, msg, remote_ufrag)) {
1057     // Received conflicting role from the peer.
1058     LOG(LS_INFO) << "Received conflicting role from the peer.";
1059     return;
1060   }
1061 
1062   stats_.recv_ping_requests++;
1063 
1064   // This is a validated stun request from remote peer.
1065   port_->SendBindingResponse(msg, remote_addr);
1066 
1067   // If it timed out on writing check, start up again
1068   if (!pruned_ && write_state_ == STATE_WRITE_TIMEOUT) {
1069     set_write_state(STATE_WRITE_INIT);
1070   }
1071 
1072   if (port_->GetIceRole() == ICEROLE_CONTROLLED) {
1073     const StunUInt32Attribute* nomination_attr =
1074         msg->GetUInt32(STUN_ATTR_NOMINATION);
1075     uint32_t nomination = 0;
1076     if (nomination_attr) {
1077       nomination = nomination_attr->value();
1078       if (nomination == 0) {
1079         LOG(LS_ERROR) << "Invalid nomination: " << nomination;
1080       }
1081     } else {
1082       const StunByteStringAttribute* use_candidate_attr =
1083           msg->GetByteString(STUN_ATTR_USE_CANDIDATE);
1084       if (use_candidate_attr) {
1085         nomination = 1;
1086       }
1087     }
1088     // We don't un-nominate a connection, so we only keep a larger nomination.
1089     if (nomination > remote_nomination_) {
1090       set_remote_nomination(nomination);
1091       SignalNominated(this);
1092     }
1093   }
1094   // Set the remote cost if the network_info attribute is available.
1095   // Note: If packets are re-ordered, we may get incorrect network cost
1096   // temporarily, but it should get the correct value shortly after that.
1097   const StunUInt32Attribute* network_attr =
1098       msg->GetUInt32(STUN_ATTR_NETWORK_INFO);
1099   if (network_attr) {
1100     uint32_t network_info = network_attr->value();
1101     uint16_t network_cost = static_cast<uint16_t>(network_info);
1102     if (network_cost != remote_candidate_.network_cost()) {
1103       remote_candidate_.set_network_cost(network_cost);
1104       // Network cost change will affect the connection ranking, so signal
1105       // state change to force a re-sort in P2PTransportChannel.
1106       SignalStateChange(this);
1107     }
1108   }
1109 }
1110 
OnReadyToSend()1111 void Connection::OnReadyToSend() {
1112   SignalReadyToSend(this);
1113 }
1114 
Prune()1115 void Connection::Prune() {
1116   if (!pruned_ || active()) {
1117     LOG_J(LS_INFO, this) << "Connection pruned";
1118     pruned_ = true;
1119     requests_.Clear();
1120     set_write_state(STATE_WRITE_TIMEOUT);
1121   }
1122 }
1123 
Destroy()1124 void Connection::Destroy() {
1125   LOG_J(LS_VERBOSE, this) << "Connection destroyed";
1126   port_->thread()->Post(RTC_FROM_HERE, this, MSG_DELETE);
1127 }
1128 
FailAndDestroy()1129 void Connection::FailAndDestroy() {
1130   set_state(IceCandidatePairState::FAILED);
1131   Destroy();
1132 }
1133 
FailAndPrune()1134 void Connection::FailAndPrune() {
1135   set_state(IceCandidatePairState::FAILED);
1136   Prune();
1137 }
1138 
PrintPingsSinceLastResponse(std::string * s,size_t max)1139 void Connection::PrintPingsSinceLastResponse(std::string* s, size_t max) {
1140   std::ostringstream oss;
1141   oss << std::boolalpha;
1142   if (pings_since_last_response_.size() > max) {
1143     for (size_t i = 0; i < max; i++) {
1144       const SentPing& ping = pings_since_last_response_[i];
1145       oss << rtc::hex_encode(ping.id) << " ";
1146     }
1147     oss << "... " << (pings_since_last_response_.size() - max) << " more";
1148   } else {
1149     for (const SentPing& ping : pings_since_last_response_) {
1150       oss << rtc::hex_encode(ping.id) << " ";
1151     }
1152   }
1153   *s = oss.str();
1154 }
1155 
UpdateState(int64_t now)1156 void Connection::UpdateState(int64_t now) {
1157   int rtt = ConservativeRTTEstimate(rtt_);
1158 
1159   if (LOG_CHECK_LEVEL(LS_VERBOSE)) {
1160     std::string pings;
1161     PrintPingsSinceLastResponse(&pings, 5);
1162     LOG_J(LS_VERBOSE, this) << "UpdateState()"
1163                             << ", ms since last received response="
1164                             << now - last_ping_response_received_
1165                             << ", ms since last received data="
1166                             << now - last_data_received_
1167                             << ", rtt=" << rtt
1168                             << ", pings_since_last_response=" << pings;
1169   }
1170 
1171   // Check the writable state.  (The order of these checks is important.)
1172   //
1173   // Before becoming unwritable, we allow for a fixed number of pings to fail
1174   // (i.e., receive no response).  We also have to give the response time to
1175   // get back, so we include a conservative estimate of this.
1176   //
1177   // Before timing out writability, we give a fixed amount of time.  This is to
1178   // allow for changes in network conditions.
1179 
1180   if ((write_state_ == STATE_WRITABLE) &&
1181       TooManyFailures(pings_since_last_response_,
1182                       CONNECTION_WRITE_CONNECT_FAILURES,
1183                       rtt,
1184                       now) &&
1185       TooLongWithoutResponse(pings_since_last_response_,
1186                              CONNECTION_WRITE_CONNECT_TIMEOUT,
1187                              now)) {
1188     uint32_t max_pings = CONNECTION_WRITE_CONNECT_FAILURES;
1189     LOG_J(LS_INFO, this) << "Unwritable after " << max_pings
1190                          << " ping failures and "
1191                          << now - pings_since_last_response_[0].sent_time
1192                          << " ms without a response,"
1193                          << " ms since last received ping="
1194                          << now - last_ping_received_
1195                          << " ms since last received data="
1196                          << now - last_data_received_
1197                          << " rtt=" << rtt;
1198     set_write_state(STATE_WRITE_UNRELIABLE);
1199   }
1200   if ((write_state_ == STATE_WRITE_UNRELIABLE ||
1201        write_state_ == STATE_WRITE_INIT) &&
1202       TooLongWithoutResponse(pings_since_last_response_,
1203                              CONNECTION_WRITE_TIMEOUT,
1204                              now)) {
1205     LOG_J(LS_INFO, this) << "Timed out after "
1206                          << now - pings_since_last_response_[0].sent_time
1207                          << " ms without a response"
1208                          << ", rtt=" << rtt;
1209     set_write_state(STATE_WRITE_TIMEOUT);
1210   }
1211 
1212   // Update the receiving state.
1213   UpdateReceiving(now);
1214   if (dead(now)) {
1215     Destroy();
1216   }
1217 }
1218 
Ping(int64_t now)1219 void Connection::Ping(int64_t now) {
1220   last_ping_sent_ = now;
1221   ConnectionRequest *req = new ConnectionRequest(this);
1222   pings_since_last_response_.push_back(SentPing(req->id(), now, nomination_));
1223   LOG_J(LS_VERBOSE, this) << "Sending STUN ping "
1224                           << ", id=" << rtc::hex_encode(req->id())
1225                           << ", nomination=" << nomination_;
1226   requests_.Send(req);
1227   state_ = IceCandidatePairState::IN_PROGRESS;
1228   num_pings_sent_++;
1229 }
1230 
ReceivedPing()1231 void Connection::ReceivedPing() {
1232   last_ping_received_ = rtc::TimeMillis();
1233   UpdateReceiving(last_ping_received_);
1234 }
1235 
ReceivedPingResponse(int rtt,const std::string & request_id)1236 void Connection::ReceivedPingResponse(int rtt, const std::string& request_id) {
1237   // We've already validated that this is a STUN binding response with
1238   // the correct local and remote username for this connection.
1239   // So if we're not already, become writable. We may be bringing a pruned
1240   // connection back to life, but if we don't really want it, we can always
1241   // prune it again.
1242   auto iter = std::find_if(
1243       pings_since_last_response_.begin(), pings_since_last_response_.end(),
1244       [request_id](const SentPing& ping) { return ping.id == request_id; });
1245   if (iter != pings_since_last_response_.end() &&
1246       iter->nomination > acked_nomination_) {
1247     acked_nomination_ = iter->nomination;
1248   }
1249 
1250   pings_since_last_response_.clear();
1251   last_ping_response_received_ = rtc::TimeMillis();
1252   UpdateReceiving(last_ping_response_received_);
1253   set_write_state(STATE_WRITABLE);
1254   set_state(IceCandidatePairState::SUCCEEDED);
1255   rtt_samples_++;
1256   rtt_ = (RTT_RATIO * rtt_ + rtt) / (RTT_RATIO + 1);
1257 }
1258 
dead(int64_t now) const1259 bool Connection::dead(int64_t now) const {
1260   if (last_received() > 0) {
1261     // If it has ever received anything, we keep it alive until it hasn't
1262     // received anything for DEAD_CONNECTION_RECEIVE_TIMEOUT. This covers the
1263     // normal case of a successfully used connection that stops working. This
1264     // also allows a remote peer to continue pinging over a locally inactive
1265     // (pruned) connection.
1266     return (now > (last_received() + DEAD_CONNECTION_RECEIVE_TIMEOUT));
1267   }
1268 
1269   if (active()) {
1270     // If it has never received anything, keep it alive as long as it is
1271     // actively pinging and not pruned. Otherwise, the connection might be
1272     // deleted before it has a chance to ping. This is the normal case for a
1273     // new connection that is pinging but hasn't received anything yet.
1274     return false;
1275   }
1276 
1277   // If it has never received anything and is not actively pinging (pruned), we
1278   // keep it around for at least MIN_CONNECTION_LIFETIME to prevent connections
1279   // from being pruned too quickly during a network change event when two
1280   // networks would be up simultaneously but only for a brief period.
1281   return now > (time_created_ms_ + MIN_CONNECTION_LIFETIME);
1282 }
1283 
stable(int64_t now) const1284 bool Connection::stable(int64_t now) const {
1285   // A connection is stable if it's RTT has converged and it isn't missing any
1286   // responses.  We should send pings at a higher rate until the RTT converges
1287   // and whenever a ping response is missing (so that we can detect
1288   // unwritability faster)
1289   return rtt_converged() && !missing_responses(now);
1290 }
1291 
ToDebugId() const1292 std::string Connection::ToDebugId() const {
1293   std::stringstream ss;
1294   ss << std::hex << this;
1295   return ss.str();
1296 }
1297 
ComputeNetworkCost() const1298 uint32_t Connection::ComputeNetworkCost() const {
1299   // TODO(honghaiz): Will add rtt as part of the network cost.
1300   return port()->network_cost() + remote_candidate_.network_cost();
1301 }
1302 
ToString() const1303 std::string Connection::ToString() const {
1304   const char CONNECT_STATE_ABBREV[2] = {
1305     '-',  // not connected (false)
1306     'C',  // connected (true)
1307   };
1308   const char RECEIVE_STATE_ABBREV[2] = {
1309     '-',  // not receiving (false)
1310     'R',  // receiving (true)
1311   };
1312   const char WRITE_STATE_ABBREV[4] = {
1313     'W',  // STATE_WRITABLE
1314     'w',  // STATE_WRITE_UNRELIABLE
1315     '-',  // STATE_WRITE_INIT
1316     'x',  // STATE_WRITE_TIMEOUT
1317   };
1318   const std::string ICESTATE[4] = {
1319     "W",  // STATE_WAITING
1320     "I",  // STATE_INPROGRESS
1321     "S",  // STATE_SUCCEEDED
1322     "F"   // STATE_FAILED
1323   };
1324   const Candidate& local = local_candidate();
1325   const Candidate& remote = remote_candidate();
1326   std::stringstream ss;
1327   ss << "Conn[" << ToDebugId() << ":" << port_->content_name() << ":"
1328      << local.id() << ":" << local.component() << ":" << local.generation()
1329      << ":" << local.type() << ":" << local.protocol() << ":"
1330      << local.address().ToSensitiveString() << "->" << remote.id() << ":"
1331      << remote.component() << ":" << remote.priority() << ":" << remote.type()
1332      << ":" << remote.protocol() << ":" << remote.address().ToSensitiveString()
1333      << "|" << CONNECT_STATE_ABBREV[connected()]
1334      << RECEIVE_STATE_ABBREV[receiving()] << WRITE_STATE_ABBREV[write_state()]
1335      << ICESTATE[static_cast<int>(state())] << "|" << remote_nomination() << "|"
1336      << nomination() << "|" << priority() << "|";
1337   if (rtt_ < DEFAULT_RTT) {
1338     ss << rtt_ << "]";
1339   } else {
1340     ss << "-]";
1341   }
1342   return ss.str();
1343 }
1344 
ToSensitiveString() const1345 std::string Connection::ToSensitiveString() const {
1346   return ToString();
1347 }
1348 
OnConnectionRequestResponse(ConnectionRequest * request,StunMessage * response)1349 void Connection::OnConnectionRequestResponse(ConnectionRequest* request,
1350                                              StunMessage* response) {
1351   // Log at LS_INFO if we receive a ping response on an unwritable
1352   // connection.
1353   rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1354 
1355   int rtt = request->Elapsed();
1356 
1357   if (LOG_CHECK_LEVEL_V(sev)) {
1358     std::string pings;
1359     PrintPingsSinceLastResponse(&pings, 5);
1360     LOG_JV(sev, this) << "Received STUN ping response"
1361                       << ", id=" << rtc::hex_encode(request->id())
1362                       << ", code=0"  // Makes logging easier to parse.
1363                       << ", rtt=" << rtt
1364                       << ", pings_since_last_response=" << pings;
1365   }
1366   ReceivedPingResponse(rtt, request->id());
1367 
1368   stats_.recv_ping_responses++;
1369 
1370   MaybeUpdateLocalCandidate(request, response);
1371 }
1372 
OnConnectionRequestErrorResponse(ConnectionRequest * request,StunMessage * response)1373 void Connection::OnConnectionRequestErrorResponse(ConnectionRequest* request,
1374                                                   StunMessage* response) {
1375   const StunErrorCodeAttribute* error_attr = response->GetErrorCode();
1376   int error_code = STUN_ERROR_GLOBAL_FAILURE;
1377   if (error_attr) {
1378     error_code = error_attr->code();
1379   }
1380 
1381   LOG_J(LS_INFO, this) << "Received STUN error response"
1382                        << " id=" << rtc::hex_encode(request->id())
1383                        << " code=" << error_code
1384                        << " rtt=" << request->Elapsed();
1385 
1386   if (error_code == STUN_ERROR_UNKNOWN_ATTRIBUTE ||
1387       error_code == STUN_ERROR_SERVER_ERROR ||
1388       error_code == STUN_ERROR_UNAUTHORIZED) {
1389     // Recoverable error, retry
1390   } else if (error_code == STUN_ERROR_STALE_CREDENTIALS) {
1391     // Race failure, retry
1392   } else if (error_code == STUN_ERROR_ROLE_CONFLICT) {
1393     HandleRoleConflictFromPeer();
1394   } else {
1395     // This is not a valid connection.
1396     LOG_J(LS_ERROR, this) << "Received STUN error response, code="
1397                           << error_code << "; killing connection";
1398     FailAndDestroy();
1399   }
1400 }
1401 
OnConnectionRequestTimeout(ConnectionRequest * request)1402 void Connection::OnConnectionRequestTimeout(ConnectionRequest* request) {
1403   // Log at LS_INFO if we miss a ping on a writable connection.
1404   rtc::LoggingSeverity sev = writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1405   LOG_JV(sev, this) << "Timing-out STUN ping "
1406                     << rtc::hex_encode(request->id())
1407                     << " after " << request->Elapsed() << " ms";
1408 }
1409 
OnConnectionRequestSent(ConnectionRequest * request)1410 void Connection::OnConnectionRequestSent(ConnectionRequest* request) {
1411   // Log at LS_INFO if we send a ping on an unwritable connection.
1412   rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
1413   LOG_JV(sev, this) << "Sent STUN ping"
1414                     << ", id=" << rtc::hex_encode(request->id())
1415                     << ", use_candidate=" << use_candidate_attr()
1416                     << ", nomination=" << nomination();
1417   stats_.sent_ping_requests_total++;
1418   if (stats_.recv_ping_responses == 0) {
1419     stats_.sent_ping_requests_before_first_response++;
1420   }
1421 }
1422 
HandleRoleConflictFromPeer()1423 void Connection::HandleRoleConflictFromPeer() {
1424   port_->SignalRoleConflict(port_);
1425 }
1426 
MaybeSetRemoteIceParametersAndGeneration(const IceParameters & ice_params,int generation)1427 void Connection::MaybeSetRemoteIceParametersAndGeneration(
1428     const IceParameters& ice_params,
1429     int generation) {
1430   if (remote_candidate_.username() == ice_params.ufrag &&
1431       remote_candidate_.password().empty()) {
1432     remote_candidate_.set_password(ice_params.pwd);
1433   }
1434   // TODO(deadbeef): A value of '0' for the generation is used for both
1435   // generation 0 and "generation unknown". It should be changed to an
1436   // rtc::Optional to fix this.
1437   if (remote_candidate_.username() == ice_params.ufrag &&
1438       remote_candidate_.password() == ice_params.pwd &&
1439       remote_candidate_.generation() == 0) {
1440     remote_candidate_.set_generation(generation);
1441   }
1442 }
1443 
MaybeUpdatePeerReflexiveCandidate(const Candidate & new_candidate)1444 void Connection::MaybeUpdatePeerReflexiveCandidate(
1445     const Candidate& new_candidate) {
1446   if (remote_candidate_.type() == PRFLX_PORT_TYPE &&
1447       new_candidate.type() != PRFLX_PORT_TYPE &&
1448       remote_candidate_.protocol() == new_candidate.protocol() &&
1449       remote_candidate_.address() == new_candidate.address() &&
1450       remote_candidate_.username() == new_candidate.username() &&
1451       remote_candidate_.password() == new_candidate.password() &&
1452       remote_candidate_.generation() == new_candidate.generation()) {
1453     remote_candidate_ = new_candidate;
1454   }
1455 }
1456 
OnMessage(rtc::Message * pmsg)1457 void Connection::OnMessage(rtc::Message *pmsg) {
1458   RTC_DCHECK(pmsg->message_id == MSG_DELETE);
1459   LOG(LS_INFO) << "Connection deleted with number of pings sent: "
1460                << num_pings_sent_;
1461   SignalDestroyed(this);
1462   delete this;
1463 }
1464 
last_received() const1465 int64_t Connection::last_received() const {
1466   return std::max(last_data_received_,
1467              std::max(last_ping_received_, last_ping_response_received_));
1468 }
1469 
stats()1470 ConnectionInfo Connection::stats() {
1471   stats_.recv_bytes_second = round(recv_rate_tracker_.ComputeRate());
1472   stats_.recv_total_bytes = recv_rate_tracker_.TotalSampleCount();
1473   stats_.sent_bytes_second = round(send_rate_tracker_.ComputeRate());
1474   stats_.sent_total_bytes = send_rate_tracker_.TotalSampleCount();
1475   stats_.receiving = receiving_;
1476   stats_.writable = write_state_ == STATE_WRITABLE;
1477   stats_.timeout = write_state_ == STATE_WRITE_TIMEOUT;
1478   stats_.new_connection = !reported_;
1479   stats_.rtt = rtt_;
1480   stats_.local_candidate = local_candidate();
1481   stats_.remote_candidate = remote_candidate();
1482   stats_.key = this;
1483   stats_.state = state_;
1484   stats_.priority = priority();
1485   return stats_;
1486 }
1487 
MaybeUpdateLocalCandidate(ConnectionRequest * request,StunMessage * response)1488 void Connection::MaybeUpdateLocalCandidate(ConnectionRequest* request,
1489                                            StunMessage* response) {
1490   // RFC 5245
1491   // The agent checks the mapped address from the STUN response.  If the
1492   // transport address does not match any of the local candidates that the
1493   // agent knows about, the mapped address represents a new candidate -- a
1494   // peer reflexive candidate.
1495   const StunAddressAttribute* addr =
1496       response->GetAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
1497   if (!addr) {
1498     LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1499                     << "No MAPPED-ADDRESS or XOR-MAPPED-ADDRESS found in the "
1500                     << "stun response message";
1501     return;
1502   }
1503 
1504   for (size_t i = 0; i < port_->Candidates().size(); ++i) {
1505     if (port_->Candidates()[i].address() == addr->GetAddress()) {
1506       if (local_candidate_index_ != i) {
1507         LOG_J(LS_INFO, this) << "Updating local candidate type to srflx.";
1508         local_candidate_index_ = i;
1509         // SignalStateChange to force a re-sort in P2PTransportChannel as this
1510         // Connection's local candidate has changed.
1511         SignalStateChange(this);
1512       }
1513       return;
1514     }
1515   }
1516 
1517   // RFC 5245
1518   // Its priority is set equal to the value of the PRIORITY attribute
1519   // in the Binding request.
1520   const StunUInt32Attribute* priority_attr =
1521       request->msg()->GetUInt32(STUN_ATTR_PRIORITY);
1522   if (!priority_attr) {
1523     LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
1524                     << "No STUN_ATTR_PRIORITY found in the "
1525                     << "stun response message";
1526     return;
1527   }
1528   const uint32_t priority = priority_attr->value();
1529   std::string id = rtc::CreateRandomString(8);
1530 
1531   Candidate new_local_candidate;
1532   new_local_candidate.set_id(id);
1533   new_local_candidate.set_component(local_candidate().component());
1534   new_local_candidate.set_type(PRFLX_PORT_TYPE);
1535   new_local_candidate.set_protocol(local_candidate().protocol());
1536   new_local_candidate.set_address(addr->GetAddress());
1537   new_local_candidate.set_priority(priority);
1538   new_local_candidate.set_username(local_candidate().username());
1539   new_local_candidate.set_password(local_candidate().password());
1540   new_local_candidate.set_network_name(local_candidate().network_name());
1541   new_local_candidate.set_network_type(local_candidate().network_type());
1542   new_local_candidate.set_related_address(local_candidate().address());
1543   new_local_candidate.set_generation(local_candidate().generation());
1544   new_local_candidate.set_foundation(ComputeFoundation(
1545       PRFLX_PORT_TYPE, local_candidate().protocol(),
1546       local_candidate().relay_protocol(), local_candidate().address()));
1547   new_local_candidate.set_network_id(local_candidate().network_id());
1548   new_local_candidate.set_network_cost(local_candidate().network_cost());
1549 
1550   // Change the local candidate of this Connection to the new prflx candidate.
1551   LOG_J(LS_INFO, this) << "Updating local candidate type to prflx.";
1552   local_candidate_index_ = port_->AddPrflxCandidate(new_local_candidate);
1553 
1554   // SignalStateChange to force a re-sort in P2PTransportChannel as this
1555   // Connection's local candidate has changed.
1556   SignalStateChange(this);
1557 }
1558 
rtt_converged() const1559 bool Connection::rtt_converged() const {
1560   return rtt_samples_ > (RTT_RATIO + 1);
1561 }
1562 
missing_responses(int64_t now) const1563 bool Connection::missing_responses(int64_t now) const {
1564   if (pings_since_last_response_.empty()) {
1565     return false;
1566   }
1567 
1568   int64_t waiting = now - pings_since_last_response_[0].sent_time;
1569   return waiting > 2 * rtt();
1570 }
1571 
ProxyConnection(Port * port,size_t index,const Candidate & remote_candidate)1572 ProxyConnection::ProxyConnection(Port* port,
1573                                  size_t index,
1574                                  const Candidate& remote_candidate)
1575     : Connection(port, index, remote_candidate) {}
1576 
Send(const void * data,size_t size,const rtc::PacketOptions & options)1577 int ProxyConnection::Send(const void* data, size_t size,
1578                           const rtc::PacketOptions& options) {
1579   stats_.sent_total_packets++;
1580   int sent = port_->SendTo(data, size, remote_candidate_.address(),
1581                            options, true);
1582   if (sent <= 0) {
1583     RTC_DCHECK(sent < 0);
1584     error_ = port_->GetError();
1585     stats_.sent_discarded_packets++;
1586   } else {
1587     send_rate_tracker_.AddSamples(sent);
1588   }
1589   return sent;
1590 }
1591 
1592 }  // namespace cricket
1593