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