| 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/port.h" |
| 12 |
| 13 | #include <cstddef> |
| 14 | #include <cstdint> |
| 15 | #include <memory> |
| 16 | #include <utility> |
| 17 | #include <vector> |
| 18 |
| 19 | #include "absl/memory/memory.h" |
| 20 | #include "absl/strings/match.h" |
| 21 | #include "absl/strings/string_view.h" |
| 22 | #include "api/array_view.h" |
| 23 | #include "api/rtc_error.h" |
| 24 | #include "api/units/time_delta.h" |
| 25 | #include "p2p/base/p2p_constants.h" |
| 26 | #include "p2p/base/stun_request.h" |
| 27 | #include "rtc_base/byte_buffer.h" |
| 28 | #include "rtc_base/checks.h" |
| 29 | #include "rtc_base/crc32.h" |
| 30 | #include "rtc_base/helpers.h" |
| 31 | #include "rtc_base/ip_address.h" |
| 32 | #include "rtc_base/logging.h" |
| 33 | #include "rtc_base/mdns_responder_interface.h" |
| 34 | #include "rtc_base/net_helper.h" |
| 35 | #include "rtc_base/network.h" |
| 36 | #include "rtc_base/socket_address.h" |
| 37 | #include "rtc_base/string_encode.h" |
| 38 | #include "rtc_base/string_utils.h" |
| 39 | #include "rtc_base/strings/string_builder.h" |
| 40 | #include "rtc_base/time_utils.h" |
| 41 | #include "rtc_base/trace_event.h" |
| 42 |
| 43 | namespace cricket { |
| 44 | namespace { |
| 45 |
| 46 | using ::webrtc::RTCError; |
| 47 | using ::webrtc::RTCErrorType; |
| 48 | using ::webrtc::TaskQueueBase; |
| 49 | using ::webrtc::TimeDelta; |
| 50 |
| 51 | rtc::PacketInfoProtocolType ConvertProtocolTypeToPacketInfoProtocolType( |
| 52 | cricket::ProtocolType type) { |
| 53 | switch (type) { |
| 54 | case cricket::ProtocolType::PROTO_UDP: |
| 55 | return rtc::PacketInfoProtocolType::kUdp; |
| 56 | case cricket::ProtocolType::PROTO_TCP: |
| 57 | return rtc::PacketInfoProtocolType::kTcp; |
| 58 | case cricket::ProtocolType::PROTO_SSLTCP: |
| 59 | return rtc::PacketInfoProtocolType::kSsltcp; |
| 60 | case cricket::ProtocolType::PROTO_TLS: |
| 61 | return rtc::PacketInfoProtocolType::kTls; |
| 62 | default: |
| 63 | return rtc::PacketInfoProtocolType::kUnknown; |
| 64 | } |
| 65 | } |
| 66 |
| 67 | // The delay before we begin checking if this port is useless. We set |
| 68 | // it to a little higher than a total STUN timeout. |
| 69 | const int kPortTimeoutDelay = cricket::STUN_TOTAL_TIMEOUT + 5000; |
| 70 |
| 71 | } // namespace |
| 72 |
| 73 | static const char* const PROTO_NAMES[] = {UDP_PROTOCOL_NAME, TCP_PROTOCOL_NAME, |
| 74 | SSLTCP_PROTOCOL_NAME, |
| 75 | TLS_PROTOCOL_NAME}; |
| 76 |
| 77 | const char* ProtoToString(ProtocolType proto) { |
| 78 | return PROTO_NAMES[proto]; |
| 79 | } |
| 80 |
| 81 | absl::optional<ProtocolType> StringToProto(absl::string_view proto_name) { |
| 82 | for (size_t i = 0; i <= PROTO_LAST; ++i) { |
| 83 | if (absl::EqualsIgnoreCase(PROTO_NAMES[i], proto_name)) { |
| 84 | return static_cast<ProtocolType>(i); |
| 85 | } |
| 86 | } |
| 87 | return absl::nullopt; |
| 88 | } |
| 89 |
| 90 | // RFC 6544, TCP candidate encoding rules. |
| 91 | const int DISCARD_PORT = 9; |
| 92 | const char TCPTYPE_ACTIVE_STR[] = "active"; |
| 93 | const char TCPTYPE_PASSIVE_STR[] = "passive"; |
| 94 | const char TCPTYPE_SIMOPEN_STR[] = "so"; |
| 95 |
| 96 | std::string Port::ComputeFoundation(absl::string_view type, |
| 97 | absl::string_view protocol, |
| 98 | absl::string_view relay_protocol, |
| 99 | const rtc::SocketAddress& base_address) { |
| 100 | // TODO(bugs.webrtc.org/14605): ensure IceTiebreaker() is set. |
| 101 | rtc::StringBuilder sb; |
| 102 | sb << type << base_address.ipaddr().ToString() << protocol << relay_protocol |
| 103 | << rtc::ToString(IceTiebreaker()); |
| 104 | return rtc::ToString(rtc::ComputeCrc32(sb.Release())); |
| 105 | } |
| 106 |
| 107 | Port::Port(TaskQueueBase* thread, |
| 108 | absl::string_view type, |
| 109 | rtc::PacketSocketFactory* factory, |
| 110 | const rtc::Network* network, |
| 111 | absl::string_view username_fragment, |
| 112 | absl::string_view password, |
| 113 | const webrtc::FieldTrialsView* field_trials) |
| 114 | : thread_(thread), |
| 115 | factory_(factory), |
| 116 | type_(type), |
| 117 | send_retransmit_count_attribute_(false), |
| 118 | network_(network), |
| 119 | min_port_(0), |
| 120 | max_port_(0), |
| 121 | component_(ICE_CANDIDATE_COMPONENT_DEFAULT), |
| 122 | generation_(0), |
| 123 | ice_username_fragment_(username_fragment), |
| 124 | password_(password), |
| 125 | timeout_delay_(kPortTimeoutDelay), |
| 126 | enable_port_packets_(false), |
| 127 | ice_role_(ICEROLE_UNKNOWN), |
| 128 | tiebreaker_(0), |
| 129 | shared_socket_(true), |
| 130 | weak_factory_(this), |
| 131 | field_trials_(field_trials) { |
| 132 | RTC_DCHECK(factory_ != NULL); |
| 133 | Construct(); |
| 134 | } |
| 135 |
| 136 | Port::Port(TaskQueueBase* thread, |
| 137 | absl::string_view type, |
| 138 | rtc::PacketSocketFactory* factory, |
| 139 | const rtc::Network* network, |
| 140 | uint16_t min_port, |
| 141 | uint16_t max_port, |
| 142 | absl::string_view username_fragment, |
| 143 | absl::string_view password, |
| 144 | const webrtc::FieldTrialsView* field_trials) |
| 145 | : thread_(thread), |
| 146 | factory_(factory), |
| 147 | type_(type), |
| 148 | send_retransmit_count_attribute_(false), |
| 149 | network_(network), |
| 150 | min_port_(min_port), |
| 151 | max_port_(max_port), |
| 152 | component_(ICE_CANDIDATE_COMPONENT_DEFAULT), |
| 153 | generation_(0), |
| 154 | ice_username_fragment_(username_fragment), |
| 155 | password_(password), |
| 156 | timeout_delay_(kPortTimeoutDelay), |
| 157 | enable_port_packets_(false), |
| 158 | ice_role_(ICEROLE_UNKNOWN), |
| 159 | tiebreaker_(0), |
| 160 | shared_socket_(false), |
| 161 | weak_factory_(this), |
| 162 | field_trials_(field_trials) { |
| 163 | RTC_DCHECK(factory_ != NULL); |
| 164 | Construct(); |
| 165 | } |
| 166 |
| 167 | void Port::Construct() { |
| 168 | RTC_DCHECK_RUN_ON(thread_); |
| 169 | // TODO(pthatcher): Remove this old behavior once we're sure no one |
| 170 | // relies on it. If the username_fragment and password are empty, |
| 171 | // we should just create one. |
| 172 | if (ice_username_fragment_.empty()) { |
| 173 | RTC_DCHECK(password_.empty()); |
| 174 | ice_username_fragment_ = rtc::CreateRandomString(ICE_UFRAG_LENGTH); |
| 175 | password_ = rtc::CreateRandomString(ICE_PWD_LENGTH); |
| 176 | } |
| 177 | network_->SignalTypeChanged.connect(this, &Port::OnNetworkTypeChanged); |
| 178 | network_cost_ = network_->GetCost(field_trials()); |
| 179 |
| 180 | PostDestroyIfDead(/*delayed=*/true); |
| 181 | RTC_LOG(LS_INFO) << ToString() << ": Port created with network cost " |
| 182 | << network_cost_; |
| 183 | } |
| 184 |
| 185 | Port::~Port() { |
| 186 | RTC_DCHECK_RUN_ON(thread_); |
| 187 | DestroyAllConnections(); |
| 188 | CancelPendingTasks(); |
| 189 | } |
| 190 |
| 191 | const absl::string_view Port::Type() const { |
| 192 | return type_; |
| 193 | } |
| 194 | const rtc::Network* Port::Network() const { |
| 195 | return network_; |
| 196 | } |
| 197 |
| 198 | IceRole Port::GetIceRole() const { |
| 199 | return ice_role_; |
| 200 | } |
| 201 |
| 202 | void Port::SetIceRole(IceRole role) { |
| 203 | ice_role_ = role; |
| 204 | } |
| 205 |
| 206 | void Port::SetIceTiebreaker(uint64_t tiebreaker) { |
| 207 | tiebreaker_ = tiebreaker; |
| 208 | } |
| 209 |
| 210 | uint64_t Port::IceTiebreaker() const { |
| 211 | return tiebreaker_; |
| 212 | } |
| 213 |
| 214 | bool Port::SharedSocket() const { |
| 215 | return shared_socket_; |
| 216 | } |
| 217 |
| 218 | void Port::SetIceParameters(int component, |
| 219 | absl::string_view username_fragment, |
| 220 | absl::string_view password) { |
| 221 | RTC_DCHECK_RUN_ON(thread_); |
| 222 | component_ = component; |
| 223 | ice_username_fragment_ = std::string(username_fragment); |
| 224 | password_ = std::string(password); |
| 225 | for (Candidate& c : candidates_) { |
| 226 | c.set_component(component); |
| 227 | c.set_username(username_fragment); |
| 228 | c.set_password(password); |
| 229 | } |
| 230 |
| 231 | // In case any connections exist make sure we update them too. |
| 232 | for (auto& [unused, connection] : connections_) { |
| 233 | connection->UpdateLocalIceParameters(component, username_fragment, |
| 234 | password); |
| 235 | } |
| 236 | } |
| 237 |
| 238 | const std::vector<Candidate>& Port::Candidates() const { |
| 239 | return candidates_; |
| 240 | } |
| 241 |
| 242 | Connection* Port::GetConnection(const rtc::SocketAddress& remote_addr) { |
| 243 | AddressMap::const_iterator iter = connections_.find(remote_addr); |
| 244 | if (iter != connections_.end()) |
| 245 | return iter->second; |
| 246 | else |
| 247 | return NULL; |
| 248 | } |
| 249 |
| 250 | void Port::AddAddress(const rtc::SocketAddress& address, |
| 251 | const rtc::SocketAddress& base_address, |
| 252 | const rtc::SocketAddress& related_address, |
| 253 | absl::string_view protocol, |
| 254 | absl::string_view relay_protocol, |
| 255 | absl::string_view tcptype, |
| 256 | absl::string_view type, |
| 257 | uint32_t type_preference, |
| 258 | uint32_t relay_preference, |
| 259 | absl::string_view url, |
| 260 | bool is_final) { |
| 261 | RTC_DCHECK_RUN_ON(thread_); |
| 262 |
| 263 | std::string foundation = |
| 264 | ComputeFoundation(type, protocol, relay_protocol, base_address); |
| 265 | Candidate c(component_, protocol, address, 0U, username_fragment(), password_, |
| 266 | type, generation_, foundation, network_->id(), network_cost_); |
| 267 |
| 268 | #if RTC_DCHECK_IS_ON |
| 269 | if (protocol == TCP_PROTOCOL_NAME && c.is_local()) { |
| 270 | RTC_DCHECK(!tcptype.empty()); |
| 271 | } |
| 272 | #endif |
| 273 |
| 274 | c.set_relay_protocol(relay_protocol); |
| 275 | c.set_priority( |
| 276 | c.GetPriority(type_preference, network_->preference(), relay_preference, |
| 277 | field_trials_->IsEnabled( |
| 278 | "WebRTC-IncreaseIceCandidatePriorityHostSrflx"))); |
| 279 | c.set_tcptype(tcptype); |
| 280 | c.set_network_name(network_->name()); |
| 281 | c.set_network_type(network_->type()); |
| 282 | c.set_underlying_type_for_vpn(network_->underlying_type_for_vpn()); |
| 283 | c.set_url(url); |
| 284 | c.set_related_address(related_address); |
| 285 |
| 286 | bool pending = MaybeObfuscateAddress(c, is_final); |
| 287 |
| 288 | if (!pending) { |
| 289 | FinishAddingAddress(c, is_final); |
| 290 | } |
| 291 | } |
| 292 |
| 293 | bool Port::MaybeObfuscateAddress(const Candidate& c, bool is_final) { |
| 294 | // TODO(bugs.webrtc.org/9723): Use a config to control the feature of IP |
| 295 | // handling with mDNS. |
| 296 | if (network_->GetMdnsResponder() == nullptr) { |
| 297 | return false; |
| 298 | } |
| 299 | if (!c.is_local()) { |
| 300 | return false; |
| 301 | } |
| 302 |
| 303 | auto copy = c; |
| 304 | auto weak_ptr = weak_factory_.GetWeakPtr(); |
| 305 | auto callback = [weak_ptr, copy, is_final](const rtc::IPAddress& addr, |
| 306 | absl::string_view name) mutable { |
| 307 | RTC_DCHECK(copy.address().ipaddr() == addr); |
| 308 | rtc::SocketAddress hostname_address(name, copy.address().port()); |
| 309 | // In Port and Connection, we need the IP address information to |
| 310 | // correctly handle the update of candidate type to prflx. The removal |
| 311 | // of IP address when signaling this candidate will take place in |
| 312 | // BasicPortAllocatorSession::OnCandidateReady, via SanitizeCandidate. |
| 313 | hostname_address.SetResolvedIP(addr); |
| 314 | copy.set_address(hostname_address); |
| 315 | copy.set_related_address(rtc::SocketAddress()); |
| 316 | if (weak_ptr != nullptr) { |
| 317 | RTC_DCHECK_RUN_ON(weak_ptr->thread_); |
| 318 | weak_ptr->set_mdns_name_registration_status( |
| 319 | MdnsNameRegistrationStatus::kCompleted); |
| 320 | weak_ptr->FinishAddingAddress(copy, is_final); |
| 321 | } |
| 322 | }; |
| 323 | set_mdns_name_registration_status(MdnsNameRegistrationStatus::kInProgress); |
| 324 | network_->GetMdnsResponder()->CreateNameForAddress(copy.address().ipaddr(), |
| 325 | callback); |
| 326 | return true; |
| 327 | } |
| 328 |
| 329 | void Port::FinishAddingAddress(const Candidate& c, bool is_final) { |
| 330 | candidates_.push_back(c); |
| 331 | SignalCandidateReady(this, c); |
| 332 |
| 333 | PostAddAddress(is_final); |
| 334 | } |
| 335 |
| 336 | void Port::PostAddAddress(bool is_final) { |
| 337 | if (is_final) { |
| 338 | SignalPortComplete(this); |
| 339 | } |
| 340 | } |
| 341 |
| 342 | void Port::AddOrReplaceConnection(Connection* conn) { |
| 343 | auto ret = connections_.insert( |
| 344 | std::make_pair(conn->remote_candidate().address(), conn)); |
| 345 | // If there is a different connection on the same remote address, replace |
| 346 | // it with the new one and destroy the old one. |
| 347 | if (ret.second == false && ret.first->second != conn) { |
| 348 | RTC_LOG(LS_WARNING) |
| 349 | << ToString() |
| 350 | << ": A new connection was created on an existing remote address. " |
| 351 | "New remote candidate: " |
| 352 | << conn->remote_candidate().ToSensitiveString(); |
| 353 | std::unique_ptr<Connection> old_conn = absl::WrapUnique(ret.first->second); |
| 354 | ret.first->second = conn; |
| 355 | HandleConnectionDestroyed(old_conn.get()); |
| 356 | old_conn->Shutdown(); |
| 357 | } |
| 358 | } |
| 359 |
| 360 | void Port::OnReadPacket(const rtc::ReceivedPacket& packet, ProtocolType proto) { |
| 361 | const char* data = reinterpret_cast<const char*>(packet.payload().data()); |
| 362 | size_t size = packet.payload().size(); |
| 363 | const rtc::SocketAddress& addr = packet.source_address(); |
| 364 | // If the user has enabled port packets, just hand this over. |
| 365 | if (enable_port_packets_) { |
| 366 | SignalReadPacket(this, data, size, addr); |
| 367 | return; |
| 368 | } |
| 369 |
| 370 | // If this is an authenticated STUN request, then signal unknown address and |
| 371 | // send back a proper binding response. |
| 372 | std::unique_ptr<IceMessage> msg; |
| 373 | std::string remote_username; |
| 374 | if (!GetStunMessage(data, size, addr, &msg, &remote_username)) { |
| 375 | RTC_LOG(LS_ERROR) << ToString() |
| 376 | << ": Received non-STUN packet from unknown address: " |
| 377 | << addr.ToSensitiveString(); |
| 378 | } else if (!msg) { |
| 379 | // STUN message handled already |
| 380 | } else if (msg->type() == STUN_BINDING_REQUEST) { |
| 381 | RTC_LOG(LS_INFO) << "Received " << StunMethodToString(msg->type()) |
| 382 | << " id=" << rtc::hex_encode(msg->transaction_id()) |
| 383 | << " from unknown address " << addr.ToSensitiveString(); |
| 384 | // We need to signal an unknown address before we handle any role conflict |
| 385 | // below. Otherwise there would be no candidate pair and TURN entry created |
| 386 | // to send the error response in case of a role conflict. |
| 387 | SignalUnknownAddress(this, addr, proto, msg.get(), remote_username, false); |
| 388 | // Check for role conflicts. |
| 389 | if (!MaybeIceRoleConflict(addr, msg.get(), remote_username)) { |
| 390 | RTC_LOG(LS_INFO) << "Received conflicting role from the peer."; |
| 391 | return; |
| 392 | } |
| 393 | } else if (msg->type() == GOOG_PING_REQUEST) { |
| 394 | // This is a PING sent to a connection that was destroyed. |
| 395 | // Send back that this is the case and a authenticated BINDING |
| 396 | // is needed. |
| 397 | SendBindingErrorResponse(msg.get(), addr, STUN_ERROR_BAD_REQUEST, |
| 398 | STUN_ERROR_REASON_BAD_REQUEST); |
| 399 | } else { |
| 400 | // NOTE(tschmelcher): STUN_BINDING_RESPONSE is benign. It occurs if we |
| 401 | // pruned a connection for this port while it had STUN requests in flight, |
| 402 | // because we then get back responses for them, which this code correctly |
| 403 | // does not handle. |
| 404 | if (msg->type() != STUN_BINDING_RESPONSE && |
| 405 | msg->type() != GOOG_PING_RESPONSE && |
| 406 | msg->type() != GOOG_PING_ERROR_RESPONSE) { |
| 407 | RTC_LOG(LS_ERROR) << ToString() |
| 408 | << ": Received unexpected STUN message type: " |
| 409 | << msg->type() << " from unknown address: " |
| 410 | << addr.ToSensitiveString(); |
| 411 | } |
| 412 | } |
| 413 | } |
| 414 |
| 415 | void Port::OnReadyToSend() { |
| 416 | AddressMap::iterator iter = connections_.begin(); |
| 417 | for (; iter != connections_.end(); ++iter) { |
| 418 | iter->second->OnReadyToSend(); |
| 419 | } |
| 420 | } |
| 421 |
| 422 | void Port::AddPrflxCandidate(const Candidate& local) { |
| 423 | RTC_DCHECK_RUN_ON(thread_); |
| 424 | candidates_.push_back(local); |
| 425 | } |
| 426 |
| 427 | bool Port::GetStunMessage(const char* data, |
| 428 | size_t size, |
| 429 | const rtc::SocketAddress& addr, |
| 430 | std::unique_ptr<IceMessage>* out_msg, |
| 431 | std::string* out_username) { |
| 432 | RTC_DCHECK_RUN_ON(thread_); |
| 433 | // NOTE: This could clearly be optimized to avoid allocating any memory. |
| 434 | // However, at the data rates we'll be looking at on the client side, |
| 435 | // this probably isn't worth worrying about. |
| 436 | RTC_DCHECK(out_msg != NULL); |
| 437 | RTC_DCHECK(out_username != NULL); |
| 438 | out_username->clear(); |
| 439 |
| 440 | // Don't bother parsing the packet if we can tell it's not STUN. |
| 441 | // In ICE mode, all STUN packets will have a valid fingerprint. |
| 442 | // Except GOOG_PING_REQUEST/RESPONSE that does not send fingerprint. |
| 443 | int types[] = {GOOG_PING_REQUEST, GOOG_PING_RESPONSE, |
| 444 | GOOG_PING_ERROR_RESPONSE}; |
| 445 | if (!StunMessage::IsStunMethod(types, data, size) && |
| 446 | !StunMessage::ValidateFingerprint(data, size)) { |
| 447 | return false; |
| 448 | } |
| 449 |
| 450 | // Parse the request message. If the packet is not a complete and correct |
| 451 | // STUN message, then ignore it. |
| 452 | std::unique_ptr<IceMessage> stun_msg(new IceMessage()); |
| 453 | rtc::ByteBufferReader buf( |
| 454 | rtc::MakeArrayView(reinterpret_cast<const uint8_t*>(data), size)); |
| 455 | if (!stun_msg->Read(&buf) || (buf.Length() > 0)) { |
| 456 | return false; |
| 457 | } |
| 458 |
| 459 | // Get list of attributes in the "comprehension-required" range that were not |
| 460 | // comprehended. If one or more is found, the behavior differs based on the |
| 461 | // type of the incoming message; see below. |
| 462 | std::vector<uint16_t> unknown_attributes = |
| 463 | stun_msg->GetNonComprehendedAttributes(); |
| 464 |
| 465 | if (stun_msg->type() == STUN_BINDING_REQUEST) { |
| 466 | // Check for the presence of USERNAME and MESSAGE-INTEGRITY (if ICE) first. |
| 467 | // If not present, fail with a 400 Bad Request. |
| 468 | if (!stun_msg->GetByteString(STUN_ATTR_USERNAME) || |
| 469 | !stun_msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY)) { |
| 470 | RTC_LOG(LS_ERROR) << ToString() << ": Received " |
| 471 | << StunMethodToString(stun_msg->type()) |
| 472 | << " without username/M-I from: " |
| 473 | << addr.ToSensitiveString(); |
| 474 | SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_BAD_REQUEST, |
| 475 | STUN_ERROR_REASON_BAD_REQUEST); |
| 476 | return true; |
| 477 | } |
| 478 |
| 479 | // If the username is bad or unknown, fail with a 401 Unauthorized. |
| 480 | std::string local_ufrag; |
| 481 | std::string remote_ufrag; |
| 482 | if (!ParseStunUsername(stun_msg.get(), &local_ufrag, &remote_ufrag) || |
| 483 | local_ufrag != username_fragment()) { |
| 484 | RTC_LOG(LS_ERROR) << ToString() << ": Received " |
| 485 | << StunMethodToString(stun_msg->type()) |
| 486 | << " with bad local username " << local_ufrag |
| 487 | << " from " << addr.ToSensitiveString(); |
| 488 | SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED, |
| 489 | STUN_ERROR_REASON_UNAUTHORIZED); |
| 490 | return true; |
| 491 | } |
| 492 |
| 493 | // If ICE, and the MESSAGE-INTEGRITY is bad, fail with a 401 Unauthorized |
| 494 | if (stun_msg->ValidateMessageIntegrity(password_) != |
| 495 | StunMessage::IntegrityStatus::kIntegrityOk) { |
| 496 | RTC_LOG(LS_ERROR) << ToString() << ": Received " |
| 497 | << StunMethodToString(stun_msg->type()) |
| 498 | << " with bad M-I from " << addr.ToSensitiveString() |
| 499 | << ", password_=" << password_; |
| 500 | SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED, |
| 501 | STUN_ERROR_REASON_UNAUTHORIZED); |
| 502 | return true; |
| 503 | } |
| 504 |
| 505 | // If a request contains unknown comprehension-required attributes, reply |
| 506 | // with an error. See RFC5389 section 7.3.1. |
| 507 | if (!unknown_attributes.empty()) { |
| 508 | SendUnknownAttributesErrorResponse(stun_msg.get(), addr, |
| 509 | unknown_attributes); |
| 510 | return true; |
| 511 | } |
| 512 |
| 513 | out_username->assign(remote_ufrag); |
| 514 | } else if ((stun_msg->type() == STUN_BINDING_RESPONSE) || |
| 515 | (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE)) { |
| 516 | if (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE) { |
| 517 | if (const StunErrorCodeAttribute* error_code = stun_msg->GetErrorCode()) { |
| 518 | RTC_LOG(LS_ERROR) << ToString() << ": Received " |
| 519 | << StunMethodToString(stun_msg->type()) |
| 520 | << ": class=" << error_code->eclass() |
| 521 | << " number=" << error_code->number() << " reason='" |
| 522 | << error_code->reason() << "' from " |
| 523 | << addr.ToSensitiveString(); |
| 524 | // Return message to allow error-specific processing |
| 525 | } else { |
| 526 | RTC_LOG(LS_ERROR) << ToString() << ": Received " |
| 527 | << StunMethodToString(stun_msg->type()) |
| 528 | << " without a error code from " |
| 529 | << addr.ToSensitiveString(); |
| 530 | return true; |
| 531 | } |
| 532 | } |
| 533 | // If a response contains unknown comprehension-required attributes, it's |
| 534 | // simply discarded and the transaction is considered failed. See RFC5389 |
| 535 | // sections 7.3.3 and 7.3.4. |
| 536 | if (!unknown_attributes.empty()) { |
| 537 | RTC_LOG(LS_ERROR) << ToString() |
| 538 | << ": Discarding STUN response due to unknown " |
| 539 | "comprehension-required attribute"; |
| 540 | return true; |
| 541 | } |
| 542 | // NOTE: Username should not be used in verifying response messages. |
| 543 | out_username->clear(); |
| 544 | } else if (stun_msg->type() == STUN_BINDING_INDICATION) { |
| 545 | RTC_LOG(LS_VERBOSE) << ToString() << ": Received " |
| 546 | << StunMethodToString(stun_msg->type()) << ": from " |
| 547 | << addr.ToSensitiveString(); |
| 548 | out_username->clear(); |
| 549 |
| 550 | // If an indication contains unknown comprehension-required attributes,[] |
| 551 | // it's simply discarded. See RFC5389 section 7.3.2. |
| 552 | if (!unknown_attributes.empty()) { |
| 553 | RTC_LOG(LS_ERROR) << ToString() |
| 554 | << ": Discarding STUN indication due to " |
| 555 | "unknown comprehension-required attribute"; |
| 556 | return true; |
| 557 | } |
| 558 | // No stun attributes will be verified, if it's stun indication message. |
| 559 | // Returning from end of the this method. |
| 560 | } else if (stun_msg->type() == GOOG_PING_REQUEST) { |
| 561 | if (stun_msg->ValidateMessageIntegrity(password_) != |
| 562 | StunMessage::IntegrityStatus::kIntegrityOk) { |
| 563 | RTC_LOG(LS_ERROR) << ToString() << ": Received " |
| 564 | << StunMethodToString(stun_msg->type()) |
| 565 | << " with bad M-I from " << addr.ToSensitiveString() |
| 566 | << ", password_=" << password_; |
| 567 | SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED, |
| 568 | STUN_ERROR_REASON_UNAUTHORIZED); |
| 569 | return true; |
| 570 | } |
| 571 | RTC_LOG(LS_VERBOSE) << ToString() << ": Received " |
| 572 | << StunMethodToString(stun_msg->type()) << " from " |
| 573 | << addr.ToSensitiveString(); |
| 574 | out_username->clear(); |
| 575 | } else if (stun_msg->type() == GOOG_PING_RESPONSE || |
| 576 | stun_msg->type() == GOOG_PING_ERROR_RESPONSE) { |
| 577 | // note: the MessageIntegrity32 will be verified in Connection.cc |
| 578 | RTC_LOG(LS_VERBOSE) << ToString() << ": Received " |
| 579 | << StunMethodToString(stun_msg->type()) << " from " |
| 580 | << addr.ToSensitiveString(); |
| 581 | out_username->clear(); |
| 582 | } else { |
| 583 | RTC_LOG(LS_ERROR) << ToString() |
| 584 | << ": Received STUN packet with invalid type (" |
| 585 | << stun_msg->type() << ") from " |
| 586 | << addr.ToSensitiveString(); |
| 587 | return true; |
| 588 | } |
| 589 |
| 590 | // Return the STUN message found. |
| 591 | *out_msg = std::move(stun_msg); |
| 592 | return true; |
| 593 | } |
| 594 |
| 595 | bool Port::IsCompatibleAddress(const rtc::SocketAddress& addr) { |
| 596 | // Get a representative IP for the Network this port is configured to use. |
| 597 | rtc::IPAddress ip = network_->GetBestIP(); |
| 598 | // We use single-stack sockets, so families must match. |
| 599 | if (addr.family() != ip.family()) { |
| 600 | return false; |
| 601 | } |
| 602 | // Link-local IPv6 ports can only connect to other link-local IPv6 ports. |
| 603 | if (ip.family() == AF_INET6 && |
| 604 | (IPIsLinkLocal(ip) != IPIsLinkLocal(addr.ipaddr()))) { |
| 605 | return false; |
| 606 | } |
| 607 | return true; |
| 608 | } |
| 609 |
| 610 | rtc::DiffServCodePoint Port::StunDscpValue() const { |
| 611 | // By default, inherit from whatever the MediaChannel sends. |
| 612 | return rtc::DSCP_NO_CHANGE; |
| 613 | } |
| 614 |
| 615 | void Port::DestroyAllConnections() { |
| 616 | RTC_DCHECK_RUN_ON(thread_); |
| 617 | for (auto& [unused, connection] : connections_) { |
| 618 | connection->Shutdown(); |
| 619 | delete connection; |
| 620 | } |
| 621 | connections_.clear(); |
| 622 | } |
| 623 |
| 624 | void Port::set_timeout_delay(int delay) { |
| 625 | RTC_DCHECK_RUN_ON(thread_); |
| 626 | // Although this method is meant to only be used by tests, some downstream |
| 627 | // projects have started using it. Ideally we should update our tests to not |
| 628 | // require to modify this state and instead use a testing harness that allows |
| 629 | // adjusting the clock and then just use the kPortTimeoutDelay constant |
| 630 | // directly. |
| 631 | timeout_delay_ = delay; |
| 632 | } |
| 633 |
| 634 | bool Port::ParseStunUsername(const StunMessage* stun_msg, |
| 635 | std::string* local_ufrag, |
| 636 | std::string* remote_ufrag) const { |
| 637 | // The packet must include a username that either begins or ends with our |
| 638 | // fragment. It should begin with our fragment if it is a request and it |
| 639 | // should end with our fragment if it is a response. |
| 640 | local_ufrag->clear(); |
| 641 | remote_ufrag->clear(); |
| 642 | const StunByteStringAttribute* username_attr = |
| 643 | stun_msg->GetByteString(STUN_ATTR_USERNAME); |
| 644 | if (username_attr == NULL) |
| 645 | return false; |
| 646 |
| 647 | // RFRAG:LFRAG |
| 648 | const absl::string_view username = username_attr->string_view(); |
| 649 | size_t colon_pos = username.find(':'); |
| 650 | if (colon_pos == absl::string_view::npos) { |
| 651 | return false; |
| 652 | } |
| 653 |
| 654 | *local_ufrag = std::string(username.substr(0, colon_pos)); |
| 655 | *remote_ufrag = std::string(username.substr(colon_pos + 1, username.size())); |
| 656 | return true; |
| 657 | } |
| 658 |
| 659 | bool Port::MaybeIceRoleConflict(const rtc::SocketAddress& addr, |
| 660 | IceMessage* stun_msg, |
| 661 | absl::string_view remote_ufrag) { |
| 662 | RTC_DCHECK_RUN_ON(thread_); |
| 663 | // Validate ICE_CONTROLLING or ICE_CONTROLLED attributes. |
| 664 | bool ret = true; |
| 665 | IceRole remote_ice_role = ICEROLE_UNKNOWN; |
| 666 | uint64_t remote_tiebreaker = 0; |
| 667 | const StunUInt64Attribute* stun_attr = |
| 668 | stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING); |
| 669 | if (stun_attr) { |
| 670 | remote_ice_role = ICEROLE_CONTROLLING; |
| 671 | remote_tiebreaker = stun_attr->value(); |
| 672 | } |
| 673 |
| 674 | // If `remote_ufrag` is same as port local username fragment and |
| 675 | // tie breaker value received in the ping message matches port |
| 676 | // tiebreaker value this must be a loopback call. |
| 677 | // We will treat this as valid scenario. |
| 678 | if (remote_ice_role == ICEROLE_CONTROLLING && |
| 679 | username_fragment() == remote_ufrag && |
| 680 | remote_tiebreaker == IceTiebreaker()) { |
| 681 | return true; |
| 682 | } |
| 683 |
| 684 | stun_attr = stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED); |
| 685 | if (stun_attr) { |
| 686 | remote_ice_role = ICEROLE_CONTROLLED; |
| 687 | remote_tiebreaker = stun_attr->value(); |
| 688 | } |
| 689 |
| 690 | switch (ice_role_) { |
| 691 | case ICEROLE_CONTROLLING: |
| 692 | if (ICEROLE_CONTROLLING == remote_ice_role) { |
| 693 | if (remote_tiebreaker >= tiebreaker_) { |
| 694 | SignalRoleConflict(this); |
| 695 | } else { |
| 696 | // Send Role Conflict (487) error response. |
| 697 | SendBindingErrorResponse(stun_msg, addr, STUN_ERROR_ROLE_CONFLICT, |
| 698 | STUN_ERROR_REASON_ROLE_CONFLICT); |
| 699 | ret = false; |
| 700 | } |
| 701 | } |
| 702 | break; |
| 703 | case ICEROLE_CONTROLLED: |
| 704 | if (ICEROLE_CONTROLLED == remote_ice_role) { |
| 705 | if (remote_tiebreaker < tiebreaker_) { |
| 706 | SignalRoleConflict(this); |
| 707 | } else { |
| 708 | // Send Role Conflict (487) error response. |
| 709 | SendBindingErrorResponse(stun_msg, addr, STUN_ERROR_ROLE_CONFLICT, |
| 710 | STUN_ERROR_REASON_ROLE_CONFLICT); |
| 711 | ret = false; |
| 712 | } |
| 713 | } |
| 714 | break; |
| 715 | default: |
| 716 | RTC_DCHECK_NOTREACHED(); |
| 717 | } |
| 718 | return ret; |
| 719 | } |
| 720 |
| 721 | std::string Port::CreateStunUsername(absl::string_view remote_username) const { |
| 722 | RTC_DCHECK_RUN_ON(thread_); |
| 723 | return std::string(remote_username) + ":" + username_fragment(); |
| 724 | } |
| 725 |
| 726 | bool Port::HandleIncomingPacket(rtc::AsyncPacketSocket* socket, |
| 727 | const rtc::ReceivedPacket& packet) { |
| 728 | RTC_DCHECK_NOTREACHED(); |
| 729 | return false; |
| 730 | } |
| 731 |
| 732 | bool Port::CanHandleIncomingPacketsFrom(const rtc::SocketAddress&) const { |
| 733 | return false; |
| 734 | } |
| 735 |
| 736 | void Port::SendBindingErrorResponse(StunMessage* message, |
| 737 | const rtc::SocketAddress& addr, |
| 738 | int error_code, |
| 739 | absl::string_view reason) { |
| 740 | RTC_DCHECK_RUN_ON(thread_); |
| 741 | RTC_DCHECK(message->type() == STUN_BINDING_REQUEST || |
| 742 | message->type() == GOOG_PING_REQUEST); |
| 743 |
| 744 | // Fill in the response message. |
| 745 | StunMessage response(message->type() == STUN_BINDING_REQUEST |
| 746 | ? STUN_BINDING_ERROR_RESPONSE |
| 747 | : GOOG_PING_ERROR_RESPONSE, |
| 748 | message->transaction_id()); |
| 749 |
| 750 | // When doing GICE, we need to write out the error code incorrectly to |
| 751 | // maintain backwards compatiblility. |
| 752 | auto error_attr = StunAttribute::CreateErrorCode(); |
| 753 | error_attr->SetCode(error_code); |
| 754 | error_attr->SetReason(std::string(reason)); |
| 755 | response.AddAttribute(std::move(error_attr)); |
| 756 |
| 757 | // Per Section 10.1.2, certain error cases don't get a MESSAGE-INTEGRITY, |
| 758 | // because we don't have enough information to determine the shared secret. |
| 759 | if (error_code != STUN_ERROR_BAD_REQUEST && |
| 760 | error_code != STUN_ERROR_UNAUTHORIZED && |
| 761 | message->type() != GOOG_PING_REQUEST) { |
| 762 | if (message->type() == STUN_BINDING_REQUEST) { |
| 763 | response.AddMessageIntegrity(password_); |
| 764 | } else { |
| 765 | response.AddMessageIntegrity32(password_); |
| 766 | } |
| 767 | } |
| 768 |
| 769 | if (message->type() == STUN_BINDING_REQUEST) { |
| 770 | response.AddFingerprint(); |
| 771 | } |
| 772 |
| 773 | // Send the response message. |
| 774 | rtc::ByteBufferWriter buf; |
| 775 | response.Write(&buf); |
| 776 | rtc::PacketOptions options(StunDscpValue()); |
| 777 | options.info_signaled_after_sent.packet_type = |
| 778 | rtc::PacketType::kIceConnectivityCheckResponse; |
| 779 | SendTo(buf.Data(), buf.Length(), addr, options, false); |
| 780 | RTC_LOG(LS_INFO) << ToString() << ": Sending STUN " |
| 781 | << StunMethodToString(response.type()) |
| 782 | << ": reason=" << reason << " to " |
| 783 | << addr.ToSensitiveString(); |
| 784 | } |
| 785 |
| 786 | void Port::SendUnknownAttributesErrorResponse( |
| 787 | StunMessage* message, |
| 788 | const rtc::SocketAddress& addr, |
| 789 | const std::vector<uint16_t>& unknown_types) { |
| 790 | RTC_DCHECK_RUN_ON(thread_); |
| 791 | RTC_DCHECK(message->type() == STUN_BINDING_REQUEST); |
| 792 |
| 793 | // Fill in the response message. |
| 794 | StunMessage response(STUN_BINDING_ERROR_RESPONSE, message->transaction_id()); |
| 795 |
| 796 | auto error_attr = StunAttribute::CreateErrorCode(); |
| 797 | error_attr->SetCode(STUN_ERROR_UNKNOWN_ATTRIBUTE); |
| 798 | error_attr->SetReason(STUN_ERROR_REASON_UNKNOWN_ATTRIBUTE); |
| 799 | response.AddAttribute(std::move(error_attr)); |
| 800 |
| 801 | std::unique_ptr<StunUInt16ListAttribute> unknown_attr = |
| 802 | StunAttribute::CreateUnknownAttributes(); |
| 803 | for (uint16_t type : unknown_types) { |
| 804 | unknown_attr->AddType(type); |
| 805 | } |
| 806 | response.AddAttribute(std::move(unknown_attr)); |
| 807 |
| 808 | response.AddMessageIntegrity(password_); |
| 809 | response.AddFingerprint(); |
| 810 |
| 811 | // Send the response message. |
| 812 | rtc::ByteBufferWriter buf; |
| 813 | response.Write(&buf); |
| 814 | rtc::PacketOptions options(StunDscpValue()); |
| 815 | options.info_signaled_after_sent.packet_type = |
| 816 | rtc::PacketType::kIceConnectivityCheckResponse; |
| 817 | SendTo(buf.Data(), buf.Length(), addr, options, false); |
| 818 | RTC_LOG(LS_ERROR) << ToString() << ": Sending STUN binding error: reason=" |
| 819 | << STUN_ERROR_UNKNOWN_ATTRIBUTE << " to " |
| 820 | << addr.ToSensitiveString(); |
| 821 | } |
| 822 |
| 823 | void Port::KeepAliveUntilPruned() { |
| 824 | // If it is pruned, we won't bring it up again. |
| 825 | if (state_ == State::INIT) { |
| 826 | state_ = State::KEEP_ALIVE_UNTIL_PRUNED; |
| 827 | } |
| 828 | } |
| 829 |
| 830 | void Port::Prune() { |
| 831 | state_ = State::PRUNED; |
| 832 | PostDestroyIfDead(/*delayed=*/false); |
| 833 | } |
| 834 |
| 835 | // Call to stop any currently pending operations from running. |
| 836 | void Port::CancelPendingTasks() { |
| 837 | TRACE_EVENT0("webrtc", "Port::CancelPendingTasks"); |
| 838 | RTC_DCHECK_RUN_ON(thread_); |
| 839 | weak_factory_.InvalidateWeakPtrs(); |
| 840 | } |
| 841 |
| 842 | void Port::PostDestroyIfDead(bool delayed) { |
| 843 | rtc::WeakPtr<Port> weak_ptr = NewWeakPtr(); |
| 844 | auto task = [weak_ptr = std::move(weak_ptr)] { |
| 845 | if (weak_ptr) { |
| 846 | weak_ptr->DestroyIfDead(); |
| 847 | } |
| 848 | }; |
| 849 | if (delayed) { |
| 850 | thread_->PostDelayedTask(std::move(task), |
| 851 | TimeDelta::Millis(timeout_delay_)); |
| 852 | } else { |
| 853 | thread_->PostTask(std::move(task)); |
| 854 | } |
| 855 | } |
| 856 |
| 857 | void Port::DestroyIfDead() { |
| 858 | RTC_DCHECK_RUN_ON(thread_); |
| 859 | bool dead = |
| 860 | (state_ == State::INIT || state_ == State::PRUNED) && |
| 861 | connections_.empty() && |
| 862 | rtc::TimeMillis() - last_time_all_connections_removed_ >= timeout_delay_; |
| 863 | if (dead) { |
| 864 | Destroy(); |
| 865 | } |
| 866 | } |
| 867 |
| 868 | void Port::SubscribePortDestroyed( |
| 869 | std::function<void(PortInterface*)> callback) { |
| 870 | port_destroyed_callback_list_.AddReceiver(callback); |
| 871 | } |
| 872 |
| 873 | void Port::SendPortDestroyed(Port* port) { |
| 874 | port_destroyed_callback_list_.Send(port); |
| 875 | } |
| 876 | void Port::OnNetworkTypeChanged(const rtc::Network* network) { |
| 877 | RTC_DCHECK(network == network_); |
| 878 |
| 879 | UpdateNetworkCost(); |
| 880 | } |
| 881 |
| 882 | std::string Port::ToString() const { |
| 883 | rtc::StringBuilder ss; |
| 884 | ss << "Port[" << rtc::ToHex(reinterpret_cast<uintptr_t>(this)) << ":" |
| 885 | << content_name_ << ":" << component_ << ":" << generation_ << ":" << type_ |
| 886 | << ":" << network_->ToString() << "]"; |
| 887 | return ss.Release(); |
| 888 | } |
| 889 |
| 890 | // TODO(honghaiz): Make the network cost configurable from user setting. |
| 891 | void Port::UpdateNetworkCost() { |
| 892 | RTC_DCHECK_RUN_ON(thread_); |
| 893 | uint16_t new_cost = network_->GetCost(field_trials()); |
| 894 | if (network_cost_ == new_cost) { |
| 895 | return; |
| 896 | } |
| 897 | RTC_LOG(LS_INFO) << "Network cost changed from " << network_cost_ << " to " |
| 898 | << new_cost |
| 899 | << ". Number of candidates created: " << candidates_.size() |
| 900 | << ". Number of connections created: " |
| 901 | << connections_.size(); |
| 902 | network_cost_ = new_cost; |
| 903 | for (cricket::Candidate& candidate : candidates_) |
| 904 | candidate.set_network_cost(network_cost_); |
| 905 |
| 906 | for (auto& [unused, connection] : connections_) |
| 907 | connection->SetLocalCandidateNetworkCost(network_cost_); |
| 908 | } |
| 909 |
| 910 | void Port::EnablePortPackets() { |
| 911 | enable_port_packets_ = true; |
| 912 | } |
| 913 |
| 914 | bool Port::OnConnectionDestroyed(Connection* conn) { |
| 915 | if (connections_.erase(conn->remote_candidate().address()) == 0) { |
| 916 | // This could indicate a programmer error outside of webrtc so while we |
| 917 | // do have this check here to alert external developers, we also need to |
| 918 | // handle it since it might be a corner case not caught in tests. |
| 919 | RTC_DCHECK_NOTREACHED() << "Calling Destroy recursively?"; |
| 920 | return false; |
| 921 | } |
| 922 |
| 923 | HandleConnectionDestroyed(conn); |
| 924 |
| 925 | // Ports time out after all connections fail if it is not marked as |
| 926 | // "keep alive until pruned." |
| 927 | // Note: If a new connection is added after this message is posted, but it |
| 928 | // fails and is removed before kPortTimeoutDelay, then this message will |
| 929 | // not cause the Port to be destroyed. |
| 930 | if (connections_.empty()) { |
| 931 | last_time_all_connections_removed_ = rtc::TimeMillis(); |
| 932 | PostDestroyIfDead(/*delayed=*/true); |
| 933 | } |
| 934 |
| 935 | return true; |
| 936 | } |
| 937 |
| 938 | void Port::DestroyConnectionInternal(Connection* conn, bool async) { |
| 939 | RTC_DCHECK_RUN_ON(thread_); |
| 940 | if (!OnConnectionDestroyed(conn)) |
| 941 | return; |
| 942 |
| 943 | conn->Shutdown(); |
| 944 | if (async) { |
| 945 | // Unwind the stack before deleting the object in case upstream callers |
| 946 | // need to refer to the Connection's state as part of teardown. |
| 947 | // NOTE: We move ownership of `conn` into the capture section of the lambda |
| 948 | // so that the object will always be deleted, including if PostTask fails. |
| 949 | // In such a case (only tests), deletion would happen inside of the call |
| 950 | // to `DestroyConnection()`. |
| 951 | thread_->PostTask([conn = absl::WrapUnique(conn)]() {}); |
| 952 | } else { |
| 953 | delete conn; |
| 954 | } |
| 955 | } |
| 956 |
| 957 | void Port::Destroy() { |
| 958 | RTC_DCHECK(connections_.empty()); |
| 959 | RTC_LOG(LS_INFO) << ToString() << ": Port deleted"; |
| 960 | SendPortDestroyed(this); |
| 961 | delete this; |
| 962 | } |
| 963 |
| 964 | const std::string& Port::username_fragment() const { |
| 965 | RTC_DCHECK_RUN_ON(thread_); |
| 966 | return ice_username_fragment_; |
| 967 | } |
| 968 |
| 969 | void Port::CopyPortInformationToPacketInfo(rtc::PacketInfo* info) const { |
| 970 | info->protocol = ConvertProtocolTypeToPacketInfoProtocolType(GetProtocol()); |
| 971 | info->network_id = Network()->id(); |
| 972 | } |
| 973 |
| 974 | } // namespace cricket |
| 975 |