| 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 <cstdint> |
| 17 | #include <memory> |
| 18 | #include <utility> |
| 19 | #include <vector> |
| 20 |
| 21 | #include "absl/algorithm/container.h" |
| 22 | #include "absl/strings/string_view.h" |
| 23 | #include "absl/types/optional.h" |
| 24 | #include "api/array_view.h" |
| 25 | #include "api/units/timestamp.h" |
| 26 | #include "p2p/base/p2p_constants.h" |
| 27 | #include "rtc_base/byte_buffer.h" |
| 28 | #include "rtc_base/checks.h" |
| 29 | #include "rtc_base/helpers.h" |
| 30 | #include "rtc_base/logging.h" |
| 31 | #include "rtc_base/net_helper.h" |
| 32 | #include "rtc_base/network.h" |
| 33 | #include "rtc_base/network/sent_packet.h" |
| 34 | #include "rtc_base/network_constants.h" |
| 35 | #include "rtc_base/numerics/safe_minmax.h" |
| 36 | #include "rtc_base/socket.h" |
| 37 | #include "rtc_base/socket_address.h" |
| 38 | #include "rtc_base/string_encode.h" |
| 39 | #include "rtc_base/string_utils.h" |
| 40 | #include "rtc_base/strings/string_builder.h" |
| 41 | #include "rtc_base/time_utils.h" |
| 42 |
| 43 | namespace cricket { |
| 44 | namespace { |
| 45 |
| 46 | // Determines whether we have seen at least the given maximum number of |
| 47 | // pings fail to have a response. |
| 48 | inline bool TooManyFailures( |
| 49 | const std::vector<Connection::SentPing>& pings_since_last_response, |
| 50 | uint32_t maximum_failures, |
| 51 | int rtt_estimate, |
| 52 | int64_t now) { |
| 53 | // If we haven't sent that many pings, then we can't have failed that many. |
| 54 | if (pings_since_last_response.size() < maximum_failures) |
| 55 | return false; |
| 56 |
| 57 | // Check if the window in which we would expect a response to the ping has |
| 58 | // already elapsed. |
| 59 | int64_t expected_response_time = |
| 60 | pings_since_last_response[maximum_failures - 1].sent_time + rtt_estimate; |
| 61 | return now > expected_response_time; |
| 62 | } |
| 63 |
| 64 | // Determines whether we have gone too long without seeing any response. |
| 65 | inline bool TooLongWithoutResponse( |
| 66 | const std::vector<Connection::SentPing>& pings_since_last_response, |
| 67 | int64_t maximum_time, |
| 68 | int64_t now) { |
| 69 | if (pings_since_last_response.size() == 0) |
| 70 | return false; |
| 71 |
| 72 | auto first = pings_since_last_response[0]; |
| 73 | return now > (first.sent_time + maximum_time); |
| 74 | } |
| 75 |
| 76 | // Helper methods for converting string values of log description fields to |
| 77 | // enum. |
| 78 | webrtc::IceCandidateType GetRtcEventLogCandidateType(const Candidate& c) { |
| 79 | if (c.is_local()) { |
| 80 | return webrtc::IceCandidateType::kHost; |
| 81 | } else if (c.is_stun()) { |
| 82 | return webrtc::IceCandidateType::kSrflx; |
| 83 | } else if (c.is_prflx()) { |
| 84 | return webrtc::IceCandidateType::kPrflx; |
| 85 | } |
| 86 | RTC_DCHECK(c.is_relay()); |
| 87 | return webrtc::IceCandidateType::kRelay; |
| 88 | } |
| 89 |
| 90 | webrtc::IceCandidatePairProtocol GetProtocolByString( |
| 91 | absl::string_view protocol) { |
| 92 | if (protocol == UDP_PROTOCOL_NAME) { |
| 93 | return webrtc::IceCandidatePairProtocol::kUdp; |
| 94 | } else if (protocol == TCP_PROTOCOL_NAME) { |
| 95 | return webrtc::IceCandidatePairProtocol::kTcp; |
| 96 | } else if (protocol == SSLTCP_PROTOCOL_NAME) { |
| 97 | return webrtc::IceCandidatePairProtocol::kSsltcp; |
| 98 | } else if (protocol == TLS_PROTOCOL_NAME) { |
| 99 | return webrtc::IceCandidatePairProtocol::kTls; |
| 100 | } |
| 101 | return webrtc::IceCandidatePairProtocol::kUnknown; |
| 102 | } |
| 103 |
| 104 | webrtc::IceCandidatePairAddressFamily GetAddressFamilyByInt( |
| 105 | int address_family) { |
| 106 | if (address_family == AF_INET) { |
| 107 | return webrtc::IceCandidatePairAddressFamily::kIpv4; |
| 108 | } else if (address_family == AF_INET6) { |
| 109 | return webrtc::IceCandidatePairAddressFamily::kIpv6; |
| 110 | } |
| 111 | return webrtc::IceCandidatePairAddressFamily::kUnknown; |
| 112 | } |
| 113 |
| 114 | webrtc::IceCandidateNetworkType ConvertNetworkType(rtc::AdapterType type) { |
| 115 | switch (type) { |
| 116 | case rtc::ADAPTER_TYPE_ETHERNET: |
| 117 | return webrtc::IceCandidateNetworkType::kEthernet; |
| 118 | case rtc::ADAPTER_TYPE_LOOPBACK: |
| 119 | return webrtc::IceCandidateNetworkType::kLoopback; |
| 120 | case rtc::ADAPTER_TYPE_WIFI: |
| 121 | return webrtc::IceCandidateNetworkType::kWifi; |
| 122 | case rtc::ADAPTER_TYPE_VPN: |
| 123 | return webrtc::IceCandidateNetworkType::kVpn; |
| 124 | case rtc::ADAPTER_TYPE_CELLULAR: |
| 125 | case rtc::ADAPTER_TYPE_CELLULAR_2G: |
| 126 | case rtc::ADAPTER_TYPE_CELLULAR_3G: |
| 127 | case rtc::ADAPTER_TYPE_CELLULAR_4G: |
| 128 | case rtc::ADAPTER_TYPE_CELLULAR_5G: |
| 129 | return webrtc::IceCandidateNetworkType::kCellular; |
| 130 | default: |
| 131 | return webrtc::IceCandidateNetworkType::kUnknown; |
| 132 | } |
| 133 | } |
| 134 |
| 135 | // When we don't have any RTT data, we have to pick something reasonable. We |
| 136 | // use a large value just in case the connection is really slow. |
| 137 | const int DEFAULT_RTT = 3000; // 3 seconds |
| 138 |
| 139 | // We will restrict RTT estimates (when used for determining state) to be |
| 140 | // within a reasonable range. |
| 141 | const int MINIMUM_RTT = 100; // 0.1 seconds |
| 142 | const int MAXIMUM_RTT = 60000; // 60 seconds |
| 143 |
| 144 | const int DEFAULT_RTT_ESTIMATE_HALF_TIME_MS = 500; |
| 145 |
| 146 | // Computes our estimate of the RTT given the current estimate. |
| 147 | inline int ConservativeRTTEstimate(int rtt) { |
| 148 | return rtc::SafeClamp(2 * rtt, MINIMUM_RTT, MAXIMUM_RTT); |
| 149 | } |
| 150 |
| 151 | // Weighting of the old rtt value to new data. |
| 152 | const int RTT_RATIO = 3; // 3 : 1 |
| 153 |
| 154 | constexpr int64_t kMinExtraPingDelayMs = 100; |
| 155 |
| 156 | // Default field trials. |
| 157 | const IceFieldTrials kDefaultFieldTrials; |
| 158 |
| 159 | constexpr int kSupportGoogPingVersionRequestIndex = static_cast<int>( |
| 160 | IceGoogMiscInfoBindingRequestAttributeIndex::SUPPORT_GOOG_PING_VERSION); |
| 161 |
| 162 | constexpr int kSupportGoogPingVersionResponseIndex = static_cast<int>( |
| 163 | IceGoogMiscInfoBindingResponseAttributeIndex::SUPPORT_GOOG_PING_VERSION); |
| 164 |
| 165 | } // namespace |
| 166 |
| 167 | // A ConnectionRequest is a STUN binding used to determine writability. |
| 168 | class Connection::ConnectionRequest : public StunRequest { |
| 169 | public: |
| 170 | ConnectionRequest(StunRequestManager& manager, |
| 171 | Connection* connection, |
| 172 | std::unique_ptr<IceMessage> message); |
| 173 | void OnResponse(StunMessage* response) override; |
| 174 | void OnErrorResponse(StunMessage* response) override; |
| 175 | void OnTimeout() override; |
| 176 | void OnSent() override; |
| 177 | int resend_delay() override; |
| 178 |
| 179 | private: |
| 180 | Connection* const connection_; |
| 181 | }; |
| 182 |
| 183 | Connection::ConnectionRequest::ConnectionRequest( |
| 184 | StunRequestManager& manager, |
| 185 | Connection* connection, |
| 186 | std::unique_ptr<IceMessage> message) |
| 187 | : StunRequest(manager, std::move(message)), connection_(connection) {} |
| 188 |
| 189 | void Connection::ConnectionRequest::OnResponse(StunMessage* response) { |
| 190 | RTC_DCHECK_RUN_ON(connection_->network_thread_); |
| 191 | connection_->OnConnectionRequestResponse(this, response); |
| 192 | } |
| 193 |
| 194 | void Connection::ConnectionRequest::OnErrorResponse(StunMessage* response) { |
| 195 | RTC_DCHECK_RUN_ON(connection_->network_thread_); |
| 196 | connection_->OnConnectionRequestErrorResponse(this, response); |
| 197 | } |
| 198 |
| 199 | void Connection::ConnectionRequest::OnTimeout() { |
| 200 | RTC_DCHECK_RUN_ON(connection_->network_thread_); |
| 201 | connection_->OnConnectionRequestTimeout(this); |
| 202 | } |
| 203 |
| 204 | void Connection::ConnectionRequest::OnSent() { |
| 205 | RTC_DCHECK_RUN_ON(connection_->network_thread_); |
| 206 | connection_->OnConnectionRequestSent(this); |
| 207 | // Each request is sent only once. After a single delay , the request will |
| 208 | // time out. |
| 209 | set_timed_out(); |
| 210 | } |
| 211 |
| 212 | int Connection::ConnectionRequest::resend_delay() { |
| 213 | return CONNECTION_RESPONSE_TIMEOUT; |
| 214 | } |
| 215 |
| 216 | Connection::Connection(rtc::WeakPtr<PortInterface> port, |
| 217 | size_t index, |
| 218 | const Candidate& remote_candidate) |
| 219 | : network_thread_(port->thread()), |
| 220 | id_(rtc::CreateRandomId()), |
| 221 | port_(std::move(port)), |
| 222 | local_candidate_(port_->Candidates()[index]), |
| 223 | remote_candidate_(remote_candidate), |
| 224 | recv_rate_tracker_(100, 10u), |
| 225 | send_rate_tracker_(100, 10u), |
| 226 | write_state_(STATE_WRITE_INIT), |
| 227 | receiving_(false), |
| 228 | connected_(true), |
| 229 | pruned_(false), |
| 230 | use_candidate_attr_(false), |
| 231 | requests_(port_->thread(), |
| 232 | [this](const void* data, size_t size, StunRequest* request) { |
| 233 | OnSendStunPacket(data, size, request); |
| 234 | }), |
| 235 | rtt_(DEFAULT_RTT), |
| 236 | last_ping_sent_(0), |
| 237 | last_ping_received_(0), |
| 238 | last_data_received_(0), |
| 239 | last_ping_response_received_(0), |
| 240 | state_(IceCandidatePairState::WAITING), |
| 241 | time_created_ms_(rtc::TimeMillis()), |
| 242 | delta_internal_unix_epoch_ms_(rtc::TimeUTCMillis() - rtc::TimeMillis()), |
| 243 | field_trials_(&kDefaultFieldTrials), |
| 244 | rtt_estimate_(DEFAULT_RTT_ESTIMATE_HALF_TIME_MS) { |
| 245 | RTC_DCHECK_RUN_ON(network_thread_); |
| 246 | RTC_DCHECK(port_); |
| 247 | RTC_LOG(LS_INFO) << ToString() << ": Connection created"; |
| 248 | } |
| 249 |
| 250 | Connection::~Connection() { |
| 251 | RTC_DCHECK_RUN_ON(network_thread_); |
| 252 | RTC_DCHECK(!port_); |
| 253 | RTC_DCHECK(!received_packet_callback_); |
| 254 | } |
| 255 |
| 256 | webrtc::TaskQueueBase* Connection::network_thread() const { |
| 257 | return network_thread_; |
| 258 | } |
| 259 |
| 260 | const Candidate& Connection::local_candidate() const { |
| 261 | RTC_DCHECK_RUN_ON(network_thread_); |
| 262 | return local_candidate_; |
| 263 | } |
| 264 |
| 265 | const Candidate& Connection::remote_candidate() const { |
| 266 | return remote_candidate_; |
| 267 | } |
| 268 |
| 269 | const rtc::Network* Connection::network() const { |
| 270 | RTC_DCHECK(port_) << ToDebugId() << ": port_ null in network()"; |
| 271 | return port()->Network(); |
| 272 | } |
| 273 |
| 274 | int Connection::generation() const { |
| 275 | RTC_DCHECK(port_) << ToDebugId() << ": port_ null in generation()"; |
| 276 | return port()->generation(); |
| 277 | } |
| 278 |
| 279 | uint64_t Connection::priority() const { |
| 280 | RTC_DCHECK(port_) << ToDebugId() << ": port_ null in priority()"; |
| 281 | if (!port_) |
| 282 | return 0; |
| 283 |
| 284 | uint64_t priority = 0; |
| 285 | // RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs |
| 286 | // Let G be the priority for the candidate provided by the controlling |
| 287 | // agent. Let D be the priority for the candidate provided by the |
| 288 | // controlled agent. |
| 289 | // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0) |
| 290 | IceRole role = port_->GetIceRole(); |
| 291 | if (role != ICEROLE_UNKNOWN) { |
| 292 | uint32_t g = 0; |
| 293 | uint32_t d = 0; |
| 294 | if (role == ICEROLE_CONTROLLING) { |
| 295 | g = local_candidate().priority(); |
| 296 | d = remote_candidate_.priority(); |
| 297 | } else { |
| 298 | g = remote_candidate_.priority(); |
| 299 | d = local_candidate().priority(); |
| 300 | } |
| 301 | priority = std::min(g, d); |
| 302 | priority = priority << 32; |
| 303 | priority += 2 * std::max(g, d) + (g > d ? 1 : 0); |
| 304 | } |
| 305 | return priority; |
| 306 | } |
| 307 |
| 308 | void Connection::set_write_state(WriteState value) { |
| 309 | RTC_DCHECK_RUN_ON(network_thread_); |
| 310 | WriteState old_value = write_state_; |
| 311 | write_state_ = value; |
| 312 | if (value != old_value) { |
| 313 | RTC_LOG(LS_VERBOSE) << ToString() << ": set_write_state from: " << old_value |
| 314 | << " to " << value; |
| 315 | SignalStateChange(this); |
| 316 | } |
| 317 | } |
| 318 |
| 319 | void Connection::UpdateReceiving(int64_t now) { |
| 320 | RTC_DCHECK_RUN_ON(network_thread_); |
| 321 | bool receiving; |
| 322 | if (last_ping_sent() < last_ping_response_received()) { |
| 323 | // We consider any candidate pair that has its last connectivity check |
| 324 | // acknowledged by a response as receiving, particularly for backup |
| 325 | // candidate pairs that send checks at a much slower pace than the selected |
| 326 | // one. Otherwise, a backup candidate pair constantly becomes not receiving |
| 327 | // as a side effect of a long ping interval, since we do not have a separate |
| 328 | // receiving timeout for backup candidate pairs. See |
| 329 | // IceConfig.ice_backup_candidate_pair_ping_interval, |
| 330 | // IceConfig.ice_connection_receiving_timeout and their default value. |
| 331 | receiving = true; |
| 332 | } else { |
| 333 | receiving = |
| 334 | last_received() > 0 && now <= last_received() + receiving_timeout(); |
| 335 | } |
| 336 | if (receiving_ == receiving) { |
| 337 | return; |
| 338 | } |
| 339 | RTC_LOG(LS_VERBOSE) << ToString() << ": set_receiving to " << receiving; |
| 340 | receiving_ = receiving; |
| 341 | receiving_unchanged_since_ = now; |
| 342 | SignalStateChange(this); |
| 343 | } |
| 344 |
| 345 | void Connection::set_state(IceCandidatePairState state) { |
| 346 | RTC_DCHECK_RUN_ON(network_thread_); |
| 347 | IceCandidatePairState old_state = state_; |
| 348 | state_ = state; |
| 349 | if (state != old_state) { |
| 350 | RTC_LOG(LS_VERBOSE) << ToString() << ": set_state"; |
| 351 | } |
| 352 | } |
| 353 |
| 354 | void Connection::set_connected(bool value) { |
| 355 | RTC_DCHECK_RUN_ON(network_thread_); |
| 356 | bool old_value = connected_; |
| 357 | connected_ = value; |
| 358 | if (value != old_value) { |
| 359 | RTC_LOG(LS_VERBOSE) << ToString() << ": Change connected_ to " << value; |
| 360 | SignalStateChange(this); |
| 361 | } |
| 362 | } |
| 363 |
| 364 | bool Connection::use_candidate_attr() const { |
| 365 | RTC_DCHECK_RUN_ON(network_thread_); |
| 366 | return use_candidate_attr_; |
| 367 | } |
| 368 |
| 369 | void Connection::set_use_candidate_attr(bool enable) { |
| 370 | RTC_DCHECK_RUN_ON(network_thread_); |
| 371 | use_candidate_attr_ = enable; |
| 372 | } |
| 373 |
| 374 | void Connection::set_nomination(uint32_t value) { |
| 375 | RTC_DCHECK_RUN_ON(network_thread_); |
| 376 | nomination_ = value; |
| 377 | } |
| 378 |
| 379 | uint32_t Connection::remote_nomination() const { |
| 380 | RTC_DCHECK_RUN_ON(network_thread_); |
| 381 | return remote_nomination_; |
| 382 | } |
| 383 |
| 384 | bool Connection::nominated() const { |
| 385 | RTC_DCHECK_RUN_ON(network_thread_); |
| 386 | return acked_nomination_ || remote_nomination_; |
| 387 | } |
| 388 |
| 389 | int Connection::unwritable_timeout() const { |
| 390 | RTC_DCHECK_RUN_ON(network_thread_); |
| 391 | return unwritable_timeout_.value_or(CONNECTION_WRITE_CONNECT_TIMEOUT); |
| 392 | } |
| 393 |
| 394 | void Connection::set_unwritable_timeout(const absl::optional<int>& value_ms) { |
| 395 | RTC_DCHECK_RUN_ON(network_thread_); |
| 396 | unwritable_timeout_ = value_ms; |
| 397 | } |
| 398 |
| 399 | int Connection::unwritable_min_checks() const { |
| 400 | RTC_DCHECK_RUN_ON(network_thread_); |
| 401 | return unwritable_min_checks_.value_or(CONNECTION_WRITE_CONNECT_FAILURES); |
| 402 | } |
| 403 |
| 404 | void Connection::set_unwritable_min_checks(const absl::optional<int>& value) { |
| 405 | RTC_DCHECK_RUN_ON(network_thread_); |
| 406 | unwritable_min_checks_ = value; |
| 407 | } |
| 408 |
| 409 | int Connection::inactive_timeout() const { |
| 410 | RTC_DCHECK_RUN_ON(network_thread_); |
| 411 | return inactive_timeout_.value_or(CONNECTION_WRITE_TIMEOUT); |
| 412 | } |
| 413 |
| 414 | void Connection::set_inactive_timeout(const absl::optional<int>& value) { |
| 415 | RTC_DCHECK_RUN_ON(network_thread_); |
| 416 | inactive_timeout_ = value; |
| 417 | } |
| 418 |
| 419 | int Connection::receiving_timeout() const { |
| 420 | RTC_DCHECK_RUN_ON(network_thread_); |
| 421 | return receiving_timeout_.value_or(WEAK_CONNECTION_RECEIVE_TIMEOUT); |
| 422 | } |
| 423 |
| 424 | void Connection::set_receiving_timeout( |
| 425 | absl::optional<int> receiving_timeout_ms) { |
| 426 | RTC_DCHECK_RUN_ON(network_thread_); |
| 427 | receiving_timeout_ = receiving_timeout_ms; |
| 428 | } |
| 429 |
| 430 | void Connection::SetIceFieldTrials(const IceFieldTrials* field_trials) { |
| 431 | RTC_DCHECK_RUN_ON(network_thread_); |
| 432 | field_trials_ = field_trials; |
| 433 | rtt_estimate_.SetHalfTime(field_trials->rtt_estimate_halftime_ms); |
| 434 | } |
| 435 |
| 436 | void Connection::OnSendStunPacket(const void* data, |
| 437 | size_t size, |
| 438 | StunRequest* req) { |
| 439 | RTC_DCHECK_RUN_ON(network_thread_); |
| 440 | rtc::PacketOptions options(port_->StunDscpValue()); |
| 441 | options.info_signaled_after_sent.packet_type = |
| 442 | rtc::PacketType::kIceConnectivityCheck; |
| 443 | auto err = |
| 444 | port_->SendTo(data, size, remote_candidate_.address(), options, false); |
| 445 | if (err < 0) { |
| 446 | RTC_LOG(LS_WARNING) << ToString() |
| 447 | << ": Failed to send STUN ping " |
| 448 | " err=" |
| 449 | << err << " id=" << rtc::hex_encode(req->id()); |
| 450 | } |
| 451 | } |
| 452 |
| 453 | void Connection::RegisterReceivedPacketCallback( |
| 454 | absl::AnyInvocable<void(Connection*, const rtc::ReceivedPacket&)> |
| 455 | received_packet_callback) { |
| 456 | RTC_DCHECK_RUN_ON(network_thread_); |
| 457 | RTC_CHECK(!received_packet_callback_); |
| 458 | received_packet_callback_ = std::move(received_packet_callback); |
| 459 | } |
| 460 |
| 461 | void Connection::DeregisterReceivedPacketCallback() { |
| 462 | RTC_DCHECK_RUN_ON(network_thread_); |
| 463 | received_packet_callback_ = nullptr; |
| 464 | } |
| 465 |
| 466 | void Connection::OnReadPacket(const char* data, |
| 467 | size_t size, |
| 468 | int64_t packet_time_us) { |
| 469 | OnReadPacket( |
| 470 | rtc::ReceivedPacket::CreateFromLegacy(data, size, packet_time_us)); |
| 471 | } |
| 472 | void Connection::OnReadPacket(const rtc::ReceivedPacket& packet) { |
| 473 | RTC_DCHECK_RUN_ON(network_thread_); |
| 474 | std::unique_ptr<IceMessage> msg; |
| 475 | std::string remote_ufrag; |
| 476 | const rtc::SocketAddress& addr(remote_candidate_.address()); |
| 477 | if (!port_->GetStunMessage( |
| 478 | reinterpret_cast<const char*>(packet.payload().data()), |
| 479 | packet.payload().size(), addr, &msg, &remote_ufrag)) { |
| 480 | // The packet did not parse as a valid STUN message |
| 481 | // This is a data packet, pass it along. |
| 482 | last_data_received_ = rtc::TimeMillis(); |
| 483 | UpdateReceiving(last_data_received_); |
| 484 | recv_rate_tracker_.AddSamples(packet.payload().size()); |
| 485 | stats_.packets_received++; |
| 486 | if (received_packet_callback_) { |
| 487 | received_packet_callback_(this, packet); |
| 488 | } |
| 489 | // If timed out sending writability checks, start up again |
| 490 | if (!pruned_ && (write_state_ == STATE_WRITE_TIMEOUT)) { |
| 491 | RTC_LOG(LS_WARNING) |
| 492 | << "Received a data packet on a timed-out Connection. " |
| 493 | "Resetting state to STATE_WRITE_INIT."; |
| 494 | set_write_state(STATE_WRITE_INIT); |
| 495 | } |
| 496 | return; |
| 497 | } else if (!msg) { |
| 498 | // The packet was STUN, but failed a check and was handled internally. |
| 499 | return; |
| 500 | } |
| 501 |
| 502 | // The packet is STUN and passed the Port checks. |
| 503 | // Perform our own checks to ensure this packet is valid. |
| 504 | // If this is a STUN request, then update the receiving bit and respond. |
| 505 | // If this is a STUN response, then update the writable bit. |
| 506 | // Log at LS_INFO if we receive a ping on an unwritable connection. |
| 507 |
| 508 | // REQUESTs have msg->integrity() already checked in Port |
| 509 | // RESPONSEs have msg->integrity() checked below. |
| 510 | // INDICATION does not have any integrity. |
| 511 | if (IsStunRequestType(msg->type())) { |
| 512 | if (msg->integrity() != StunMessage::IntegrityStatus::kIntegrityOk) { |
| 513 | // "silently" discard the request. |
| 514 | RTC_LOG(LS_VERBOSE) << ToString() << ": Discarding " |
| 515 | << StunMethodToString(msg->type()) |
| 516 | << ", id=" << rtc::hex_encode(msg->transaction_id()) |
| 517 | << " with invalid message integrity: " |
| 518 | << static_cast<int>(msg->integrity()); |
| 519 | return; |
| 520 | } |
| 521 | // fall-through |
| 522 | } else if (IsStunSuccessResponseType(msg->type()) || |
| 523 | IsStunErrorResponseType(msg->type())) { |
| 524 | RTC_DCHECK(msg->integrity() == StunMessage::IntegrityStatus::kNotSet); |
| 525 | if (msg->ValidateMessageIntegrity(remote_candidate().password()) != |
| 526 | StunMessage::IntegrityStatus::kIntegrityOk) { |
| 527 | // "silently" discard the response. |
| 528 | RTC_LOG(LS_VERBOSE) << ToString() << ": Discarding " |
| 529 | << StunMethodToString(msg->type()) |
| 530 | << ", id=" << rtc::hex_encode(msg->transaction_id()) |
| 531 | << " with invalid message integrity: " |
| 532 | << static_cast<int>(msg->integrity()); |
| 533 | return; |
| 534 | } |
| 535 | } else { |
| 536 | RTC_DCHECK(IsStunIndicationType(msg->type())); |
| 537 | // No message integrity. |
| 538 | } |
| 539 |
| 540 | rtc::LoggingSeverity sev = (!writable() ? rtc::LS_INFO : rtc::LS_VERBOSE); |
| 541 | switch (msg->type()) { |
| 542 | case STUN_BINDING_REQUEST: |
| 543 | RTC_LOG_V(sev) << ToString() << ": Received " |
| 544 | << StunMethodToString(msg->type()) |
| 545 | << ", id=" << rtc::hex_encode(msg->transaction_id()); |
| 546 | if (remote_ufrag == remote_candidate_.username()) { |
| 547 | HandleStunBindingOrGoogPingRequest(msg.get()); |
| 548 | } else { |
| 549 | // The packet had the right local username, but the remote username |
| 550 | // was not the right one for the remote address. |
| 551 | RTC_LOG(LS_ERROR) << ToString() |
| 552 | << ": Received STUN request with bad remote username " |
| 553 | << remote_ufrag; |
| 554 | port_->SendBindingErrorResponse(msg.get(), addr, |
| 555 | STUN_ERROR_UNAUTHORIZED, |
| 556 | STUN_ERROR_REASON_UNAUTHORIZED); |
| 557 | } |
| 558 | break; |
| 559 |
| 560 | // Response from remote peer. Does it match request sent? |
| 561 | // This doesn't just check, it makes callbacks if transaction |
| 562 | // id's match. |
| 563 | case STUN_BINDING_RESPONSE: |
| 564 | case STUN_BINDING_ERROR_RESPONSE: |
| 565 | requests_.CheckResponse(msg.get()); |
| 566 | break; |
| 567 |
| 568 | // Remote end point sent an STUN indication instead of regular binding |
| 569 | // request. In this case `last_ping_received_` will be updated but no |
| 570 | // response will be sent. |
| 571 | case STUN_BINDING_INDICATION: |
| 572 | ReceivedPing(msg->transaction_id()); |
| 573 | break; |
| 574 | case GOOG_PING_REQUEST: |
| 575 | // Checked in Port::GetStunMessage. |
| 576 | HandleStunBindingOrGoogPingRequest(msg.get()); |
| 577 | break; |
| 578 | case GOOG_PING_RESPONSE: |
| 579 | case GOOG_PING_ERROR_RESPONSE: |
| 580 | requests_.CheckResponse(msg.get()); |
| 581 | break; |
| 582 | default: |
| 583 | RTC_DCHECK_NOTREACHED(); |
| 584 | break; |
| 585 | } |
| 586 | } |
| 587 |
| 588 | void Connection::HandleStunBindingOrGoogPingRequest(IceMessage* msg) { |
| 589 | RTC_DCHECK_RUN_ON(network_thread_); |
| 590 | // This connection should now be receiving. |
| 591 | ReceivedPing(msg->transaction_id()); |
| 592 | if (field_trials_->extra_ice_ping && last_ping_response_received_ == 0) { |
| 593 | if (local_candidate().is_relay() || local_candidate().is_prflx() || |
| 594 | remote_candidate().is_relay() || remote_candidate().is_prflx()) { |
| 595 | const int64_t now = rtc::TimeMillis(); |
| 596 | if (last_ping_sent_ + kMinExtraPingDelayMs <= now) { |
| 597 | RTC_LOG(LS_INFO) << ToString() |
| 598 | << "WebRTC-ExtraICEPing/Sending extra ping" |
| 599 | " last_ping_sent_: " |
| 600 | << last_ping_sent_ << " now: " << now |
| 601 | << " (diff: " << (now - last_ping_sent_) << ")"; |
| 602 | Ping(now); |
| 603 | } else { |
| 604 | RTC_LOG(LS_INFO) << ToString() |
| 605 | << "WebRTC-ExtraICEPing/Not sending extra ping" |
| 606 | " last_ping_sent_: " |
| 607 | << last_ping_sent_ << " now: " << now |
| 608 | << " (diff: " << (now - last_ping_sent_) << ")"; |
| 609 | } |
| 610 | } |
| 611 | } |
| 612 |
| 613 | const rtc::SocketAddress& remote_addr = remote_candidate_.address(); |
| 614 | if (msg->type() == STUN_BINDING_REQUEST) { |
| 615 | // Check for role conflicts. |
| 616 | const std::string& remote_ufrag = remote_candidate_.username(); |
| 617 | if (!port_->MaybeIceRoleConflict(remote_addr, msg, remote_ufrag)) { |
| 618 | // Received conflicting role from the peer. |
| 619 | RTC_LOG(LS_INFO) << "Received conflicting role from the peer."; |
| 620 | return; |
| 621 | } |
| 622 | } |
| 623 |
| 624 | stats_.recv_ping_requests++; |
| 625 | LogCandidatePairEvent(webrtc::IceCandidatePairEventType::kCheckReceived, |
| 626 | msg->reduced_transaction_id()); |
| 627 |
| 628 | // This is a validated stun request from remote peer. |
| 629 | if (msg->type() == STUN_BINDING_REQUEST) { |
| 630 | SendStunBindingResponse(msg); |
| 631 | } else { |
| 632 | RTC_DCHECK(msg->type() == GOOG_PING_REQUEST); |
| 633 | SendGoogPingResponse(msg); |
| 634 | } |
| 635 |
| 636 | // If it timed out on writing check, start up again |
| 637 | if (!pruned_ && write_state_ == STATE_WRITE_TIMEOUT) { |
| 638 | set_write_state(STATE_WRITE_INIT); |
| 639 | } |
| 640 |
| 641 | if (port_->GetIceRole() == ICEROLE_CONTROLLED) { |
| 642 | const StunUInt32Attribute* nomination_attr = |
| 643 | msg->GetUInt32(STUN_ATTR_NOMINATION); |
| 644 | uint32_t nomination = 0; |
| 645 | if (nomination_attr) { |
| 646 | nomination = nomination_attr->value(); |
| 647 | if (nomination == 0) { |
| 648 | RTC_LOG(LS_ERROR) << "Invalid nomination: " << nomination; |
| 649 | } |
| 650 | } else { |
| 651 | const StunByteStringAttribute* use_candidate_attr = |
| 652 | msg->GetByteString(STUN_ATTR_USE_CANDIDATE); |
| 653 | if (use_candidate_attr) { |
| 654 | nomination = 1; |
| 655 | } |
| 656 | } |
| 657 | // We don't un-nominate a connection, so we only keep a larger nomination. |
| 658 | if (nomination > remote_nomination_) { |
| 659 | set_remote_nomination(nomination); |
| 660 | SignalNominated(this); |
| 661 | } |
| 662 | } |
| 663 | // Set the remote cost if the network_info attribute is available. |
| 664 | // Note: If packets are re-ordered, we may get incorrect network cost |
| 665 | // temporarily, but it should get the correct value shortly after that. |
| 666 | const StunUInt32Attribute* network_attr = |
| 667 | msg->GetUInt32(STUN_ATTR_GOOG_NETWORK_INFO); |
| 668 | if (network_attr) { |
| 669 | uint32_t network_info = network_attr->value(); |
| 670 | uint16_t network_cost = static_cast<uint16_t>(network_info); |
| 671 | if (network_cost != remote_candidate_.network_cost()) { |
| 672 | remote_candidate_.set_network_cost(network_cost); |
| 673 | // Network cost change will affect the connection ranking, so signal |
| 674 | // state change to force a re-sort in P2PTransportChannel. |
| 675 | SignalStateChange(this); |
| 676 | } |
| 677 | } |
| 678 |
| 679 | if (field_trials_->piggyback_ice_check_acknowledgement) { |
| 680 | HandlePiggybackCheckAcknowledgementIfAny(msg); |
| 681 | } |
| 682 | } |
| 683 |
| 684 | void Connection::SendStunBindingResponse(const StunMessage* message) { |
| 685 | RTC_DCHECK_RUN_ON(network_thread_); |
| 686 | RTC_DCHECK_EQ(message->type(), STUN_BINDING_REQUEST); |
| 687 |
| 688 | // Retrieve the username from the `message`. |
| 689 | const StunByteStringAttribute* username_attr = |
| 690 | message->GetByteString(STUN_ATTR_USERNAME); |
| 691 | RTC_DCHECK(username_attr != NULL); |
| 692 | if (username_attr == NULL) { |
| 693 | // No valid username, skip the response. |
| 694 | return; |
| 695 | } |
| 696 |
| 697 | // Fill in the response. |
| 698 | StunMessage response(STUN_BINDING_RESPONSE, message->transaction_id()); |
| 699 | const StunUInt32Attribute* retransmit_attr = |
| 700 | message->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT); |
| 701 | if (retransmit_attr) { |
| 702 | // Inherit the incoming retransmit value in the response so the other side |
| 703 | // can see our view of lost pings. |
| 704 | response.AddAttribute(std::make_unique<StunUInt32Attribute>( |
| 705 | STUN_ATTR_RETRANSMIT_COUNT, retransmit_attr->value())); |
| 706 |
| 707 | if (retransmit_attr->value() > CONNECTION_WRITE_CONNECT_FAILURES) { |
| 708 | RTC_LOG(LS_INFO) |
| 709 | << ToString() |
| 710 | << ": Received a remote ping with high retransmit count: " |
| 711 | << retransmit_attr->value(); |
| 712 | } |
| 713 | } |
| 714 |
| 715 | response.AddAttribute(std::make_unique<StunXorAddressAttribute>( |
| 716 | STUN_ATTR_XOR_MAPPED_ADDRESS, remote_candidate_.address())); |
| 717 |
| 718 | if (field_trials_->announce_goog_ping) { |
| 719 | // Check if message contains a announce-request. |
| 720 | auto goog_misc = message->GetUInt16List(STUN_ATTR_GOOG_MISC_INFO); |
| 721 | if (goog_misc != nullptr && |
| 722 | goog_misc->Size() >= kSupportGoogPingVersionRequestIndex && |
| 723 | // Which version can we handle...currently any >= 1 |
| 724 | goog_misc->GetType(kSupportGoogPingVersionRequestIndex) >= 1) { |
| 725 | auto list = |
| 726 | StunAttribute::CreateUInt16ListAttribute(STUN_ATTR_GOOG_MISC_INFO); |
| 727 | list->AddTypeAtIndex(kSupportGoogPingVersionResponseIndex, |
| 728 | kGoogPingVersion); |
| 729 | response.AddAttribute(std::move(list)); |
| 730 | } |
| 731 | } |
| 732 |
| 733 | const StunByteStringAttribute* delta = |
| 734 | message->GetByteString(STUN_ATTR_GOOG_DELTA); |
| 735 | if (delta) { |
| 736 | if (field_trials_->answer_goog_delta && goog_delta_consumer_) { |
| 737 | auto ack = (*goog_delta_consumer_)(delta); |
| 738 | if (ack) { |
| 739 | RTC_LOG(LS_INFO) << "Sending GOOG_DELTA_ACK" |
| 740 | << " delta len: " << delta->length(); |
| 741 | response.AddAttribute(std::move(ack)); |
| 742 | } else { |
| 743 | RTC_LOG(LS_ERROR) << "GOOG_DELTA consumer did not return ack!"; |
| 744 | } |
| 745 | } else { |
| 746 | RTC_LOG(LS_WARNING) << "Ignore GOOG_DELTA" |
| 747 | << " len: " << delta->length() |
| 748 | << " answer_goog_delta = " |
| 749 | << field_trials_->answer_goog_delta |
| 750 | << " goog_delta_consumer_ = " |
| 751 | << goog_delta_consumer_.has_value(); |
| 752 | } |
| 753 | } |
| 754 |
| 755 | response.AddMessageIntegrity(local_candidate().password()); |
| 756 | response.AddFingerprint(); |
| 757 |
| 758 | SendResponseMessage(response); |
| 759 | } |
| 760 |
| 761 | void Connection::SendGoogPingResponse(const StunMessage* message) { |
| 762 | RTC_DCHECK_RUN_ON(network_thread_); |
| 763 | RTC_DCHECK(message->type() == GOOG_PING_REQUEST); |
| 764 |
| 765 | // Fill in the response. |
| 766 | StunMessage response(GOOG_PING_RESPONSE, message->transaction_id()); |
| 767 | response.AddMessageIntegrity32(local_candidate().password()); |
| 768 | SendResponseMessage(response); |
| 769 | } |
| 770 |
| 771 | void Connection::SendResponseMessage(const StunMessage& response) { |
| 772 | RTC_DCHECK_RUN_ON(network_thread_); |
| 773 | // Where I send the response. |
| 774 | const rtc::SocketAddress& addr = remote_candidate_.address(); |
| 775 |
| 776 | // Send the response. |
| 777 | rtc::ByteBufferWriter buf; |
| 778 | response.Write(&buf); |
| 779 | rtc::PacketOptions options(port_->StunDscpValue()); |
| 780 | options.info_signaled_after_sent.packet_type = |
| 781 | rtc::PacketType::kIceConnectivityCheckResponse; |
| 782 | auto err = port_->SendTo(buf.Data(), buf.Length(), addr, options, false); |
| 783 | if (err < 0) { |
| 784 | RTC_LOG(LS_ERROR) << ToString() << ": Failed to send " |
| 785 | << StunMethodToString(response.type()) |
| 786 | << ", to=" << addr.ToSensitiveString() << ", err=" << err |
| 787 | << ", id=" << rtc::hex_encode(response.transaction_id()); |
| 788 | } else { |
| 789 | // Log at LS_INFO if we send a stun ping response on an unwritable |
| 790 | // connection. |
| 791 | rtc::LoggingSeverity sev = (!writable()) ? rtc::LS_INFO : rtc::LS_VERBOSE; |
| 792 | RTC_LOG_V(sev) << ToString() << ": Sent " |
| 793 | << StunMethodToString(response.type()) |
| 794 | << ", to=" << addr.ToSensitiveString() |
| 795 | << ", id=" << rtc::hex_encode(response.transaction_id()); |
| 796 |
| 797 | stats_.sent_ping_responses++; |
| 798 | LogCandidatePairEvent(webrtc::IceCandidatePairEventType::kCheckResponseSent, |
| 799 | response.reduced_transaction_id()); |
| 800 | } |
| 801 | } |
| 802 |
| 803 | uint32_t Connection::acked_nomination() const { |
| 804 | RTC_DCHECK_RUN_ON(network_thread_); |
| 805 | return acked_nomination_; |
| 806 | } |
| 807 |
| 808 | void Connection::set_remote_nomination(uint32_t remote_nomination) { |
| 809 | RTC_DCHECK_RUN_ON(network_thread_); |
| 810 | remote_nomination_ = remote_nomination; |
| 811 | } |
| 812 |
| 813 | void Connection::OnReadyToSend() { |
| 814 | RTC_DCHECK_RUN_ON(network_thread_); |
| 815 | SignalReadyToSend(this); |
| 816 | } |
| 817 |
| 818 | bool Connection::pruned() const { |
| 819 | RTC_DCHECK_RUN_ON(network_thread_); |
| 820 | return pruned_; |
| 821 | } |
| 822 |
| 823 | void Connection::Prune() { |
| 824 | RTC_DCHECK_RUN_ON(network_thread_); |
| 825 | if (!pruned_ || active()) { |
| 826 | RTC_LOG(LS_INFO) << ToString() << ": Connection pruned"; |
| 827 | pruned_ = true; |
| 828 | requests_.Clear(); |
| 829 | set_write_state(STATE_WRITE_TIMEOUT); |
| 830 | } |
| 831 | } |
| 832 |
| 833 | void Connection::Destroy() { |
| 834 | RTC_DCHECK_RUN_ON(network_thread_); |
| 835 | RTC_DCHECK(port_) << ToDebugId() << ": port_ null in Destroy()"; |
| 836 | if (port_) |
| 837 | port_->DestroyConnection(this); |
| 838 | } |
| 839 |
| 840 | bool Connection::Shutdown() { |
| 841 | RTC_DCHECK_RUN_ON(network_thread_); |
| 842 | RTC_DCHECK(port_) << ToDebugId() << ": Calling Shutdown() twice?"; |
| 843 | if (!port_) |
| 844 | return false; // already shut down. |
| 845 |
| 846 | RTC_DLOG(LS_VERBOSE) << ToString() << ": Connection destroyed"; |
| 847 |
| 848 | // Fire the 'destroyed' event before deleting the object. This is done |
| 849 | // intentionally to avoid a situation whereby the signal might have dangling |
| 850 | // pointers to objects that have been deleted by the time the async task |
| 851 | // that deletes the connection object runs. |
| 852 | auto destroyed_signals = SignalDestroyed; |
| 853 | SignalDestroyed.disconnect_all(); |
| 854 | destroyed_signals(this); |
| 855 |
| 856 | LogCandidatePairConfig(webrtc::IceCandidatePairConfigType::kDestroyed); |
| 857 |
| 858 | // Reset the `port_` after logging and firing the destroyed signal since |
| 859 | // information required for logging needs access to `port_`. |
| 860 | port_.reset(); |
| 861 |
| 862 | // Clear any pending requests (or responses). |
| 863 | requests_.Clear(); |
| 864 |
| 865 | return true; |
| 866 | } |
| 867 |
| 868 | void Connection::FailAndPrune() { |
| 869 | RTC_DCHECK_RUN_ON(network_thread_); |
| 870 |
| 871 | // TODO(bugs.webrtc.org/13865): There's a circular dependency between Port |
| 872 | // and Connection. In some cases (Port dtor), a Connection object is deleted |
| 873 | // without using the `Destroy` method (port_ won't be nulled and some |
| 874 | // functionality won't run as expected), while in other cases |
| 875 | // the Connection object is deleted asynchronously and in that case `port_` |
| 876 | // will be nulled. |
| 877 | // In such a case, there's a chance that the Port object gets |
| 878 | // deleted before the Connection object ends up being deleted. |
| 879 | RTC_DCHECK(port_) << ToDebugId() << ": port_ null in FailAndPrune()"; |
| 880 | if (!port_) |
| 881 | return; |
| 882 |
| 883 | set_state(IceCandidatePairState::FAILED); |
| 884 | Prune(); |
| 885 | } |
| 886 |
| 887 | void Connection::PrintPingsSinceLastResponse(std::string* s, size_t max) { |
| 888 | RTC_DCHECK_RUN_ON(network_thread_); |
| 889 | rtc::StringBuilder oss; |
| 890 | if (pings_since_last_response_.size() > max) { |
| 891 | for (size_t i = 0; i < max; i++) { |
| 892 | const SentPing& ping = pings_since_last_response_[i]; |
| 893 | oss << rtc::hex_encode(ping.id) << " "; |
| 894 | } |
| 895 | oss << "... " << (pings_since_last_response_.size() - max) << " more"; |
| 896 | } else { |
| 897 | for (const SentPing& ping : pings_since_last_response_) { |
| 898 | oss << rtc::hex_encode(ping.id) << " "; |
| 899 | } |
| 900 | } |
| 901 | *s = oss.str(); |
| 902 | } |
| 903 |
| 904 | bool Connection::selected() const { |
| 905 | RTC_DCHECK_RUN_ON(network_thread_); |
| 906 | return selected_; |
| 907 | } |
| 908 |
| 909 | void Connection::set_selected(bool selected) { |
| 910 | RTC_DCHECK_RUN_ON(network_thread_); |
| 911 | selected_ = selected; |
| 912 | } |
| 913 |
| 914 | void Connection::UpdateState(int64_t now) { |
| 915 | RTC_DCHECK_RUN_ON(network_thread_); |
| 916 | RTC_DCHECK(port_) << ToDebugId() << ": port_ null in UpdateState()"; |
| 917 | if (!port_) |
| 918 | return; |
| 919 |
| 920 | int rtt = ConservativeRTTEstimate(rtt_); |
| 921 |
| 922 | if (RTC_LOG_CHECK_LEVEL(LS_VERBOSE)) { |
| 923 | std::string pings; |
| 924 | PrintPingsSinceLastResponse(&pings, 5); |
| 925 | RTC_LOG(LS_VERBOSE) << ToString() |
| 926 | << ": UpdateState()" |
| 927 | ", ms since last received response=" |
| 928 | << now - last_ping_response_received_ |
| 929 | << ", ms since last received data=" |
| 930 | << now - last_data_received_ << ", rtt=" << rtt |
| 931 | << ", pings_since_last_response=" << pings; |
| 932 | } |
| 933 |
| 934 | // Check the writable state. (The order of these checks is important.) |
| 935 | // |
| 936 | // Before becoming unwritable, we allow for a fixed number of pings to fail |
| 937 | // (i.e., receive no response). We also have to give the response time to |
| 938 | // get back, so we include a conservative estimate of this. |
| 939 | // |
| 940 | // Before timing out writability, we give a fixed amount of time. This is to |
| 941 | // allow for changes in network conditions. |
| 942 |
| 943 | if ((write_state_ == STATE_WRITABLE) && |
| 944 | TooManyFailures(pings_since_last_response_, unwritable_min_checks(), rtt, |
| 945 | now) && |
| 946 | TooLongWithoutResponse(pings_since_last_response_, unwritable_timeout(), |
| 947 | now)) { |
| 948 | uint32_t max_pings = unwritable_min_checks(); |
| 949 | RTC_LOG(LS_INFO) << ToString() << ": Unwritable after " << max_pings |
| 950 | << " ping failures and " |
| 951 | << now - pings_since_last_response_[0].sent_time |
| 952 | << " ms without a response," |
| 953 | " ms since last received ping=" |
| 954 | << now - last_ping_received_ |
| 955 | << " ms since last received data=" |
| 956 | << now - last_data_received_ << " rtt=" << rtt; |
| 957 | set_write_state(STATE_WRITE_UNRELIABLE); |
| 958 | } |
| 959 | if ((write_state_ == STATE_WRITE_UNRELIABLE || |
| 960 | write_state_ == STATE_WRITE_INIT) && |
| 961 | TooLongWithoutResponse(pings_since_last_response_, inactive_timeout(), |
| 962 | now)) { |
| 963 | RTC_LOG(LS_INFO) << ToString() << ": Timed out after " |
| 964 | << now - pings_since_last_response_[0].sent_time |
| 965 | << " ms without a response, rtt=" << rtt; |
| 966 | set_write_state(STATE_WRITE_TIMEOUT); |
| 967 | } |
| 968 |
| 969 | // Update the receiving state. |
| 970 | UpdateReceiving(now); |
| 971 | if (dead(now)) { |
| 972 | port_->DestroyConnectionAsync(this); |
| 973 | } |
| 974 | } |
| 975 |
| 976 | void Connection::UpdateLocalIceParameters(int component, |
| 977 | absl::string_view username_fragment, |
| 978 | absl::string_view password) { |
| 979 | RTC_DCHECK_RUN_ON(network_thread_); |
| 980 | local_candidate_.set_component(component); |
| 981 | local_candidate_.set_username(username_fragment); |
| 982 | local_candidate_.set_password(password); |
| 983 | } |
| 984 |
| 985 | int64_t Connection::last_ping_sent() const { |
| 986 | RTC_DCHECK_RUN_ON(network_thread_); |
| 987 | return last_ping_sent_; |
| 988 | } |
| 989 |
| 990 | void Connection::Ping(int64_t now, |
| 991 | std::unique_ptr<StunByteStringAttribute> delta) { |
| 992 | RTC_DCHECK_RUN_ON(network_thread_); |
| 993 | RTC_DCHECK(port_) << ToDebugId() << ": port_ null in Ping()"; |
| 994 | if (!port_) |
| 995 | return; |
| 996 |
| 997 | last_ping_sent_ = now; |
| 998 |
| 999 | // If not using renomination, we use "1" to mean "nominated" and "0" to mean |
| 1000 | // "not nominated". If using renomination, values greater than 1 are used for |
| 1001 | // re-nominated pairs. |
| 1002 | int nomination = use_candidate_attr_ ? 1 : 0; |
| 1003 | if (nomination_ > 0) { |
| 1004 | nomination = nomination_; |
| 1005 | } |
| 1006 |
| 1007 | bool has_delta = delta != nullptr; |
| 1008 | auto req = std::make_unique<ConnectionRequest>( |
| 1009 | requests_, this, BuildPingRequest(std::move(delta))); |
| 1010 |
| 1011 | if (!has_delta && ShouldSendGoogPing(req->msg())) { |
| 1012 | auto message = std::make_unique<IceMessage>(GOOG_PING_REQUEST, req->id()); |
| 1013 | message->AddMessageIntegrity32(remote_candidate_.password()); |
| 1014 | req.reset(new ConnectionRequest(requests_, this, std::move(message))); |
| 1015 | } |
| 1016 |
| 1017 | pings_since_last_response_.push_back(SentPing(req->id(), now, nomination)); |
| 1018 | RTC_LOG(LS_VERBOSE) << ToString() << ": Sending STUN ping, id=" |
| 1019 | << rtc::hex_encode(req->id()) |
| 1020 | << ", nomination=" << nomination_; |
| 1021 | requests_.Send(req.release()); |
| 1022 | state_ = IceCandidatePairState::IN_PROGRESS; |
| 1023 | num_pings_sent_++; |
| 1024 | } |
| 1025 |
| 1026 | std::unique_ptr<IceMessage> Connection::BuildPingRequest( |
| 1027 | std::unique_ptr<StunByteStringAttribute> delta) { |
| 1028 | auto message = std::make_unique<IceMessage>(STUN_BINDING_REQUEST); |
| 1029 | // Note that the order of attributes does not impact the parsing on the |
| 1030 | // receiver side. The attribute is retrieved then by iterating and matching |
| 1031 | // over all parsed attributes. See StunMessage::GetAttribute. |
| 1032 | message->AddAttribute(std::make_unique<StunByteStringAttribute>( |
| 1033 | STUN_ATTR_USERNAME, |
| 1034 | port()->CreateStunUsername(remote_candidate_.username()))); |
| 1035 | message->AddAttribute(std::make_unique<StunUInt32Attribute>( |
| 1036 | STUN_ATTR_GOOG_NETWORK_INFO, |
| 1037 | (port_->Network()->id() << 16) | port_->network_cost())); |
| 1038 |
| 1039 | if (field_trials_->piggyback_ice_check_acknowledgement && |
| 1040 | last_ping_id_received_) { |
| 1041 | message->AddAttribute(std::make_unique<StunByteStringAttribute>( |
| 1042 | STUN_ATTR_GOOG_LAST_ICE_CHECK_RECEIVED, *last_ping_id_received_)); |
| 1043 | } |
| 1044 |
| 1045 | // Adding ICE_CONTROLLED or ICE_CONTROLLING attribute based on the role. |
| 1046 | IceRole ice_role = port_->GetIceRole(); |
| 1047 | RTC_DCHECK(ice_role == ICEROLE_CONTROLLING || ice_role == ICEROLE_CONTROLLED); |
| 1048 | message->AddAttribute(std::make_unique<StunUInt64Attribute>( |
| 1049 | ice_role == ICEROLE_CONTROLLING ? STUN_ATTR_ICE_CONTROLLING |
| 1050 | : STUN_ATTR_ICE_CONTROLLED, |
| 1051 | port_->IceTiebreaker())); |
| 1052 |
| 1053 | if (ice_role == ICEROLE_CONTROLLING) { |
| 1054 | // We should have either USE_CANDIDATE attribute or ICE_NOMINATION |
| 1055 | // attribute but not both. That was enforced in p2ptransportchannel. |
| 1056 | if (use_candidate_attr()) { |
| 1057 | message->AddAttribute( |
| 1058 | std::make_unique<StunByteStringAttribute>(STUN_ATTR_USE_CANDIDATE)); |
| 1059 | } |
| 1060 | if (nomination_ && nomination_ != acked_nomination()) { |
| 1061 | message->AddAttribute(std::make_unique<StunUInt32Attribute>( |
| 1062 | STUN_ATTR_NOMINATION, nomination_)); |
| 1063 | } |
| 1064 | } |
| 1065 |
| 1066 | message->AddAttribute(std::make_unique<StunUInt32Attribute>( |
| 1067 | STUN_ATTR_PRIORITY, prflx_priority())); |
| 1068 |
| 1069 | if (port()->send_retransmit_count_attribute()) { |
| 1070 | message->AddAttribute(std::make_unique<StunUInt32Attribute>( |
| 1071 | STUN_ATTR_RETRANSMIT_COUNT, pings_since_last_response_.size())); |
| 1072 | } |
| 1073 | if (field_trials_->enable_goog_ping && |
| 1074 | !remote_support_goog_ping_.has_value()) { |
| 1075 | // Check if remote supports GOOG PING by announcing which version we |
| 1076 | // support. This is sent on all STUN_BINDING_REQUEST until we get a |
| 1077 | // STUN_BINDING_RESPONSE. |
| 1078 | auto list = |
| 1079 | StunAttribute::CreateUInt16ListAttribute(STUN_ATTR_GOOG_MISC_INFO); |
| 1080 | list->AddTypeAtIndex(kSupportGoogPingVersionRequestIndex, kGoogPingVersion); |
| 1081 | message->AddAttribute(std::move(list)); |
| 1082 | } |
| 1083 |
| 1084 | if (delta) { |
| 1085 | RTC_DCHECK(delta->type() == STUN_ATTR_GOOG_DELTA); |
| 1086 | RTC_LOG(LS_INFO) << "Sending GOOG_DELTA: len: " << delta->length(); |
| 1087 | message->AddAttribute(std::move(delta)); |
| 1088 | } |
| 1089 |
| 1090 | message->AddMessageIntegrity(remote_candidate_.password()); |
| 1091 | message->AddFingerprint(); |
| 1092 |
| 1093 | return message; |
| 1094 | } |
| 1095 |
| 1096 | int64_t Connection::last_ping_response_received() const { |
| 1097 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1098 | return last_ping_response_received_; |
| 1099 | } |
| 1100 |
| 1101 | const absl::optional<std::string>& Connection::last_ping_id_received() const { |
| 1102 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1103 | return last_ping_id_received_; |
| 1104 | } |
| 1105 |
| 1106 | // Used to check if any STUN ping response has been received. |
| 1107 | int Connection::rtt_samples() const { |
| 1108 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1109 | return rtt_samples_; |
| 1110 | } |
| 1111 |
| 1112 | // Called whenever a valid ping is received on this connection. This is |
| 1113 | // public because the connection intercepts the first ping for us. |
| 1114 | int64_t Connection::last_ping_received() const { |
| 1115 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1116 | return last_ping_received_; |
| 1117 | } |
| 1118 |
| 1119 | void Connection::ReceivedPing(const absl::optional<std::string>& request_id) { |
| 1120 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1121 | last_ping_received_ = rtc::TimeMillis(); |
| 1122 | last_ping_id_received_ = request_id; |
| 1123 | UpdateReceiving(last_ping_received_); |
| 1124 | } |
| 1125 |
| 1126 | void Connection::HandlePiggybackCheckAcknowledgementIfAny(StunMessage* msg) { |
| 1127 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1128 | RTC_DCHECK(msg->type() == STUN_BINDING_REQUEST || |
| 1129 | msg->type() == GOOG_PING_REQUEST); |
| 1130 | const StunByteStringAttribute* last_ice_check_received_attr = |
| 1131 | msg->GetByteString(STUN_ATTR_GOOG_LAST_ICE_CHECK_RECEIVED); |
| 1132 | if (last_ice_check_received_attr) { |
| 1133 | const absl::string_view request_id = |
| 1134 | last_ice_check_received_attr->string_view(); |
| 1135 | auto iter = absl::c_find_if( |
| 1136 | pings_since_last_response_, |
| 1137 | [&request_id](const SentPing& ping) { return ping.id == request_id; }); |
| 1138 | if (iter != pings_since_last_response_.end()) { |
| 1139 | rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE; |
| 1140 | RTC_LOG_V(sev) << ToString() |
| 1141 | << ": Received piggyback STUN ping response, id=" |
| 1142 | << rtc::hex_encode(request_id); |
| 1143 | const int64_t rtt = rtc::TimeMillis() - iter->sent_time; |
| 1144 | ReceivedPingResponse(rtt, request_id, iter->nomination); |
| 1145 | } |
| 1146 | } |
| 1147 | } |
| 1148 |
| 1149 | int64_t Connection::last_send_data() const { |
| 1150 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1151 | return last_send_data_; |
| 1152 | } |
| 1153 |
| 1154 | int64_t Connection::last_data_received() const { |
| 1155 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1156 | return last_data_received_; |
| 1157 | } |
| 1158 |
| 1159 | void Connection::ReceivedPingResponse( |
| 1160 | int rtt, |
| 1161 | absl::string_view request_id, |
| 1162 | const absl::optional<uint32_t>& nomination) { |
| 1163 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1164 | RTC_DCHECK_GE(rtt, 0); |
| 1165 | // We've already validated that this is a STUN binding response with |
| 1166 | // the correct local and remote username for this connection. |
| 1167 | // So if we're not already, become writable. We may be bringing a pruned |
| 1168 | // connection back to life, but if we don't really want it, we can always |
| 1169 | // prune it again. |
| 1170 | if (nomination && nomination.value() > acked_nomination_) { |
| 1171 | acked_nomination_ = nomination.value(); |
| 1172 | } |
| 1173 |
| 1174 | int64_t now = rtc::TimeMillis(); |
| 1175 | total_round_trip_time_ms_ += rtt; |
| 1176 | current_round_trip_time_ms_ = static_cast<uint32_t>(rtt); |
| 1177 | rtt_estimate_.AddSample(now, rtt); |
| 1178 |
| 1179 | pings_since_last_response_.clear(); |
| 1180 | last_ping_response_received_ = now; |
| 1181 | UpdateReceiving(last_ping_response_received_); |
| 1182 | set_write_state(STATE_WRITABLE); |
| 1183 | set_state(IceCandidatePairState::SUCCEEDED); |
| 1184 | if (rtt_samples_ > 0) { |
| 1185 | rtt_ = rtc::GetNextMovingAverage(rtt_, rtt, RTT_RATIO); |
| 1186 | } else { |
| 1187 | rtt_ = rtt; |
| 1188 | } |
| 1189 | rtt_samples_++; |
| 1190 | } |
| 1191 |
| 1192 | Connection::WriteState Connection::write_state() const { |
| 1193 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1194 | return write_state_; |
| 1195 | } |
| 1196 |
| 1197 | bool Connection::writable() const { |
| 1198 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1199 | return write_state_ == STATE_WRITABLE; |
| 1200 | } |
| 1201 |
| 1202 | bool Connection::receiving() const { |
| 1203 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1204 | return receiving_; |
| 1205 | } |
| 1206 |
| 1207 | // Determines whether the connection has finished connecting. This can only |
| 1208 | // be false for TCP connections. |
| 1209 | bool Connection::connected() const { |
| 1210 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1211 | return connected_; |
| 1212 | } |
| 1213 |
| 1214 | bool Connection::weak() const { |
| 1215 | return !(writable() && receiving() && connected()); |
| 1216 | } |
| 1217 |
| 1218 | bool Connection::active() const { |
| 1219 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1220 | return write_state_ != STATE_WRITE_TIMEOUT; |
| 1221 | } |
| 1222 |
| 1223 | bool Connection::dead(int64_t now) const { |
| 1224 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1225 | if (last_received() > 0) { |
| 1226 | // If it has ever received anything, we keep it alive |
| 1227 | // - if it has recevied last DEAD_CONNECTION_RECEIVE_TIMEOUT (30s) |
| 1228 | // - if it has a ping outstanding shorter than |
| 1229 | // DEAD_CONNECTION_RECEIVE_TIMEOUT (30s) |
| 1230 | // - else if IDLE let it live field_trials_->dead_connection_timeout_ms |
| 1231 | // |
| 1232 | // This covers the normal case of a successfully used connection that stops |
| 1233 | // working. This also allows a remote peer to continue pinging over a |
| 1234 | // locally inactive (pruned) connection. This also allows the local agent to |
| 1235 | // ping with longer interval than 30s as long as it shorter than |
| 1236 | // `dead_connection_timeout_ms`. |
| 1237 | if (now <= (last_received() + DEAD_CONNECTION_RECEIVE_TIMEOUT)) { |
| 1238 | // Not dead since we have received the last 30s. |
| 1239 | return false; |
| 1240 | } |
| 1241 | if (!pings_since_last_response_.empty()) { |
| 1242 | // Outstanding pings: let it live until the ping is unreplied for |
| 1243 | // DEAD_CONNECTION_RECEIVE_TIMEOUT. |
| 1244 | return now > (pings_since_last_response_[0].sent_time + |
| 1245 | DEAD_CONNECTION_RECEIVE_TIMEOUT); |
| 1246 | } |
| 1247 |
| 1248 | // No outstanding pings: let it live until |
| 1249 | // field_trials_->dead_connection_timeout_ms has passed. |
| 1250 | return now > (last_received() + field_trials_->dead_connection_timeout_ms); |
| 1251 | } |
| 1252 |
| 1253 | if (active()) { |
| 1254 | // If it has never received anything, keep it alive as long as it is |
| 1255 | // actively pinging and not pruned. Otherwise, the connection might be |
| 1256 | // deleted before it has a chance to ping. This is the normal case for a |
| 1257 | // new connection that is pinging but hasn't received anything yet. |
| 1258 | return false; |
| 1259 | } |
| 1260 |
| 1261 | // If it has never received anything and is not actively pinging (pruned), we |
| 1262 | // keep it around for at least MIN_CONNECTION_LIFETIME to prevent connections |
| 1263 | // from being pruned too quickly during a network change event when two |
| 1264 | // networks would be up simultaneously but only for a brief period. |
| 1265 | return now > (time_created_ms_ + MIN_CONNECTION_LIFETIME); |
| 1266 | } |
| 1267 |
| 1268 | int Connection::rtt() const { |
| 1269 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1270 | return rtt_; |
| 1271 | } |
| 1272 |
| 1273 | bool Connection::stable(int64_t now) const { |
| 1274 | // A connection is stable if it's RTT has converged and it isn't missing any |
| 1275 | // responses. We should send pings at a higher rate until the RTT converges |
| 1276 | // and whenever a ping response is missing (so that we can detect |
| 1277 | // unwritability faster) |
| 1278 | return rtt_converged() && !missing_responses(now); |
| 1279 | } |
| 1280 |
| 1281 | std::string Connection::ToDebugId() const { |
| 1282 | return rtc::ToHex(reinterpret_cast<uintptr_t>(this)); |
| 1283 | } |
| 1284 |
| 1285 | uint32_t Connection::ComputeNetworkCost() const { |
| 1286 | // TODO(honghaiz): Will add rtt as part of the network cost. |
| 1287 | RTC_DCHECK(port_) << ToDebugId() << ": port_ null in ComputeNetworkCost()"; |
| 1288 | return port()->network_cost() + remote_candidate_.network_cost(); |
| 1289 | } |
| 1290 |
| 1291 | std::string Connection::ToString() const { |
| 1292 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1293 | RTC_DCHECK(port_) << ToDebugId() << ": port_ null in ToString()"; |
| 1294 | constexpr absl::string_view CONNECT_STATE_ABBREV[2] = { |
| 1295 | "-", // not connected (false) |
| 1296 | "C", // connected (true) |
| 1297 | }; |
| 1298 | constexpr absl::string_view RECEIVE_STATE_ABBREV[2] = { |
| 1299 | "-", // not receiving (false) |
| 1300 | "R", // receiving (true) |
| 1301 | }; |
| 1302 | constexpr absl::string_view WRITE_STATE_ABBREV[4] = { |
| 1303 | "W", // STATE_WRITABLE |
| 1304 | "w", // STATE_WRITE_UNRELIABLE |
| 1305 | "-", // STATE_WRITE_INIT |
| 1306 | "x", // STATE_WRITE_TIMEOUT |
| 1307 | }; |
| 1308 | constexpr absl::string_view ICESTATE[4] = { |
| 1309 | "W", // STATE_WAITING |
| 1310 | "I", // STATE_INPROGRESS |
| 1311 | "S", // STATE_SUCCEEDED |
| 1312 | "F" // STATE_FAILED |
| 1313 | }; |
| 1314 | constexpr absl::string_view SELECTED_STATE_ABBREV[2] = { |
| 1315 | "-", // candidate pair not selected (false) |
| 1316 | "S", // selected (true) |
| 1317 | }; |
| 1318 | rtc::StringBuilder ss; |
| 1319 | ss << "Conn[" << ToDebugId(); |
| 1320 |
| 1321 | if (!port_) { |
| 1322 | // No content or network names for pending delete. Temporarily substitute |
| 1323 | // the names with a hash (rhyming with trash). |
| 1324 | ss << ":#:#:"; |
| 1325 | } else { |
| 1326 | ss << ":" << port_->content_name() << ":" << port_->Network()->ToString() |
| 1327 | << ":"; |
| 1328 | } |
| 1329 |
| 1330 | const Candidate& local = local_candidate(); |
| 1331 | const Candidate& remote = remote_candidate(); |
| 1332 | ss << local.id() << ":" << local.component() << ":" << local.generation() |
| 1333 | << ":" << local.type_name() << ":" << local.protocol() << ":" |
| 1334 | << local.address().ToSensitiveString() << "->" << remote.id() << ":" |
| 1335 | << remote.component() << ":" << remote.priority() << ":" |
| 1336 | << remote.type_name() << ":" << remote.protocol() << ":" |
| 1337 | << remote.address().ToSensitiveString() << "|"; |
| 1338 |
| 1339 | ss << CONNECT_STATE_ABBREV[connected_] << RECEIVE_STATE_ABBREV[receiving_] |
| 1340 | << WRITE_STATE_ABBREV[write_state_] << ICESTATE[static_cast<int>(state_)] |
| 1341 | << "|" << SELECTED_STATE_ABBREV[selected_] << "|" << remote_nomination_ |
| 1342 | << "|" << nomination_ << "|"; |
| 1343 |
| 1344 | if (port_) |
| 1345 | ss << priority() << "|"; |
| 1346 |
| 1347 | if (rtt_ < DEFAULT_RTT) { |
| 1348 | ss << rtt_ << "]"; |
| 1349 | } else { |
| 1350 | ss << "-]"; |
| 1351 | } |
| 1352 |
| 1353 | return ss.Release(); |
| 1354 | } |
| 1355 |
| 1356 | std::string Connection::ToSensitiveString() const { |
| 1357 | return ToString(); |
| 1358 | } |
| 1359 |
| 1360 | const webrtc::IceCandidatePairDescription& Connection::ToLogDescription() { |
| 1361 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1362 | if (log_description_.has_value()) { |
| 1363 | return log_description_.value(); |
| 1364 | } |
| 1365 | const Candidate& local = local_candidate(); |
| 1366 | const Candidate& remote = remote_candidate(); |
| 1367 | const rtc::Network* network = port()->Network(); |
| 1368 | log_description_ = webrtc::IceCandidatePairDescription( |
| 1369 | GetRtcEventLogCandidateType(local), GetRtcEventLogCandidateType(remote)); |
| 1370 | log_description_->local_relay_protocol = |
| 1371 | GetProtocolByString(local.relay_protocol()); |
| 1372 | log_description_->local_network_type = ConvertNetworkType(network->type()); |
| 1373 | log_description_->local_address_family = |
| 1374 | GetAddressFamilyByInt(local.address().family()); |
| 1375 | log_description_->remote_address_family = |
| 1376 | GetAddressFamilyByInt(remote.address().family()); |
| 1377 | log_description_->candidate_pair_protocol = |
| 1378 | GetProtocolByString(local.protocol()); |
| 1379 | return log_description_.value(); |
| 1380 | } |
| 1381 |
| 1382 | void Connection::set_ice_event_log(webrtc::IceEventLog* ice_event_log) { |
| 1383 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1384 | ice_event_log_ = ice_event_log; |
| 1385 | } |
| 1386 |
| 1387 | void Connection::LogCandidatePairConfig( |
| 1388 | webrtc::IceCandidatePairConfigType type) { |
| 1389 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1390 | if (ice_event_log_ == nullptr) { |
| 1391 | return; |
| 1392 | } |
| 1393 | ice_event_log_->LogCandidatePairConfig(type, id(), ToLogDescription()); |
| 1394 | } |
| 1395 |
| 1396 | void Connection::LogCandidatePairEvent(webrtc::IceCandidatePairEventType type, |
| 1397 | uint32_t transaction_id) { |
| 1398 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1399 | if (ice_event_log_ == nullptr) { |
| 1400 | return; |
| 1401 | } |
| 1402 | ice_event_log_->LogCandidatePairEvent(type, id(), transaction_id); |
| 1403 | } |
| 1404 |
| 1405 | void Connection::OnConnectionRequestResponse(StunRequest* request, |
| 1406 | StunMessage* response) { |
| 1407 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1408 | // Log at LS_INFO if we receive a ping response on an unwritable |
| 1409 | // connection. |
| 1410 | rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE; |
| 1411 |
| 1412 | int rtt = request->Elapsed(); |
| 1413 |
| 1414 | if (RTC_LOG_CHECK_LEVEL_V(sev)) { |
| 1415 | std::string pings; |
| 1416 | PrintPingsSinceLastResponse(&pings, 5); |
| 1417 | RTC_LOG_V(sev) << ToString() << ": Received " |
| 1418 | << StunMethodToString(response->type()) |
| 1419 | << ", id=" << rtc::hex_encode(request->id()) |
| 1420 | << ", code=0" // Makes logging easier to parse. |
| 1421 | ", rtt=" |
| 1422 | << rtt << ", pings_since_last_response=" << pings; |
| 1423 | } |
| 1424 | absl::optional<uint32_t> nomination; |
| 1425 | const std::string request_id = request->id(); |
| 1426 | auto iter = absl::c_find_if( |
| 1427 | pings_since_last_response_, |
| 1428 | [&request_id](const SentPing& ping) { return ping.id == request_id; }); |
| 1429 | if (iter != pings_since_last_response_.end()) { |
| 1430 | nomination.emplace(iter->nomination); |
| 1431 | } |
| 1432 | ReceivedPingResponse(rtt, request_id, nomination); |
| 1433 |
| 1434 | stats_.recv_ping_responses++; |
| 1435 | LogCandidatePairEvent( |
| 1436 | webrtc::IceCandidatePairEventType::kCheckResponseReceived, |
| 1437 | response->reduced_transaction_id()); |
| 1438 |
| 1439 | if (request->msg()->type() == STUN_BINDING_REQUEST) { |
| 1440 | if (!remote_support_goog_ping_.has_value()) { |
| 1441 | auto goog_misc = response->GetUInt16List(STUN_ATTR_GOOG_MISC_INFO); |
| 1442 | if (goog_misc != nullptr && |
| 1443 | goog_misc->Size() >= kSupportGoogPingVersionResponseIndex) { |
| 1444 | // The remote peer has indicated that it {does/does not} supports |
| 1445 | // GOOG_PING. |
| 1446 | remote_support_goog_ping_ = |
| 1447 | goog_misc->GetType(kSupportGoogPingVersionResponseIndex) >= |
| 1448 | kGoogPingVersion; |
| 1449 | } else { |
| 1450 | remote_support_goog_ping_ = false; |
| 1451 | } |
| 1452 | } |
| 1453 |
| 1454 | MaybeUpdateLocalCandidate(request, response); |
| 1455 |
| 1456 | if (field_trials_->enable_goog_ping && remote_support_goog_ping_) { |
| 1457 | cached_stun_binding_ = request->msg()->Clone(); |
| 1458 | } |
| 1459 | } |
| 1460 |
| 1461 | // Did we send a delta ? |
| 1462 | const bool sent_goog_delta = |
| 1463 | request->msg()->GetByteString(STUN_ATTR_GOOG_DELTA) != nullptr; |
| 1464 | // Did we get a GOOG_DELTA_ACK ? |
| 1465 | const StunUInt64Attribute* delta_ack = |
| 1466 | response->GetUInt64(STUN_ATTR_GOOG_DELTA_ACK); |
| 1467 |
| 1468 | if (goog_delta_ack_consumer_) { |
| 1469 | if (sent_goog_delta && delta_ack) { |
| 1470 | RTC_LOG(LS_VERBOSE) << "Got GOOG_DELTA_ACK len: " << delta_ack->length(); |
| 1471 | (*goog_delta_ack_consumer_)(delta_ack); |
| 1472 | } else if (sent_goog_delta) { |
| 1473 | // We sent DELTA but did not get a DELTA_ACK. |
| 1474 | // This means that remote does not support GOOG_DELTA |
| 1475 | RTC_LOG(LS_INFO) << "NO DELTA ACK => disable GOOG_DELTA"; |
| 1476 | (*goog_delta_ack_consumer_)( |
| 1477 | webrtc::RTCError(webrtc::RTCErrorType::UNSUPPORTED_OPERATION)); |
| 1478 | } else if (delta_ack) { |
| 1479 | // We did NOT send DELTA but got a DELTA_ACK. |
| 1480 | // That is internal error. |
| 1481 | RTC_LOG(LS_ERROR) << "DELTA ACK w/o DELTA => disable GOOG_DELTA"; |
| 1482 | (*goog_delta_ack_consumer_)( |
| 1483 | webrtc::RTCError(webrtc::RTCErrorType::INTERNAL_ERROR)); |
| 1484 | } |
| 1485 | } else if (delta_ack) { |
| 1486 | RTC_LOG(LS_ERROR) << "Discard GOOG_DELTA_ACK, no consumer"; |
| 1487 | } |
| 1488 | } |
| 1489 |
| 1490 | void Connection::OnConnectionRequestErrorResponse(ConnectionRequest* request, |
| 1491 | StunMessage* response) { |
| 1492 | RTC_DCHECK(port_) << ToDebugId() |
| 1493 | << ": port_ null in OnConnectionRequestErrorResponse"; |
| 1494 | if (!port_) |
| 1495 | return; |
| 1496 |
| 1497 | int error_code = response->GetErrorCodeValue(); |
| 1498 | RTC_LOG(LS_WARNING) << ToString() << ": Received " |
| 1499 | << StunMethodToString(response->type()) |
| 1500 | << " id=" << rtc::hex_encode(request->id()) |
| 1501 | << " code=" << error_code |
| 1502 | << " rtt=" << request->Elapsed(); |
| 1503 |
| 1504 | cached_stun_binding_.reset(); |
| 1505 | if (error_code == STUN_ERROR_UNKNOWN_ATTRIBUTE || |
| 1506 | error_code == STUN_ERROR_SERVER_ERROR || |
| 1507 | error_code == STUN_ERROR_UNAUTHORIZED) { |
| 1508 | // Recoverable error, retry |
| 1509 | } else if (error_code == STUN_ERROR_ROLE_CONFLICT) { |
| 1510 | port_->SignalRoleConflict(port_.get()); |
| 1511 | } else if (request->msg()->type() == GOOG_PING_REQUEST) { |
| 1512 | // Race, retry. |
| 1513 | } else { |
| 1514 | // This is not a valid connection. |
| 1515 | RTC_LOG(LS_ERROR) << ToString() |
| 1516 | << ": Received STUN error response, code=" << error_code |
| 1517 | << "; killing connection"; |
| 1518 | set_state(IceCandidatePairState::FAILED); |
| 1519 | port_->DestroyConnectionAsync(this); |
| 1520 | } |
| 1521 | } |
| 1522 |
| 1523 | void Connection::OnConnectionRequestTimeout(ConnectionRequest* request) { |
| 1524 | // Log at LS_INFO if we miss a ping on a writable connection. |
| 1525 | rtc::LoggingSeverity sev = writable() ? rtc::LS_INFO : rtc::LS_VERBOSE; |
| 1526 | RTC_LOG_V(sev) << ToString() << ": Timing-out STUN ping " |
| 1527 | << rtc::hex_encode(request->id()) << " after " |
| 1528 | << request->Elapsed() << " ms"; |
| 1529 | } |
| 1530 |
| 1531 | void Connection::OnConnectionRequestSent(ConnectionRequest* request) { |
| 1532 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1533 | // Log at LS_INFO if we send a ping on an unwritable connection. |
| 1534 | rtc::LoggingSeverity sev = !writable() ? rtc::LS_INFO : rtc::LS_VERBOSE; |
| 1535 | RTC_LOG_V(sev) << ToString() << ": Sent " |
| 1536 | << StunMethodToString(request->msg()->type()) |
| 1537 | << ", id=" << rtc::hex_encode(request->id()) |
| 1538 | << ", use_candidate=" << use_candidate_attr() |
| 1539 | << ", nomination=" << nomination_; |
| 1540 | stats_.sent_ping_requests_total++; |
| 1541 | LogCandidatePairEvent(webrtc::IceCandidatePairEventType::kCheckSent, |
| 1542 | request->reduced_transaction_id()); |
| 1543 | if (stats_.recv_ping_responses == 0) { |
| 1544 | stats_.sent_ping_requests_before_first_response++; |
| 1545 | } |
| 1546 | } |
| 1547 |
| 1548 | IceCandidatePairState Connection::state() const { |
| 1549 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1550 | return state_; |
| 1551 | } |
| 1552 |
| 1553 | int Connection::num_pings_sent() const { |
| 1554 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1555 | return num_pings_sent_; |
| 1556 | } |
| 1557 |
| 1558 | void Connection::MaybeSetRemoteIceParametersAndGeneration( |
| 1559 | const IceParameters& ice_params, |
| 1560 | int generation) { |
| 1561 | if (remote_candidate_.username() == ice_params.ufrag && |
| 1562 | remote_candidate_.password().empty()) { |
| 1563 | remote_candidate_.set_password(ice_params.pwd); |
| 1564 | } |
| 1565 | // TODO(deadbeef): A value of '0' for the generation is used for both |
| 1566 | // generation 0 and "generation unknown". It should be changed to an |
| 1567 | // absl::optional to fix this. |
| 1568 | if (remote_candidate_.username() == ice_params.ufrag && |
| 1569 | remote_candidate_.password() == ice_params.pwd && |
| 1570 | remote_candidate_.generation() == 0) { |
| 1571 | remote_candidate_.set_generation(generation); |
| 1572 | } |
| 1573 | } |
| 1574 |
| 1575 | void Connection::MaybeUpdatePeerReflexiveCandidate( |
| 1576 | const Candidate& new_candidate) { |
| 1577 | if (remote_candidate_.is_prflx() && !new_candidate.is_prflx() && |
| 1578 | remote_candidate_.protocol() == new_candidate.protocol() && |
| 1579 | remote_candidate_.address() == new_candidate.address() && |
| 1580 | remote_candidate_.username() == new_candidate.username() && |
| 1581 | remote_candidate_.password() == new_candidate.password() && |
| 1582 | remote_candidate_.generation() == new_candidate.generation()) { |
| 1583 | remote_candidate_ = new_candidate; |
| 1584 | } |
| 1585 | } |
| 1586 |
| 1587 | int64_t Connection::last_received() const { |
| 1588 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1589 | return std::max(last_data_received_, |
| 1590 | std::max(last_ping_received_, last_ping_response_received_)); |
| 1591 | } |
| 1592 |
| 1593 | int64_t Connection::receiving_unchanged_since() const { |
| 1594 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1595 | return receiving_unchanged_since_; |
| 1596 | } |
| 1597 |
| 1598 | uint32_t Connection::prflx_priority() const { |
| 1599 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1600 | // PRIORITY Attribute. |
| 1601 | // Changing the type preference to Peer Reflexive and local preference |
| 1602 | // and component id information is unchanged from the original priority. |
| 1603 | // priority = (2^24)*(type preference) + |
| 1604 | // (2^8)*(local preference) + |
| 1605 | // (2^0)*(256 - component ID) |
| 1606 | IcePriorityValue type_preference = |
| 1607 | (local_candidate_.protocol() == TCP_PROTOCOL_NAME) |
| 1608 | ? ICE_TYPE_PREFERENCE_PRFLX_TCP |
| 1609 | : ICE_TYPE_PREFERENCE_PRFLX; |
| 1610 | return type_preference << 24 | (local_candidate_.priority() & 0x00FFFFFF); |
| 1611 | } |
| 1612 |
| 1613 | ConnectionInfo Connection::stats() { |
| 1614 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1615 | stats_.recv_bytes_second = round(recv_rate_tracker_.ComputeRate()); |
| 1616 | stats_.recv_total_bytes = recv_rate_tracker_.TotalSampleCount(); |
| 1617 | stats_.sent_bytes_second = round(send_rate_tracker_.ComputeRate()); |
| 1618 | stats_.sent_total_bytes = send_rate_tracker_.TotalSampleCount(); |
| 1619 | stats_.receiving = receiving_; |
| 1620 | stats_.writable = write_state_ == STATE_WRITABLE; |
| 1621 | stats_.timeout = write_state_ == STATE_WRITE_TIMEOUT; |
| 1622 | stats_.rtt = rtt_; |
| 1623 | stats_.key = this; |
| 1624 | stats_.state = state_; |
| 1625 | if (port_) { |
| 1626 | stats_.priority = priority(); |
| 1627 | stats_.local_candidate = local_candidate(); |
| 1628 | } |
| 1629 | stats_.nominated = nominated(); |
| 1630 | stats_.total_round_trip_time_ms = total_round_trip_time_ms_; |
| 1631 | stats_.current_round_trip_time_ms = current_round_trip_time_ms_; |
| 1632 | stats_.remote_candidate = remote_candidate(); |
| 1633 | if (last_data_received_ > 0) { |
| 1634 | stats_.last_data_received = webrtc::Timestamp::Millis( |
| 1635 | last_data_received_ + delta_internal_unix_epoch_ms_); |
| 1636 | } |
| 1637 | if (last_send_data_ > 0) { |
| 1638 | stats_.last_data_sent = webrtc::Timestamp::Millis( |
| 1639 | last_send_data_ + delta_internal_unix_epoch_ms_); |
| 1640 | } |
| 1641 | return stats_; |
| 1642 | } |
| 1643 |
| 1644 | void Connection::MaybeUpdateLocalCandidate(StunRequest* request, |
| 1645 | StunMessage* response) { |
| 1646 | RTC_DCHECK(port_) << ToDebugId() |
| 1647 | << ": port_ null in MaybeUpdateLocalCandidate"; |
| 1648 | if (!port_) |
| 1649 | return; |
| 1650 |
| 1651 | // RFC 5245 |
| 1652 | // The agent checks the mapped address from the STUN response. If the |
| 1653 | // transport address does not match any of the local candidates that the |
| 1654 | // agent knows about, the mapped address represents a new candidate -- a |
| 1655 | // peer reflexive candidate. |
| 1656 | const StunAddressAttribute* addr = |
| 1657 | response->GetAddress(STUN_ATTR_XOR_MAPPED_ADDRESS); |
| 1658 | if (!addr) { |
| 1659 | RTC_LOG(LS_WARNING) |
| 1660 | << "Connection::OnConnectionRequestResponse - " |
| 1661 | "No MAPPED-ADDRESS or XOR-MAPPED-ADDRESS found in the " |
| 1662 | "stun response message"; |
| 1663 | return; |
| 1664 | } |
| 1665 |
| 1666 | for (const Candidate& candidate : port_->Candidates()) { |
| 1667 | if (absl::EndsWith(candidate.address().hostname(), ".reflector")) { |
| 1668 | Candidate testCandidate = candidate; |
| 1669 | testCandidate.set_address(local_candidate_.address()); |
| 1670 | if (testCandidate == local_candidate_) { |
| 1671 | return; |
| 1672 | } |
| 1673 | } |
| 1674 |
| 1675 | if (candidate.address() == addr->GetAddress()) { |
| 1676 | if (local_candidate_ != candidate) { |
| 1677 | RTC_LOG(LS_INFO) << ToString() |
| 1678 | << ": Updating local candidate type to srflx."; |
| 1679 | local_candidate_ = candidate; |
| 1680 | // SignalStateChange to force a re-sort in P2PTransportChannel as this |
| 1681 | // Connection's local candidate has changed. |
| 1682 | SignalStateChange(this); |
| 1683 | } |
| 1684 | return; |
| 1685 | } |
| 1686 | } |
| 1687 |
| 1688 | // RFC 5245 |
| 1689 | // Its priority is set equal to the value of the PRIORITY attribute |
| 1690 | // in the Binding request. |
| 1691 | const StunUInt32Attribute* priority_attr = |
| 1692 | request->msg()->GetUInt32(STUN_ATTR_PRIORITY); |
| 1693 | if (!priority_attr) { |
| 1694 | RTC_LOG(LS_WARNING) << "Connection::OnConnectionRequestResponse - " |
| 1695 | "No STUN_ATTR_PRIORITY found in the " |
| 1696 | "stun response message"; |
| 1697 | return; |
| 1698 | } |
| 1699 | const uint32_t priority = priority_attr->value(); |
| 1700 |
| 1701 | // Create a peer-reflexive candidate based on the local candidate. |
| 1702 | local_candidate_.generate_id(); |
| 1703 | local_candidate_.set_type(PRFLX_PORT_TYPE); |
| 1704 | // Set the related address and foundation attributes before changing the |
| 1705 | // address. |
| 1706 | local_candidate_.set_related_address(local_candidate_.address()); |
| 1707 | local_candidate_.set_foundation(port()->ComputeFoundation( |
| 1708 | PRFLX_PORT_TYPE, local_candidate_.protocol(), |
| 1709 | local_candidate_.relay_protocol(), local_candidate_.address())); |
| 1710 | local_candidate_.set_priority(priority); |
| 1711 | local_candidate_.set_address(addr->GetAddress()); |
| 1712 |
| 1713 | // Change the local candidate of this Connection to the new prflx candidate. |
| 1714 | RTC_LOG(LS_INFO) << ToString() << ": Updating local candidate type to prflx."; |
| 1715 | port_->AddPrflxCandidate(local_candidate_); |
| 1716 |
| 1717 | // SignalStateChange to force a re-sort in P2PTransportChannel as this |
| 1718 | // Connection's local candidate has changed. |
| 1719 | SignalStateChange(this); |
| 1720 | } |
| 1721 |
| 1722 | bool Connection::rtt_converged() const { |
| 1723 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1724 | return rtt_samples_ > (RTT_RATIO + 1); |
| 1725 | } |
| 1726 |
| 1727 | bool Connection::missing_responses(int64_t now) const { |
| 1728 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1729 | if (pings_since_last_response_.empty()) { |
| 1730 | return false; |
| 1731 | } |
| 1732 |
| 1733 | int64_t waiting = now - pings_since_last_response_[0].sent_time; |
| 1734 | return waiting > 2 * rtt(); |
| 1735 | } |
| 1736 |
| 1737 | bool Connection::TooManyOutstandingPings( |
| 1738 | const absl::optional<int>& max_outstanding_pings) const { |
| 1739 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1740 | if (!max_outstanding_pings.has_value()) { |
| 1741 | return false; |
| 1742 | } |
| 1743 | if (static_cast<int>(pings_since_last_response_.size()) < |
| 1744 | *max_outstanding_pings) { |
| 1745 | return false; |
| 1746 | } |
| 1747 | return true; |
| 1748 | } |
| 1749 |
| 1750 | void Connection::SetLocalCandidateNetworkCost(uint16_t cost) { |
| 1751 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1752 |
| 1753 | if (cost == local_candidate_.network_cost()) |
| 1754 | return; |
| 1755 |
| 1756 | local_candidate_.set_network_cost(cost); |
| 1757 |
| 1758 | // Network cost change will affect the connection selection criteria. |
| 1759 | // Signal the connection state change to force a re-sort in |
| 1760 | // P2PTransportChannel. |
| 1761 | SignalStateChange(this); |
| 1762 | } |
| 1763 |
| 1764 | bool Connection::ShouldSendGoogPing(const StunMessage* message) { |
| 1765 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1766 | if (remote_support_goog_ping_ == true && cached_stun_binding_ && |
| 1767 | cached_stun_binding_->EqualAttributes(message, [](int type) { |
| 1768 | // Ignore these attributes. |
| 1769 | // NOTE: Consider what to do if adding more content to |
| 1770 | // STUN_ATTR_GOOG_MISC_INFO |
| 1771 | return type != STUN_ATTR_FINGERPRINT && |
| 1772 | type != STUN_ATTR_MESSAGE_INTEGRITY && |
| 1773 | type != STUN_ATTR_RETRANSMIT_COUNT && |
| 1774 | type != STUN_ATTR_GOOG_MISC_INFO; |
| 1775 | })) { |
| 1776 | return true; |
| 1777 | } |
| 1778 | return false; |
| 1779 | } |
| 1780 |
| 1781 | void Connection::ForgetLearnedState() { |
| 1782 | RTC_DCHECK_RUN_ON(network_thread_); |
| 1783 | RTC_LOG(LS_INFO) << ToString() << ": Connection forget learned state"; |
| 1784 | requests_.Clear(); |
| 1785 | receiving_ = false; |
| 1786 | write_state_ = STATE_WRITE_INIT; |
| 1787 | rtt_estimate_.Reset(); |
| 1788 | pings_since_last_response_.clear(); |
| 1789 | } |
| 1790 |
| 1791 | ProxyConnection::ProxyConnection(rtc::WeakPtr<PortInterface> port, |
| 1792 | size_t index, |
| 1793 | const Candidate& remote_candidate) |
| 1794 | : Connection(std::move(port), index, remote_candidate) {} |
| 1795 |
| 1796 | int ProxyConnection::Send(const void* data, |
| 1797 | size_t size, |
| 1798 | const rtc::PacketOptions& options) { |
| 1799 | RTC_DCHECK(port_) << ToDebugId() << ": port_ null in Send()"; |
| 1800 | if (!port_) |
| 1801 | return SOCKET_ERROR; |
| 1802 |
| 1803 | stats_.sent_total_packets++; |
| 1804 | int sent = |
| 1805 | port_->SendTo(data, size, remote_candidate_.address(), options, true); |
| 1806 | int64_t now = rtc::TimeMillis(); |
| 1807 | if (sent <= 0) { |
| 1808 | RTC_DCHECK(sent < 0); |
| 1809 | error_ = port_->GetError(); |
| 1810 | stats_.sent_discarded_packets++; |
| 1811 | stats_.sent_discarded_bytes += size; |
| 1812 | } else { |
| 1813 | send_rate_tracker_.AddSamplesAtTime(now, sent); |
| 1814 | } |
| 1815 | last_send_data_ = now; |
| 1816 | return sent; |
| 1817 | } |
| 1818 |
| 1819 | int ProxyConnection::GetError() { |
| 1820 | return error_; |
| 1821 | } |
| 1822 |
| 1823 | } // namespace cricket |
| 1824 |