| 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/stun_request.h" |
| 12 |
| 13 | #include <algorithm> |
| 14 | #include <memory> |
| 15 | #include <utility> |
| 16 | #include <vector> |
| 17 |
| 18 | #include "absl/memory/memory.h" |
| 19 | #include "api/task_queue/pending_task_safety_flag.h" |
| 20 | #include "rtc_base/checks.h" |
| 21 | #include "rtc_base/helpers.h" |
| 22 | #include "rtc_base/logging.h" |
| 23 | #include "rtc_base/string_encode.h" |
| 24 | #include "rtc_base/time_utils.h" // For TimeMillis |
| 25 |
| 26 | namespace cricket { |
| 27 | using ::webrtc::SafeTask; |
| 28 |
| 29 | // RFC 5389 says SHOULD be 500ms. |
| 30 | // For years, this was 100ms, but for networks that |
| 31 | // experience moments of high RTT (such as 2G networks), this doesn't |
| 32 | // work well. |
| 33 | const int STUN_INITIAL_RTO = 250; // milliseconds |
| 34 |
| 35 | // The timeout doubles each retransmission, up to this many times |
| 36 | // RFC 5389 says SHOULD retransmit 7 times. |
| 37 | // This has been 8 for years (not sure why). |
| 38 | const int STUN_MAX_RETRANSMISSIONS = 8; // Total sends: 9 |
| 39 |
| 40 | // We also cap the doubling, even though the standard doesn't say to. |
| 41 | // This has been 1.6 seconds for years, but for networks that |
| 42 | // experience moments of high RTT (such as 2G networks), this doesn't |
| 43 | // work well. |
| 44 | const int STUN_MAX_RTO = 8000; // milliseconds, or 5 doublings |
| 45 |
| 46 | StunRequestManager::StunRequestManager( |
| 47 | webrtc::TaskQueueBase* thread, |
| 48 | std::function<void(const void*, size_t, StunRequest*)> send_packet) |
| 49 | : thread_(thread), send_packet_(std::move(send_packet)) {} |
| 50 |
| 51 | StunRequestManager::~StunRequestManager() = default; |
| 52 |
| 53 | void StunRequestManager::Send(StunRequest* request) { |
| 54 | SendDelayed(request, 0); |
| 55 | } |
| 56 |
| 57 | void StunRequestManager::SendDelayed(StunRequest* request, int delay) { |
| 58 | RTC_DCHECK_RUN_ON(thread_); |
| 59 | RTC_DCHECK_EQ(this, request->manager()); |
| 60 | RTC_DCHECK(!request->AuthenticationRequired() || |
| 61 | request->msg()->integrity() != |
| 62 | StunMessage::IntegrityStatus::kNotSet) |
| 63 | << "Sending request w/o integrity!"; |
| 64 | auto [iter, was_inserted] = |
| 65 | requests_.emplace(request->id(), absl::WrapUnique(request)); |
| 66 | RTC_DCHECK(was_inserted); |
| 67 | request->Send(webrtc::TimeDelta::Millis(delay)); |
| 68 | } |
| 69 |
| 70 | void StunRequestManager::FlushForTest(int msg_type) { |
| 71 | RTC_DCHECK_RUN_ON(thread_); |
| 72 | for (const auto& [unused, request] : requests_) { |
| 73 | if (msg_type == kAllRequestsForTest || msg_type == request->type()) { |
| 74 | // Calling `Send` implies starting the send operation which may be posted |
| 75 | // on a timer and be repeated on a timer until timeout. To make sure that |
| 76 | // a call to `Send` doesn't conflict with a previously started `Send` |
| 77 | // operation, we reset the `task_safety_` flag here, which has the effect |
| 78 | // of canceling any outstanding tasks and prepare a new flag for |
| 79 | // operations related to this call to `Send`. |
| 80 | request->ResetTasksForTest(); |
| 81 | request->Send(webrtc::TimeDelta::Zero()); |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 |
| 86 | bool StunRequestManager::HasRequestForTest(int msg_type) { |
| 87 | RTC_DCHECK_RUN_ON(thread_); |
| 88 | RTC_DCHECK_NE(msg_type, kAllRequestsForTest); |
| 89 | for (const auto& [unused, request] : requests_) { |
| 90 | if (msg_type == request->type()) { |
| 91 | return true; |
| 92 | } |
| 93 | } |
| 94 | return false; |
| 95 | } |
| 96 |
| 97 | void StunRequestManager::Clear() { |
| 98 | RTC_DCHECK_RUN_ON(thread_); |
| 99 | requests_.clear(); |
| 100 | } |
| 101 |
| 102 | bool StunRequestManager::CheckResponse(StunMessage* msg) { |
| 103 | RTC_DCHECK_RUN_ON(thread_); |
| 104 | RequestMap::iterator iter = requests_.find(msg->transaction_id()); |
| 105 | if (iter == requests_.end()) |
| 106 | return false; |
| 107 |
| 108 | StunRequest* request = iter->second.get(); |
| 109 |
| 110 | // Now that we know the request, we can see if the response is |
| 111 | // integrity-protected or not. Some requests explicitly disables |
| 112 | // integrity checks using SetAuthenticationRequired. |
| 113 | // TODO(chromium:1177125): Remove below! |
| 114 | // And we suspect that for some tests, the message integrity is not set in the |
| 115 | // request. Complain, and then don't check. |
| 116 | bool skip_integrity_checking = |
| 117 | (request->msg()->integrity() == StunMessage::IntegrityStatus::kNotSet); |
| 118 | if (!request->AuthenticationRequired()) { |
| 119 | // This is a STUN_BINDING to from stun_port.cc or |
| 120 | // the initial (unauthenticated) TURN_ALLOCATE_REQUEST. |
| 121 | } else if (skip_integrity_checking) { |
| 122 | // TODO(chromium:1177125): Remove below! |
| 123 | // This indicates lazy test writing (not adding integrity attribute). |
| 124 | // Complain, but only in debug mode (while developing). |
| 125 | RTC_LOG(LS_ERROR) |
| 126 | << "CheckResponse called on a passwordless request. Fix test!"; |
| 127 | RTC_DCHECK(false) |
| 128 | << "CheckResponse called on a passwordless request. Fix test!"; |
| 129 | } else { |
| 130 | if (msg->integrity() == StunMessage::IntegrityStatus::kNotSet) { |
| 131 | // Checking status for the first time. Normal. |
| 132 | msg->ValidateMessageIntegrity(request->msg()->password()); |
| 133 | } else if (msg->integrity() == StunMessage::IntegrityStatus::kIntegrityOk && |
| 134 | msg->password() == request->msg()->password()) { |
| 135 | // Status is already checked, with the same password. This is the case |
| 136 | // we would want to see happen. |
| 137 | } else if (msg->integrity() == |
| 138 | StunMessage::IntegrityStatus::kIntegrityBad) { |
| 139 | // This indicates that the original check had the wrong password. |
| 140 | // Bad design, needs revisiting. |
| 141 | // TODO(crbug.com/1177125): Fix this. |
| 142 | msg->RevalidateMessageIntegrity(request->msg()->password()); |
| 143 | } else { |
| 144 | RTC_CHECK_NOTREACHED(); |
| 145 | } |
| 146 | } |
| 147 |
| 148 | if (!msg->GetNonComprehendedAttributes().empty()) { |
| 149 | // If a response contains unknown comprehension-required attributes, it's |
| 150 | // simply discarded and the transaction is considered failed. See RFC5389 |
| 151 | // sections 7.3.3 and 7.3.4. |
| 152 | RTC_LOG(LS_ERROR) << ": Discarding response due to unknown " |
| 153 | "comprehension-required attribute."; |
| 154 | requests_.erase(iter); |
| 155 | return false; |
| 156 | } else if (msg->type() == GetStunSuccessResponseType(request->type())) { |
| 157 | if (!msg->IntegrityOk() && !skip_integrity_checking) { |
| 158 | return false; |
| 159 | } |
| 160 | // Erase element from hash before calling callback. This ensures |
| 161 | // that the callback can modify the StunRequestManager any way it |
| 162 | // sees fit. |
| 163 | std::unique_ptr<StunRequest> owned_request = std::move(iter->second); |
| 164 | requests_.erase(iter); |
| 165 | owned_request->OnResponse(msg); |
| 166 | return true; |
| 167 | } else if (msg->type() == GetStunErrorResponseType(request->type())) { |
| 168 | // Erase element from hash before calling callback. This ensures |
| 169 | // that the callback can modify the StunRequestManager any way it |
| 170 | // sees fit. |
| 171 | std::unique_ptr<StunRequest> owned_request = std::move(iter->second); |
| 172 | requests_.erase(iter); |
| 173 | owned_request->OnErrorResponse(msg); |
| 174 | return true; |
| 175 | } else { |
| 176 | RTC_LOG(LS_ERROR) << "Received response with wrong type: " << msg->type() |
| 177 | << " (expecting " |
| 178 | << GetStunSuccessResponseType(request->type()) << ")"; |
| 179 | return false; |
| 180 | } |
| 181 | } |
| 182 |
| 183 | bool StunRequestManager::empty() const { |
| 184 | RTC_DCHECK_RUN_ON(thread_); |
| 185 | return requests_.empty(); |
| 186 | } |
| 187 |
| 188 | bool StunRequestManager::CheckResponse(const char* data, size_t size) { |
| 189 | RTC_DCHECK_RUN_ON(thread_); |
| 190 | // Check the appropriate bytes of the stream to see if they match the |
| 191 | // transaction ID of a response we are expecting. |
| 192 |
| 193 | if (size < 20) |
| 194 | return false; |
| 195 |
| 196 | std::string id; |
| 197 | id.append(data + kStunTransactionIdOffset, kStunTransactionIdLength); |
| 198 |
| 199 | RequestMap::iterator iter = requests_.find(id); |
| 200 | if (iter == requests_.end()) |
| 201 | return false; |
| 202 |
| 203 | // Parse the STUN message and continue processing as usual. |
| 204 |
| 205 | rtc::ByteBufferReader buf( |
| 206 | rtc::MakeArrayView(reinterpret_cast<const uint8_t*>(data), size)); |
| 207 | std::unique_ptr<StunMessage> response(iter->second->msg_->CreateNew()); |
| 208 | if (!response->Read(&buf)) { |
| 209 | RTC_LOG(LS_WARNING) << "Failed to read STUN response " |
| 210 | << rtc::hex_encode(id); |
| 211 | return false; |
| 212 | } |
| 213 |
| 214 | return CheckResponse(response.get()); |
| 215 | } |
| 216 |
| 217 | void StunRequestManager::OnRequestTimedOut(StunRequest* request) { |
| 218 | RTC_DCHECK_RUN_ON(thread_); |
| 219 | requests_.erase(request->id()); |
| 220 | } |
| 221 |
| 222 | void StunRequestManager::SendPacket(const void* data, |
| 223 | size_t size, |
| 224 | StunRequest* request) { |
| 225 | RTC_DCHECK_EQ(this, request->manager()); |
| 226 | send_packet_(data, size, request); |
| 227 | } |
| 228 |
| 229 | StunRequest::StunRequest(StunRequestManager& manager) |
| 230 | : manager_(manager), |
| 231 | msg_(new StunMessage(STUN_INVALID_MESSAGE_TYPE)), |
| 232 | tstamp_(0), |
| 233 | count_(0), |
| 234 | timeout_(false) { |
| 235 | RTC_DCHECK_RUN_ON(network_thread()); |
| 236 | } |
| 237 |
| 238 | StunRequest::StunRequest(StunRequestManager& manager, |
| 239 | std::unique_ptr<StunMessage> message) |
| 240 | : manager_(manager), |
| 241 | msg_(std::move(message)), |
| 242 | tstamp_(0), |
| 243 | count_(0), |
| 244 | timeout_(false) { |
| 245 | RTC_DCHECK_RUN_ON(network_thread()); |
| 246 | RTC_DCHECK(!msg_->transaction_id().empty()); |
| 247 | } |
| 248 |
| 249 | StunRequest::~StunRequest() {} |
| 250 |
| 251 | int StunRequest::type() { |
| 252 | RTC_DCHECK(msg_ != NULL); |
| 253 | return msg_->type(); |
| 254 | } |
| 255 |
| 256 | const StunMessage* StunRequest::msg() const { |
| 257 | return msg_.get(); |
| 258 | } |
| 259 |
| 260 | int StunRequest::Elapsed() const { |
| 261 | RTC_DCHECK_RUN_ON(network_thread()); |
| 262 | return static_cast<int>(rtc::TimeMillis() - tstamp_); |
| 263 | } |
| 264 |
| 265 | void StunRequest::SendInternal() { |
| 266 | RTC_DCHECK_RUN_ON(network_thread()); |
| 267 | if (timeout_) { |
| 268 | OnTimeout(); |
| 269 | manager_.OnRequestTimedOut(this); |
| 270 | return; |
| 271 | } |
| 272 |
| 273 | tstamp_ = rtc::TimeMillis(); |
| 274 |
| 275 | rtc::ByteBufferWriter buf; |
| 276 | msg_->Write(&buf); |
| 277 | manager_.SendPacket(buf.Data(), buf.Length(), this); |
| 278 |
| 279 | OnSent(); |
| 280 | SendDelayed(webrtc::TimeDelta::Millis(resend_delay())); |
| 281 | } |
| 282 |
| 283 | void StunRequest::SendDelayed(webrtc::TimeDelta delay) { |
| 284 | network_thread()->PostDelayedTask( |
| 285 | SafeTask(task_safety_.flag(), [this]() { SendInternal(); }), delay); |
| 286 | } |
| 287 |
| 288 | void StunRequest::Send(webrtc::TimeDelta delay) { |
| 289 | RTC_DCHECK_RUN_ON(network_thread()); |
| 290 | RTC_DCHECK_GE(delay.ms(), 0); |
| 291 |
| 292 | RTC_DCHECK(!task_safety_.flag()->alive()) << "Send already called?"; |
| 293 | task_safety_.flag()->SetAlive(); |
| 294 |
| 295 | delay.IsZero() ? SendInternal() : SendDelayed(delay); |
| 296 | } |
| 297 |
| 298 | void StunRequest::ResetTasksForTest() { |
| 299 | RTC_DCHECK_RUN_ON(network_thread()); |
| 300 | task_safety_.reset(webrtc::PendingTaskSafetyFlag::CreateDetachedInactive()); |
| 301 | count_ = 0; |
| 302 | RTC_DCHECK(!timeout_); |
| 303 | } |
| 304 |
| 305 | void StunRequest::OnSent() { |
| 306 | RTC_DCHECK_RUN_ON(network_thread()); |
| 307 | count_ += 1; |
| 308 | int retransmissions = (count_ - 1); |
| 309 | if (retransmissions >= STUN_MAX_RETRANSMISSIONS) { |
| 310 | timeout_ = true; |
| 311 | } |
| 312 | RTC_DLOG(LS_VERBOSE) << "Sent STUN request " << count_ |
| 313 | << "; resend delay = " << resend_delay(); |
| 314 | } |
| 315 |
| 316 | int StunRequest::resend_delay() { |
| 317 | RTC_DCHECK_RUN_ON(network_thread()); |
| 318 | if (count_ == 0) { |
| 319 | return 0; |
| 320 | } |
| 321 | int retransmissions = (count_ - 1); |
| 322 | int rto = STUN_INITIAL_RTO << retransmissions; |
| 323 | return std::min(rto, STUN_MAX_RTO); |
| 324 | } |
| 325 |
| 326 | void StunRequest::set_timed_out() { |
| 327 | RTC_DCHECK_RUN_ON(network_thread()); |
| 328 | timeout_ = true; |
| 329 | } |
| 330 |
| 331 | } // namespace cricket |
| 332 |