You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1159 lines
43 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright 2019 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. #include "p2p/base/connection.h"
  11. #include <math.h>
  12. #include <algorithm>
  13. #include <memory>
  14. #include <utility>
  15. #include <vector>
  16. #include "absl/algorithm/container.h"
  17. #include "absl/strings/match.h"
  18. #include "p2p/base/port_allocator.h"
  19. #include "rtc_base/checks.h"
  20. #include "rtc_base/crc32.h"
  21. #include "rtc_base/helpers.h"
  22. #include "rtc_base/logging.h"
  23. #include "rtc_base/mdns_responder_interface.h"
  24. #include "rtc_base/message_digest.h"
  25. #include "rtc_base/network.h"
  26. #include "rtc_base/numerics/safe_minmax.h"
  27. #include "rtc_base/string_encode.h"
  28. #include "rtc_base/string_utils.h"
  29. #include "rtc_base/third_party/base64/base64.h"
  30. #include "system_wrappers/include/field_trial.h"
  31. namespace {
  32. // Determines whether we have seen at least the given maximum number of
  33. // pings fail to have a response.
  34. inline bool TooManyFailures(
  35. const std::vector<cricket::Connection::SentPing>& pings_since_last_response,
  36. uint32_t maximum_failures,
  37. int rtt_estimate,
  38. int64_t now) {
  39. // If we haven't sent that many pings, then we can't have failed that many.
  40. if (pings_since_last_response.size() < maximum_failures)
  41. return false;
  42. // Check if the window in which we would expect a response to the ping has
  43. // already elapsed.
  44. int64_t expected_response_time =
  45. pings_since_last_response[maximum_failures - 1].sent_time + rtt_estimate;
  46. return now > expected_response_time;
  47. }
  48. // Determines whether we have gone too long without seeing any response.
  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. auto first = pings_since_last_response[0];
  56. return now > (first.sent_time + maximum_time);
  57. }
  58. // Helper methods for converting string values of log description fields to
  59. // enum.
  60. webrtc::IceCandidateType GetCandidateTypeByString(const std::string& type) {
  61. if (type == cricket::LOCAL_PORT_TYPE) {
  62. return webrtc::IceCandidateType::kLocal;
  63. } else if (type == cricket::STUN_PORT_TYPE) {
  64. return webrtc::IceCandidateType::kStun;
  65. } else if (type == cricket::PRFLX_PORT_TYPE) {
  66. return webrtc::IceCandidateType::kPrflx;
  67. } else if (type == cricket::RELAY_PORT_TYPE) {
  68. return webrtc::IceCandidateType::kRelay;
  69. }
  70. return webrtc::IceCandidateType::kUnknown;
  71. }
  72. webrtc::IceCandidatePairProtocol GetProtocolByString(
  73. const std::string& protocol) {
  74. if (protocol == cricket::UDP_PROTOCOL_NAME) {
  75. return webrtc::IceCandidatePairProtocol::kUdp;
  76. } else if (protocol == cricket::TCP_PROTOCOL_NAME) {
  77. return webrtc::IceCandidatePairProtocol::kTcp;
  78. } else if (protocol == cricket::SSLTCP_PROTOCOL_NAME) {
  79. return webrtc::IceCandidatePairProtocol::kSsltcp;
  80. } else if (protocol == cricket::TLS_PROTOCOL_NAME) {
  81. return webrtc::IceCandidatePairProtocol::kTls;
  82. }
  83. return webrtc::IceCandidatePairProtocol::kUnknown;
  84. }
  85. webrtc::IceCandidatePairAddressFamily GetAddressFamilyByInt(
  86. int address_family) {
  87. if (address_family == AF_INET) {
  88. return webrtc::IceCandidatePairAddressFamily::kIpv4;
  89. } else if (address_family == AF_INET6) {
  90. return webrtc::IceCandidatePairAddressFamily::kIpv6;
  91. }
  92. return webrtc::IceCandidatePairAddressFamily::kUnknown;
  93. }
  94. webrtc::IceCandidateNetworkType ConvertNetworkType(rtc::AdapterType type) {
  95. if (type == rtc::ADAPTER_TYPE_ETHERNET) {
  96. return webrtc::IceCandidateNetworkType::kEthernet;
  97. } else if (type == rtc::ADAPTER_TYPE_LOOPBACK) {
  98. return webrtc::IceCandidateNetworkType::kLoopback;
  99. } else if (type == rtc::ADAPTER_TYPE_WIFI) {
  100. return webrtc::IceCandidateNetworkType::kWifi;
  101. } else if (type == rtc::ADAPTER_TYPE_VPN) {
  102. return webrtc::IceCandidateNetworkType::kVpn;
  103. } else if (type == rtc::ADAPTER_TYPE_CELLULAR) {
  104. return webrtc::IceCandidateNetworkType::kCellular;
  105. }
  106. return webrtc::IceCandidateNetworkType::kUnknown;
  107. }
  108. // When we don't have any RTT data, we have to pick something reasonable. We
  109. // use a large value just in case the connection is really slow.
  110. const int DEFAULT_RTT = 3000; // 3 seconds
  111. // We will restrict RTT estimates (when used for determining state) to be
  112. // within a reasonable range.
  113. const int MINIMUM_RTT = 100; // 0.1 seconds
  114. const int MAXIMUM_RTT = 60000; // 60 seconds
  115. // Computes our estimate of the RTT given the current estimate.
  116. inline int ConservativeRTTEstimate(int rtt) {
  117. return rtc::SafeClamp(2 * rtt, MINIMUM_RTT, MAXIMUM_RTT);
  118. }
  119. // Weighting of the old rtt value to new data.
  120. const int RTT_RATIO = 3; // 3 : 1
  121. constexpr int64_t kMinExtraPingDelayMs = 100;
  122. } // namespace
  123. namespace cricket {
  124. // A ConnectionRequest is a simple STUN ping used to determine writability.
  125. ConnectionRequest::ConnectionRequest(Connection* connection)
  126. : StunRequest(new IceMessage()), connection_(connection) {}
  127. void ConnectionRequest::Prepare(StunMessage* request) {
  128. request->SetType(STUN_BINDING_REQUEST);
  129. std::string username;
  130. connection_->port()->CreateStunUsername(
  131. connection_->remote_candidate().username(), &username);
  132. // Note that the order of attributes does not impact the parsing on the
  133. // receiver side. The attribute is retrieved then by iterating and matching
  134. // over all parsed attributes. See StunMessage::GetAttribute.
  135. request->AddAttribute(
  136. std::make_unique<StunByteStringAttribute>(STUN_ATTR_USERNAME, username));
  137. // connection_ already holds this ping, so subtract one from count.
  138. if (connection_->port()->send_retransmit_count_attribute()) {
  139. request->AddAttribute(std::make_unique<StunUInt32Attribute>(
  140. STUN_ATTR_RETRANSMIT_COUNT,
  141. static_cast<uint32_t>(connection_->pings_since_last_response_.size() -
  142. 1)));
  143. }
  144. uint32_t network_info = connection_->port()->Network()->id();
  145. network_info = (network_info << 16) | connection_->port()->network_cost();
  146. request->AddAttribute(std::make_unique<StunUInt32Attribute>(
  147. STUN_ATTR_NETWORK_INFO, network_info));
  148. if (webrtc::field_trial::IsEnabled(
  149. "WebRTC-PiggybackIceCheckAcknowledgement") &&
  150. connection_->last_ping_id_received()) {
  151. request->AddAttribute(std::make_unique<StunByteStringAttribute>(
  152. STUN_ATTR_LAST_ICE_CHECK_RECEIVED,
  153. connection_->last_ping_id_received().value()));
  154. }
  155. // Adding ICE_CONTROLLED or ICE_CONTROLLING attribute based on the role.
  156. if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLING) {
  157. request->AddAttribute(std::make_unique<StunUInt64Attribute>(
  158. STUN_ATTR_ICE_CONTROLLING, connection_->port()->IceTiebreaker()));
  159. // We should have either USE_CANDIDATE attribute or ICE_NOMINATION
  160. // attribute but not both. That was enforced in p2ptransportchannel.
  161. if (connection_->use_candidate_attr()) {
  162. request->AddAttribute(
  163. std::make_unique<StunByteStringAttribute>(STUN_ATTR_USE_CANDIDATE));
  164. }
  165. if (connection_->nomination() &&
  166. connection_->nomination() != connection_->acked_nomination()) {
  167. request->AddAttribute(std::make_unique<StunUInt32Attribute>(
  168. STUN_ATTR_NOMINATION, connection_->nomination()));
  169. }
  170. } else if (connection_->port()->GetIceRole() == ICEROLE_CONTROLLED) {
  171. request->AddAttribute(std::make_unique<StunUInt64Attribute>(
  172. STUN_ATTR_ICE_CONTROLLED, connection_->port()->IceTiebreaker()));
  173. } else {
  174. RTC_NOTREACHED();
  175. }
  176. // Adding PRIORITY Attribute.
  177. // Changing the type preference to Peer Reflexive and local preference
  178. // and component id information is unchanged from the original priority.
  179. // priority = (2^24)*(type preference) +
  180. // (2^8)*(local preference) +
  181. // (2^0)*(256 - component ID)
  182. uint32_t type_preference =
  183. (connection_->local_candidate().protocol() == TCP_PROTOCOL_NAME)
  184. ? ICE_TYPE_PREFERENCE_PRFLX_TCP
  185. : ICE_TYPE_PREFERENCE_PRFLX;
  186. uint32_t prflx_priority =
  187. type_preference << 24 |
  188. (connection_->local_candidate().priority() & 0x00FFFFFF);
  189. request->AddAttribute(std::make_unique<StunUInt32Attribute>(
  190. STUN_ATTR_PRIORITY, prflx_priority));
  191. // Adding Message Integrity attribute.
  192. request->AddMessageIntegrity(connection_->remote_candidate().password());
  193. // Adding Fingerprint.
  194. request->AddFingerprint();
  195. }
  196. void ConnectionRequest::OnResponse(StunMessage* response) {
  197. connection_->OnConnectionRequestResponse(this, response);
  198. }
  199. void ConnectionRequest::OnErrorResponse(StunMessage* response) {
  200. connection_->OnConnectionRequestErrorResponse(this, response);
  201. }
  202. void ConnectionRequest::OnTimeout() {
  203. connection_->OnConnectionRequestTimeout(this);
  204. }
  205. void ConnectionRequest::OnSent() {
  206. connection_->OnConnectionRequestSent(this);
  207. // Each request is sent only once. After a single delay , the request will
  208. // time out.
  209. timeout_ = true;
  210. }
  211. int ConnectionRequest::resend_delay() {
  212. return CONNECTION_RESPONSE_TIMEOUT;
  213. }
  214. Connection::Connection(Port* port,
  215. size_t index,
  216. const Candidate& remote_candidate)
  217. : id_(rtc::CreateRandomId()),
  218. port_(port),
  219. local_candidate_index_(index),
  220. remote_candidate_(remote_candidate),
  221. recv_rate_tracker_(100, 10u),
  222. send_rate_tracker_(100, 10u),
  223. write_state_(STATE_WRITE_INIT),
  224. receiving_(false),
  225. connected_(true),
  226. pruned_(false),
  227. use_candidate_attr_(false),
  228. remote_ice_mode_(ICEMODE_FULL),
  229. requests_(port->thread()),
  230. rtt_(DEFAULT_RTT),
  231. last_ping_sent_(0),
  232. last_ping_received_(0),
  233. last_data_received_(0),
  234. last_ping_response_received_(0),
  235. reported_(false),
  236. state_(IceCandidatePairState::WAITING),
  237. time_created_ms_(rtc::TimeMillis()) {
  238. // All of our connections start in WAITING state.
  239. // TODO(mallinath) - Start connections from STATE_FROZEN.
  240. // Wire up to send stun packets
  241. requests_.SignalSendPacket.connect(this, &Connection::OnSendStunPacket);
  242. RTC_LOG(LS_INFO) << ToString() << ": Connection created";
  243. }
  244. Connection::~Connection() {}
  245. const Candidate& Connection::local_candidate() const {
  246. RTC_DCHECK(local_candidate_index_ < port_->Candidates().size());
  247. return port_->Candidates()[local_candidate_index_];
  248. }
  249. const Candidate& Connection::remote_candidate() const {
  250. return remote_candidate_;
  251. }
  252. uint64_t Connection::priority() const {
  253. uint64_t priority = 0;
  254. // RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs
  255. // Let G be the priority for the candidate provided by the controlling
  256. // agent. Let D be the priority for the candidate provided by the
  257. // controlled agent.
  258. // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
  259. IceRole role = port_->GetIceRole();
  260. if (role != ICEROLE_UNKNOWN) {
  261. uint32_t g = 0;
  262. uint32_t d = 0;
  263. if (role == ICEROLE_CONTROLLING) {
  264. g = local_candidate().priority();
  265. d = remote_candidate_.priority();
  266. } else {
  267. g = remote_candidate_.priority();
  268. d = local_candidate().priority();
  269. }
  270. priority = std::min(g, d);
  271. priority = priority << 32;
  272. priority += 2 * std::max(g, d) + (g > d ? 1 : 0);
  273. }
  274. return priority;
  275. }
  276. void Connection::set_write_state(WriteState value) {
  277. WriteState old_value = write_state_;
  278. write_state_ = value;
  279. if (value != old_value) {
  280. RTC_LOG(LS_VERBOSE) << ToString() << ": set_write_state from: " << old_value
  281. << " to " << value;
  282. SignalStateChange(this);
  283. }
  284. }
  285. void Connection::UpdateReceiving(int64_t now) {
  286. bool receiving;
  287. if (last_ping_sent() < last_ping_response_received()) {
  288. // We consider any candidate pair that has its last connectivity check
  289. // acknowledged by a response as receiving, particularly for backup
  290. // candidate pairs that send checks at a much slower pace than the selected
  291. // one. Otherwise, a backup candidate pair constantly becomes not receiving
  292. // as a side effect of a long ping interval, since we do not have a separate
  293. // receiving timeout for backup candidate pairs. See
  294. // IceConfig.ice_backup_candidate_pair_ping_interval,
  295. // IceConfig.ice_connection_receiving_timeout and their default value.
  296. receiving = true;
  297. } else {
  298. receiving =
  299. last_received() > 0 && now <= last_received() + receiving_timeout();
  300. }
  301. if (receiving_ == receiving) {
  302. return;
  303. }
  304. RTC_LOG(LS_VERBOSE) << ToString() << ": set_receiving to " << receiving;
  305. receiving_ = receiving;
  306. receiving_unchanged_since_ = now;
  307. SignalStateChange(this);
  308. }
  309. void Connection::set_state(IceCandidatePairState state) {
  310. IceCandidatePairState old_state = state_;
  311. state_ = state;
  312. if (state != old_state) {
  313. RTC_LOG(LS_VERBOSE) << ToString() << ": set_state";
  314. }
  315. }
  316. void Connection::set_connected(bool value) {
  317. bool old_value = connected_;
  318. connected_ = value;
  319. if (value != old_value) {
  320. RTC_LOG(LS_VERBOSE) << ToString() << ": Change connected_ to " << value;
  321. SignalStateChange(this);
  322. }
  323. }
  324. void Connection::set_use_candidate_attr(bool enable) {
  325. use_candidate_attr_ = enable;
  326. }
  327. int Connection::unwritable_timeout() const {
  328. return unwritable_timeout_.value_or(CONNECTION_WRITE_CONNECT_TIMEOUT);
  329. }
  330. int Connection::unwritable_min_checks() const {
  331. return unwritable_min_checks_.value_or(CONNECTION_WRITE_CONNECT_FAILURES);
  332. }
  333. int Connection::inactive_timeout() const {
  334. return inactive_timeout_.value_or(CONNECTION_WRITE_TIMEOUT);
  335. }
  336. int Connection::receiving_timeout() const {
  337. return receiving_timeout_.value_or(WEAK_CONNECTION_RECEIVE_TIMEOUT);
  338. }
  339. void Connection::OnSendStunPacket(const void* data,
  340. size_t size,
  341. StunRequest* req) {
  342. rtc::PacketOptions options(port_->StunDscpValue());
  343. options.info_signaled_after_sent.packet_type =
  344. rtc::PacketType::kIceConnectivityCheck;
  345. auto err =
  346. port_->SendTo(data, size, remote_candidate_.address(), options, false);
  347. if (err < 0) {
  348. RTC_LOG(LS_WARNING) << ToString()
  349. << ": Failed to send STUN ping "
  350. " err="
  351. << err << " id=" << rtc::hex_encode(req->id());
  352. }
  353. }
  354. void Connection::OnReadPacket(const char* data,
  355. size_t size,
  356. int64_t packet_time_us) {
  357. std::unique_ptr<IceMessage> msg;
  358. std::string remote_ufrag;
  359. const rtc::SocketAddress& addr(remote_candidate_.address());
  360. if (!port_->GetStunMessage(data, size, addr, &msg, &remote_ufrag)) {
  361. // The packet did not parse as a valid STUN message
  362. // This is a data packet, pass it along.
  363. last_data_received_ = rtc::TimeMillis();
  364. UpdateReceiving(last_data_received_);
  365. recv_rate_tracker_.AddSamples(size);
  366. SignalReadPacket(this, data, size, packet_time_us);
  367. // If timed out sending writability checks, start up again
  368. if (!pruned_ && (write_state_ == STATE_WRITE_TIMEOUT)) {
  369. RTC_LOG(LS_WARNING)
  370. << "Received a data packet on a timed-out Connection. "
  371. "Resetting state to STATE_WRITE_INIT.";
  372. set_write_state(STATE_WRITE_INIT);
  373. }
  374. } else if (!msg) {
  375. // The packet was STUN, but failed a check and was handled internally.
  376. } else {
  377. // The packet is STUN and passed the Port checks.
  378. // Perform our own checks to ensure this packet is valid.
  379. // If this is a STUN request, then update the receiving bit and respond.
  380. // If this is a STUN response, then update the writable bit.
  381. // Log at LS_INFO if we receive a ping on an unwritable connection.
  382. rtc::LoggingSeverity sev = (!writable() ? rtc::LS_INFO : rtc::LS_VERBOSE);
  383. switch (msg->type()) {
  384. case STUN_BINDING_REQUEST:
  385. RTC_LOG_V(sev) << ToString() << ": Received STUN ping, id="
  386. << rtc::hex_encode(msg->transaction_id());
  387. if (remote_ufrag == remote_candidate_.username()) {
  388. HandleBindingRequest(msg.get());
  389. } else {
  390. // The packet had the right local username, but the remote username
  391. // was not the right one for the remote address.
  392. RTC_LOG(LS_ERROR)
  393. << ToString()
  394. << ": Received STUN request with bad remote username "
  395. << remote_ufrag;
  396. port_->SendBindingErrorResponse(msg.get(), addr,
  397. STUN_ERROR_UNAUTHORIZED,
  398. STUN_ERROR_REASON_UNAUTHORIZED);
  399. }
  400. break;
  401. // Response from remote peer. Does it match request sent?
  402. // This doesn't just check, it makes callbacks if transaction
  403. // id's match.
  404. case STUN_BINDING_RESPONSE:
  405. case STUN_BINDING_ERROR_RESPONSE:
  406. if (msg->ValidateMessageIntegrity(data, size,
  407. remote_candidate().password())) {
  408. requests_.CheckResponse(msg.get());
  409. }
  410. // Otherwise silently discard the response message.
  411. break;
  412. // Remote end point sent an STUN indication instead of regular binding
  413. // request. In this case |last_ping_received_| will be updated but no
  414. // response will be sent.
  415. case STUN_BINDING_INDICATION:
  416. ReceivedPing(msg->transaction_id());
  417. break;
  418. default:
  419. RTC_NOTREACHED();
  420. break;
  421. }
  422. }
  423. }
  424. void Connection::HandleBindingRequest(IceMessage* msg) {
  425. // This connection should now be receiving.
  426. ReceivedPing(msg->transaction_id());
  427. if (webrtc::field_trial::IsEnabled("WebRTC-ExtraICEPing") &&
  428. last_ping_response_received_ == 0) {
  429. if (local_candidate().type() == RELAY_PORT_TYPE ||
  430. local_candidate().type() == PRFLX_PORT_TYPE ||
  431. remote_candidate().type() == RELAY_PORT_TYPE ||
  432. remote_candidate().type() == PRFLX_PORT_TYPE) {
  433. const int64_t now = rtc::TimeMillis();
  434. if (last_ping_sent_ + kMinExtraPingDelayMs <= now) {
  435. RTC_LOG(LS_INFO) << ToString()
  436. << "WebRTC-ExtraICEPing/Sending extra ping"
  437. << " last_ping_sent_: " << last_ping_sent_
  438. << " now: " << now
  439. << " (diff: " << (now - last_ping_sent_) << ")";
  440. Ping(now);
  441. } else {
  442. RTC_LOG(LS_INFO) << ToString()
  443. << "WebRTC-ExtraICEPing/Not sending extra ping"
  444. << " last_ping_sent_: " << last_ping_sent_
  445. << " now: " << now
  446. << " (diff: " << (now - last_ping_sent_) << ")";
  447. }
  448. }
  449. }
  450. const rtc::SocketAddress& remote_addr = remote_candidate_.address();
  451. const std::string& remote_ufrag = remote_candidate_.username();
  452. // Check for role conflicts.
  453. if (!port_->MaybeIceRoleConflict(remote_addr, msg, remote_ufrag)) {
  454. // Received conflicting role from the peer.
  455. RTC_LOG(LS_INFO) << "Received conflicting role from the peer.";
  456. return;
  457. }
  458. stats_.recv_ping_requests++;
  459. LogCandidatePairEvent(webrtc::IceCandidatePairEventType::kCheckReceived,
  460. msg->reduced_transaction_id());
  461. // This is a validated stun request from remote peer.
  462. port_->SendBindingResponse(msg, remote_addr);
  463. // If it timed out on writing check, start up again
  464. if (!pruned_ && write_state_ == STATE_WRITE_TIMEOUT) {
  465. set_write_state(STATE_WRITE_INIT);
  466. }
  467. if (port_->GetIceRole() == ICEROLE_CONTROLLED) {
  468. const StunUInt32Attribute* nomination_attr =
  469. msg->GetUInt32(STUN_ATTR_NOMINATION);
  470. uint32_t nomination = 0;
  471. if (nomination_attr) {
  472. nomination = nomination_attr->value();
  473. if (nomination == 0) {
  474. RTC_LOG(LS_ERROR) << "Invalid nomination: " << nomination;
  475. }
  476. } else {
  477. const StunByteStringAttribute* use_candidate_attr =
  478. msg->GetByteString(STUN_ATTR_USE_CANDIDATE);
  479. if (use_candidate_attr) {
  480. nomination = 1;
  481. }
  482. }
  483. // We don't un-nominate a connection, so we only keep a larger nomination.
  484. if (nomination > remote_nomination_) {
  485. set_remote_nomination(nomination);
  486. SignalNominated(this);
  487. }
  488. }
  489. // Set the remote cost if the network_info attribute is available.
  490. // Note: If packets are re-ordered, we may get incorrect network cost
  491. // temporarily, but it should get the correct value shortly after that.
  492. const StunUInt32Attribute* network_attr =
  493. msg->GetUInt32(STUN_ATTR_NETWORK_INFO);
  494. if (network_attr) {
  495. uint32_t network_info = network_attr->value();
  496. uint16_t network_cost = static_cast<uint16_t>(network_info);
  497. if (network_cost != remote_candidate_.network_cost()) {
  498. remote_candidate_.set_network_cost(network_cost);
  499. // Network cost change will affect the connection ranking, so signal
  500. // state change to force a re-sort in P2PTransportChannel.
  501. SignalStateChange(this);
  502. }
  503. }
  504. if (webrtc::field_trial::IsEnabled(
  505. "WebRTC-PiggybackIceCheckAcknowledgement")) {
  506. HandlePiggybackCheckAcknowledgementIfAny(msg);
  507. }
  508. }
  509. void Connection::OnReadyToSend() {
  510. SignalReadyToSend(this);
  511. }
  512. void Connection::Prune() {
  513. if (!pruned_ || active()) {
  514. RTC_LOG(LS_INFO) << ToString() << ": Connection pruned";
  515. pruned_ = true;
  516. requests_.Clear();
  517. set_write_state(STATE_WRITE_TIMEOUT);
  518. }
  519. }
  520. void Connection::Destroy() {
  521. // TODO(deadbeef, nisse): This may leak if an application closes a
  522. // PeerConnection and then quickly destroys the PeerConnectionFactory (along
  523. // with the networking thread on which this message is posted). Also affects
  524. // tests, with a workaround in
  525. // AutoSocketServerThread::~AutoSocketServerThread.
  526. RTC_LOG(LS_VERBOSE) << ToString() << ": Connection destroyed";
  527. port_->thread()->Post(RTC_FROM_HERE, this, MSG_DELETE);
  528. LogCandidatePairConfig(webrtc::IceCandidatePairConfigType::kDestroyed);
  529. }
  530. void Connection::FailAndDestroy() {
  531. set_state(IceCandidatePairState::FAILED);
  532. Destroy();
  533. }
  534. void Connection::FailAndPrune() {
  535. set_state(IceCandidatePairState::FAILED);
  536. Prune();
  537. }
  538. void Connection::PrintPingsSinceLastResponse(std::string* s, size_t max) {
  539. rtc::StringBuilder oss;
  540. if (pings_since_last_response_.size() > max) {
  541. for (size_t i = 0; i < max; i++) {
  542. const SentPing& ping = pings_since_last_response_[i];
  543. oss << rtc::hex_encode(ping.id) << " ";
  544. }
  545. oss << "... " << (pings_since_last_response_.size() - max) << " more";
  546. } else {
  547. for (const SentPing& ping : pings_since_last_response_) {
  548. oss << rtc::hex_encode(ping.id) << " ";
  549. }
  550. }
  551. *s = oss.str();
  552. }
  553. void Connection::UpdateState(int64_t now) {
  554. int rtt = ConservativeRTTEstimate(rtt_);
  555. if (RTC_LOG_CHECK_LEVEL(LS_VERBOSE)) {
  556. std::string pings;
  557. PrintPingsSinceLastResponse(&pings, 5);
  558. RTC_LOG(LS_VERBOSE) << ToString()
  559. << ": UpdateState()"
  560. ", ms since last received response="
  561. << now - last_ping_response_received_
  562. << ", ms since last received data="
  563. << now - last_data_received_ << ", rtt=" << rtt
  564. << ", pings_since_last_response=" << pings;
  565. }
  566. // Check the writable state. (The order of these checks is important.)
  567. //
  568. // Before becoming unwritable, we allow for a fixed number of pings to fail
  569. // (i.e., receive no response). We also have to give the response time to
  570. // get back, so we include a conservative estimate of this.
  571. //
  572. // Before timing out writability, we give a fixed amount of time. This is to
  573. // allow for changes in network conditions.
  574. if ((write_state_ == STATE_WRITABLE) &&
  575. TooManyFailures(pings_since_last_response_, unwritable_min_checks(), rtt,
  576. now) &&
  577. TooLongWithoutResponse(pings_since_last_response_, unwritable_timeout(),
  578. now)) {
  579. uint32_t max_pings = unwritable_min_checks();
  580. RTC_LOG(LS_INFO) << ToString() << ": Unwritable after " << max_pings
  581. << " ping failures and "
  582. << now - pings_since_last_response_[0].sent_time
  583. << " ms without a response,"
  584. " ms since last received ping="
  585. << now - last_ping_received_
  586. << " ms since last received data="
  587. << now - last_data_received_ << " rtt=" << rtt;
  588. set_write_state(STATE_WRITE_UNRELIABLE);
  589. }
  590. if ((write_state_ == STATE_WRITE_UNRELIABLE ||
  591. write_state_ == STATE_WRITE_INIT) &&
  592. TooLongWithoutResponse(pings_since_last_response_, inactive_timeout(),
  593. now)) {
  594. RTC_LOG(LS_INFO) << ToString() << ": Timed out after "
  595. << now - pings_since_last_response_[0].sent_time
  596. << " ms without a response, rtt=" << rtt;
  597. set_write_state(STATE_WRITE_TIMEOUT);
  598. }
  599. // Update the receiving state.
  600. UpdateReceiving(now);
  601. if (dead(now)) {
  602. Destroy();
  603. }
  604. }
  605. void Connection::Ping(int64_t now) {
  606. last_ping_sent_ = now;
  607. ConnectionRequest* req = new ConnectionRequest(this);
  608. // If not using renomination, we use "1" to mean "nominated" and "0" to mean
  609. // "not nominated". If using renomination, values greater than 1 are used for
  610. // re-nominated pairs.
  611. int nomination = use_candidate_attr_ ? 1 : 0;
  612. if (nomination_ > 0) {
  613. nomination = nomination_;
  614. }
  615. pings_since_last_response_.push_back(SentPing(req->id(), now, nomination));
  616. RTC_LOG(LS_VERBOSE) << ToString() << ": Sending STUN ping, id="
  617. << rtc::hex_encode(req->id())
  618. << ", nomination=" << nomination_;
  619. requests_.Send(req);
  620. state_ = IceCandidatePairState::IN_PROGRESS;
  621. num_pings_sent_++;
  622. }
  623. void Connection::ReceivedPing(const absl::optional<std::string>& request_id) {
  624. last_ping_received_ = rtc::TimeMillis();
  625. last_ping_id_received_ = request_id;
  626. UpdateReceiving(last_ping_received_);
  627. }
  628. void Connection::HandlePiggybackCheckAcknowledgementIfAny(StunMessage* msg) {
  629. RTC_DCHECK(msg->type() == STUN_BINDING_REQUEST);
  630. const StunByteStringAttribute* last_ice_check_received_attr =
  631. msg->GetByteString(STUN_ATTR_LAST_ICE_CHECK_RECEIVED);
  632. if (last_ice_check_received_attr) {
  633. const std::string request_id = last_ice_check_received_attr->GetString();
  634. auto iter = absl::c_find_if(
  635. pings_since_last_response_,
  636. [&request_id](const SentPing& ping) { return ping.id == request_id; });
  637. if (iter != pings_since_last_response_.end()) {
  638. rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
  639. RTC_LOG_V(sev) << ToString()
  640. << ": Received piggyback STUN ping response, id="
  641. << rtc::hex_encode(request_id);
  642. const int64_t rtt = rtc::TimeMillis() - iter->sent_time;
  643. ReceivedPingResponse(rtt, request_id, iter->nomination);
  644. }
  645. }
  646. }
  647. void Connection::ReceivedPingResponse(
  648. int rtt,
  649. const std::string& request_id,
  650. const absl::optional<uint32_t>& nomination) {
  651. RTC_DCHECK_GE(rtt, 0);
  652. // We've already validated that this is a STUN binding response with
  653. // the correct local and remote username for this connection.
  654. // So if we're not already, become writable. We may be bringing a pruned
  655. // connection back to life, but if we don't really want it, we can always
  656. // prune it again.
  657. if (nomination && nomination.value() > acked_nomination_) {
  658. acked_nomination_ = nomination.value();
  659. }
  660. total_round_trip_time_ms_ += rtt;
  661. current_round_trip_time_ms_ = static_cast<uint32_t>(rtt);
  662. pings_since_last_response_.clear();
  663. last_ping_response_received_ = rtc::TimeMillis();
  664. UpdateReceiving(last_ping_response_received_);
  665. set_write_state(STATE_WRITABLE);
  666. set_state(IceCandidatePairState::SUCCEEDED);
  667. if (rtt_samples_ > 0) {
  668. rtt_ = rtc::GetNextMovingAverage(rtt_, rtt, RTT_RATIO);
  669. } else {
  670. rtt_ = rtt;
  671. }
  672. rtt_samples_++;
  673. }
  674. bool Connection::dead(int64_t now) const {
  675. if (last_received() > 0) {
  676. // If it has ever received anything, we keep it alive until it hasn't
  677. // received anything for DEAD_CONNECTION_RECEIVE_TIMEOUT. This covers the
  678. // normal case of a successfully used connection that stops working. This
  679. // also allows a remote peer to continue pinging over a locally inactive
  680. // (pruned) connection.
  681. return (now > (last_received() + DEAD_CONNECTION_RECEIVE_TIMEOUT));
  682. }
  683. if (active()) {
  684. // If it has never received anything, keep it alive as long as it is
  685. // actively pinging and not pruned. Otherwise, the connection might be
  686. // deleted before it has a chance to ping. This is the normal case for a
  687. // new connection that is pinging but hasn't received anything yet.
  688. return false;
  689. }
  690. // If it has never received anything and is not actively pinging (pruned), we
  691. // keep it around for at least MIN_CONNECTION_LIFETIME to prevent connections
  692. // from being pruned too quickly during a network change event when two
  693. // networks would be up simultaneously but only for a brief period.
  694. return now > (time_created_ms_ + MIN_CONNECTION_LIFETIME);
  695. }
  696. bool Connection::stable(int64_t now) const {
  697. // A connection is stable if it's RTT has converged and it isn't missing any
  698. // responses. We should send pings at a higher rate until the RTT converges
  699. // and whenever a ping response is missing (so that we can detect
  700. // unwritability faster)
  701. return rtt_converged() && !missing_responses(now);
  702. }
  703. std::string Connection::ToDebugId() const {
  704. return rtc::ToHex(reinterpret_cast<uintptr_t>(this));
  705. }
  706. uint32_t Connection::ComputeNetworkCost() const {
  707. // TODO(honghaiz): Will add rtt as part of the network cost.
  708. return port()->network_cost() + remote_candidate_.network_cost();
  709. }
  710. std::string Connection::ToString() const {
  711. const absl::string_view CONNECT_STATE_ABBREV[2] = {
  712. "-", // not connected (false)
  713. "C", // connected (true)
  714. };
  715. const absl::string_view RECEIVE_STATE_ABBREV[2] = {
  716. "-", // not receiving (false)
  717. "R", // receiving (true)
  718. };
  719. const absl::string_view WRITE_STATE_ABBREV[4] = {
  720. "W", // STATE_WRITABLE
  721. "w", // STATE_WRITE_UNRELIABLE
  722. "-", // STATE_WRITE_INIT
  723. "x", // STATE_WRITE_TIMEOUT
  724. };
  725. const absl::string_view ICESTATE[4] = {
  726. "W", // STATE_WAITING
  727. "I", // STATE_INPROGRESS
  728. "S", // STATE_SUCCEEDED
  729. "F" // STATE_FAILED
  730. };
  731. const absl::string_view SELECTED_STATE_ABBREV[2] = {
  732. "-", // candidate pair not selected (false)
  733. "S", // selected (true)
  734. };
  735. const Candidate& local = local_candidate();
  736. const Candidate& remote = remote_candidate();
  737. rtc::StringBuilder ss;
  738. ss << "Conn[" << ToDebugId() << ":" << port_->content_name() << ":"
  739. << port_->Network()->ToString() << ":" << local.id() << ":"
  740. << local.component() << ":" << local.generation() << ":" << local.type()
  741. << ":" << local.protocol() << ":" << local.address().ToSensitiveString()
  742. << "->" << remote.id() << ":" << remote.component() << ":"
  743. << remote.priority() << ":" << remote.type() << ":" << remote.protocol()
  744. << ":" << remote.address().ToSensitiveString() << "|"
  745. << CONNECT_STATE_ABBREV[connected()] << RECEIVE_STATE_ABBREV[receiving()]
  746. << WRITE_STATE_ABBREV[write_state()] << ICESTATE[static_cast<int>(state())]
  747. << "|" << SELECTED_STATE_ABBREV[selected()] << "|" << remote_nomination()
  748. << "|" << nomination() << "|" << priority() << "|";
  749. if (rtt_ < DEFAULT_RTT) {
  750. ss << rtt_ << "]";
  751. } else {
  752. ss << "-]";
  753. }
  754. return ss.Release();
  755. }
  756. std::string Connection::ToSensitiveString() const {
  757. return ToString();
  758. }
  759. const webrtc::IceCandidatePairDescription& Connection::ToLogDescription() {
  760. if (log_description_.has_value()) {
  761. return log_description_.value();
  762. }
  763. const Candidate& local = local_candidate();
  764. const Candidate& remote = remote_candidate();
  765. const rtc::Network* network = port()->Network();
  766. log_description_ = webrtc::IceCandidatePairDescription();
  767. log_description_->local_candidate_type =
  768. GetCandidateTypeByString(local.type());
  769. log_description_->local_relay_protocol =
  770. GetProtocolByString(local.relay_protocol());
  771. log_description_->local_network_type = ConvertNetworkType(network->type());
  772. log_description_->local_address_family =
  773. GetAddressFamilyByInt(local.address().family());
  774. log_description_->remote_candidate_type =
  775. GetCandidateTypeByString(remote.type());
  776. log_description_->remote_address_family =
  777. GetAddressFamilyByInt(remote.address().family());
  778. log_description_->candidate_pair_protocol =
  779. GetProtocolByString(local.protocol());
  780. return log_description_.value();
  781. }
  782. void Connection::LogCandidatePairConfig(
  783. webrtc::IceCandidatePairConfigType type) {
  784. if (ice_event_log_ == nullptr) {
  785. return;
  786. }
  787. ice_event_log_->LogCandidatePairConfig(type, id(), ToLogDescription());
  788. }
  789. void Connection::LogCandidatePairEvent(webrtc::IceCandidatePairEventType type,
  790. uint32_t transaction_id) {
  791. if (ice_event_log_ == nullptr) {
  792. return;
  793. }
  794. ice_event_log_->LogCandidatePairEvent(type, id(), transaction_id);
  795. }
  796. void Connection::OnConnectionRequestResponse(ConnectionRequest* request,
  797. StunMessage* response) {
  798. // Log at LS_INFO if we receive a ping response on an unwritable
  799. // connection.
  800. rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
  801. int rtt = request->Elapsed();
  802. if (RTC_LOG_CHECK_LEVEL_V(sev)) {
  803. std::string pings;
  804. PrintPingsSinceLastResponse(&pings, 5);
  805. RTC_LOG_V(sev) << ToString() << ": Received STUN ping response, id="
  806. << rtc::hex_encode(request->id())
  807. << ", code=0" // Makes logging easier to parse.
  808. ", rtt="
  809. << rtt << ", pings_since_last_response=" << pings;
  810. }
  811. absl::optional<uint32_t> nomination;
  812. const std::string request_id = request->id();
  813. auto iter = absl::c_find_if(
  814. pings_since_last_response_,
  815. [&request_id](const SentPing& ping) { return ping.id == request_id; });
  816. if (iter != pings_since_last_response_.end()) {
  817. nomination.emplace(iter->nomination);
  818. }
  819. ReceivedPingResponse(rtt, request_id, nomination);
  820. stats_.recv_ping_responses++;
  821. LogCandidatePairEvent(
  822. webrtc::IceCandidatePairEventType::kCheckResponseReceived,
  823. response->reduced_transaction_id());
  824. MaybeUpdateLocalCandidate(request, response);
  825. }
  826. void Connection::OnConnectionRequestErrorResponse(ConnectionRequest* request,
  827. StunMessage* response) {
  828. int error_code = response->GetErrorCodeValue();
  829. RTC_LOG(LS_WARNING) << ToString() << ": Received STUN error response id="
  830. << rtc::hex_encode(request->id())
  831. << " code=" << error_code
  832. << " rtt=" << request->Elapsed();
  833. if (error_code == STUN_ERROR_UNKNOWN_ATTRIBUTE ||
  834. error_code == STUN_ERROR_SERVER_ERROR ||
  835. error_code == STUN_ERROR_UNAUTHORIZED) {
  836. // Recoverable error, retry
  837. } else if (error_code == STUN_ERROR_STALE_CREDENTIALS) {
  838. // Race failure, retry
  839. } else if (error_code == STUN_ERROR_ROLE_CONFLICT) {
  840. HandleRoleConflictFromPeer();
  841. } else {
  842. // This is not a valid connection.
  843. RTC_LOG(LS_ERROR) << ToString()
  844. << ": Received STUN error response, code=" << error_code
  845. << "; killing connection";
  846. FailAndDestroy();
  847. }
  848. }
  849. void Connection::OnConnectionRequestTimeout(ConnectionRequest* request) {
  850. // Log at LS_INFO if we miss a ping on a writable connection.
  851. rtc::LoggingSeverity sev = writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
  852. RTC_LOG_V(sev) << ToString() << ": Timing-out STUN ping "
  853. << rtc::hex_encode(request->id()) << " after "
  854. << request->Elapsed() << " ms";
  855. }
  856. void Connection::OnConnectionRequestSent(ConnectionRequest* request) {
  857. // Log at LS_INFO if we send a ping on an unwritable connection.
  858. rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE;
  859. RTC_LOG_V(sev) << ToString()
  860. << ": Sent STUN ping, id=" << rtc::hex_encode(request->id())
  861. << ", use_candidate=" << use_candidate_attr()
  862. << ", nomination=" << nomination();
  863. stats_.sent_ping_requests_total++;
  864. LogCandidatePairEvent(webrtc::IceCandidatePairEventType::kCheckSent,
  865. request->reduced_transaction_id());
  866. if (stats_.recv_ping_responses == 0) {
  867. stats_.sent_ping_requests_before_first_response++;
  868. }
  869. }
  870. void Connection::HandleRoleConflictFromPeer() {
  871. port_->SignalRoleConflict(port_);
  872. }
  873. void Connection::MaybeSetRemoteIceParametersAndGeneration(
  874. const IceParameters& ice_params,
  875. int generation) {
  876. if (remote_candidate_.username() == ice_params.ufrag &&
  877. remote_candidate_.password().empty()) {
  878. remote_candidate_.set_password(ice_params.pwd);
  879. }
  880. // TODO(deadbeef): A value of '0' for the generation is used for both
  881. // generation 0 and "generation unknown". It should be changed to an
  882. // absl::optional to fix this.
  883. if (remote_candidate_.username() == ice_params.ufrag &&
  884. remote_candidate_.password() == ice_params.pwd &&
  885. remote_candidate_.generation() == 0) {
  886. remote_candidate_.set_generation(generation);
  887. }
  888. }
  889. void Connection::MaybeUpdatePeerReflexiveCandidate(
  890. const Candidate& new_candidate) {
  891. if (remote_candidate_.type() == PRFLX_PORT_TYPE &&
  892. new_candidate.type() != PRFLX_PORT_TYPE &&
  893. remote_candidate_.protocol() == new_candidate.protocol() &&
  894. remote_candidate_.address() == new_candidate.address() &&
  895. remote_candidate_.username() == new_candidate.username() &&
  896. remote_candidate_.password() == new_candidate.password() &&
  897. remote_candidate_.generation() == new_candidate.generation()) {
  898. remote_candidate_ = new_candidate;
  899. }
  900. }
  901. void Connection::OnMessage(rtc::Message* pmsg) {
  902. RTC_DCHECK(pmsg->message_id == MSG_DELETE);
  903. RTC_LOG(LS_INFO) << "Connection deleted with number of pings sent: "
  904. << num_pings_sent_;
  905. SignalDestroyed(this);
  906. delete this;
  907. }
  908. int64_t Connection::last_received() const {
  909. return std::max(last_data_received_,
  910. std::max(last_ping_received_, last_ping_response_received_));
  911. }
  912. ConnectionInfo Connection::stats() {
  913. stats_.recv_bytes_second = round(recv_rate_tracker_.ComputeRate());
  914. stats_.recv_total_bytes = recv_rate_tracker_.TotalSampleCount();
  915. stats_.sent_bytes_second = round(send_rate_tracker_.ComputeRate());
  916. stats_.sent_total_bytes = send_rate_tracker_.TotalSampleCount();
  917. stats_.receiving = receiving_;
  918. stats_.writable = write_state_ == STATE_WRITABLE;
  919. stats_.timeout = write_state_ == STATE_WRITE_TIMEOUT;
  920. stats_.new_connection = !reported_;
  921. stats_.rtt = rtt_;
  922. stats_.key = this;
  923. stats_.state = state_;
  924. stats_.priority = priority();
  925. stats_.nominated = nominated();
  926. stats_.total_round_trip_time_ms = total_round_trip_time_ms_;
  927. stats_.current_round_trip_time_ms = current_round_trip_time_ms_;
  928. stats_.local_candidate = local_candidate();
  929. stats_.remote_candidate = remote_candidate();
  930. return stats_;
  931. }
  932. void Connection::MaybeUpdateLocalCandidate(ConnectionRequest* request,
  933. StunMessage* response) {
  934. // RFC 5245
  935. // The agent checks the mapped address from the STUN response. If the
  936. // transport address does not match any of the local candidates that the
  937. // agent knows about, the mapped address represents a new candidate -- a
  938. // peer reflexive candidate.
  939. const StunAddressAttribute* addr =
  940. response->GetAddress(STUN_ATTR_XOR_MAPPED_ADDRESS);
  941. if (!addr) {
  942. RTC_LOG(LS_WARNING)
  943. << "Connection::OnConnectionRequestResponse - "
  944. "No MAPPED-ADDRESS or XOR-MAPPED-ADDRESS found in the "
  945. "stun response message";
  946. return;
  947. }
  948. for (size_t i = 0; i < port_->Candidates().size(); ++i) {
  949. if (port_->Candidates()[i].address() == addr->GetAddress()) {
  950. if (local_candidate_index_ != i) {
  951. RTC_LOG(LS_INFO) << ToString()
  952. << ": Updating local candidate type to srflx.";
  953. local_candidate_index_ = i;
  954. // SignalStateChange to force a re-sort in P2PTransportChannel as this
  955. // Connection's local candidate has changed.
  956. SignalStateChange(this);
  957. }
  958. return;
  959. }
  960. }
  961. // RFC 5245
  962. // Its priority is set equal to the value of the PRIORITY attribute
  963. // in the Binding request.
  964. const StunUInt32Attribute* priority_attr =
  965. request->msg()->GetUInt32(STUN_ATTR_PRIORITY);
  966. if (!priority_attr) {
  967. RTC_LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - "
  968. "No STUN_ATTR_PRIORITY found in the "
  969. "stun response message";
  970. return;
  971. }
  972. const uint32_t priority = priority_attr->value();
  973. std::string id = rtc::CreateRandomString(8);
  974. Candidate new_local_candidate;
  975. new_local_candidate.set_id(id);
  976. new_local_candidate.set_component(local_candidate().component());
  977. new_local_candidate.set_type(PRFLX_PORT_TYPE);
  978. new_local_candidate.set_protocol(local_candidate().protocol());
  979. new_local_candidate.set_address(addr->GetAddress());
  980. new_local_candidate.set_priority(priority);
  981. new_local_candidate.set_username(local_candidate().username());
  982. new_local_candidate.set_password(local_candidate().password());
  983. new_local_candidate.set_network_name(local_candidate().network_name());
  984. new_local_candidate.set_network_type(local_candidate().network_type());
  985. new_local_candidate.set_related_address(local_candidate().address());
  986. new_local_candidate.set_generation(local_candidate().generation());
  987. new_local_candidate.set_foundation(Port::ComputeFoundation(
  988. PRFLX_PORT_TYPE, local_candidate().protocol(),
  989. local_candidate().relay_protocol(), local_candidate().address()));
  990. new_local_candidate.set_network_id(local_candidate().network_id());
  991. new_local_candidate.set_network_cost(local_candidate().network_cost());
  992. // Change the local candidate of this Connection to the new prflx candidate.
  993. RTC_LOG(LS_INFO) << ToString() << ": Updating local candidate type to prflx.";
  994. local_candidate_index_ = port_->AddPrflxCandidate(new_local_candidate);
  995. // SignalStateChange to force a re-sort in P2PTransportChannel as this
  996. // Connection's local candidate has changed.
  997. SignalStateChange(this);
  998. }
  999. bool Connection::rtt_converged() const {
  1000. return rtt_samples_ > (RTT_RATIO + 1);
  1001. }
  1002. bool Connection::missing_responses(int64_t now) const {
  1003. if (pings_since_last_response_.empty()) {
  1004. return false;
  1005. }
  1006. int64_t waiting = now - pings_since_last_response_[0].sent_time;
  1007. return waiting > 2 * rtt();
  1008. }
  1009. bool Connection::TooManyOutstandingPings(
  1010. const absl::optional<int>& max_outstanding_pings) const {
  1011. if (!max_outstanding_pings.has_value()) {
  1012. return false;
  1013. }
  1014. if (static_cast<int>(pings_since_last_response_.size()) <
  1015. *max_outstanding_pings) {
  1016. return false;
  1017. }
  1018. return true;
  1019. }
  1020. ProxyConnection::ProxyConnection(Port* port,
  1021. size_t index,
  1022. const Candidate& remote_candidate)
  1023. : Connection(port, index, remote_candidate) {}
  1024. int ProxyConnection::Send(const void* data,
  1025. size_t size,
  1026. const rtc::PacketOptions& options) {
  1027. stats_.sent_total_packets++;
  1028. int sent =
  1029. port_->SendTo(data, size, remote_candidate_.address(), options, true);
  1030. if (sent <= 0) {
  1031. RTC_DCHECK(sent < 0);
  1032. error_ = port_->GetError();
  1033. stats_.sent_discarded_packets++;
  1034. } else {
  1035. send_rate_tracker_.AddSamples(sent);
  1036. }
  1037. return sent;
  1038. }
  1039. int ProxyConnection::GetError() {
  1040. return error_;
  1041. }
  1042. } // namespace cricket