blob: c4d586caae7744c00227d7c21e02ac0ff6c4714f [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Steve Anton10542f22019-01-11 09:11:00 -080011#include "p2p/base/stun_request.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000012
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000013#include <algorithm>
kwiberg3ec46792016-04-27 07:22:53 -070014#include <memory>
Tommi86aa03e2022-04-12 09:17:57 +020015#include <utility>
Steve Anton6c38cc72017-11-29 10:25:58 -080016#include <vector>
kwiberg3ec46792016-04-27 07:22:53 -070017
Tommi25452572022-04-12 12:51:40 +020018#include "absl/memory/memory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "rtc_base/checks.h"
20#include "rtc_base/helpers.h"
21#include "rtc_base/logging.h"
Steve Antonf4172382020-01-27 15:45:02 -080022#include "rtc_base/string_encode.h"
Tommi7ef4f512022-06-14 14:51:29 +020023#include "rtc_base/task_utils/to_queued_task.h"
Steve Anton10542f22019-01-11 09:11:00 -080024#include "rtc_base/time_utils.h" // For TimeMillis
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000025
26namespace cricket {
27
pthatcher94a2f212017-02-08 14:42:22 -080028// RFC 5389 says SHOULD be 500ms.
29// For years, this was 100ms, but for networks that
30// experience moments of high RTT (such as 2G networks), this doesn't
31// work well.
32const int STUN_INITIAL_RTO = 250; // milliseconds
33
34// The timeout doubles each retransmission, up to this many times
35// RFC 5389 says SHOULD retransmit 7 times.
36// This has been 8 for years (not sure why).
Jonas Olssona4d87372019-07-05 19:08:33 +020037const int STUN_MAX_RETRANSMISSIONS = 8; // Total sends: 9
pthatcher94a2f212017-02-08 14:42:22 -080038
39// We also cap the doubling, even though the standard doesn't say to.
40// This has been 1.6 seconds for years, but for networks that
41// experience moments of high RTT (such as 2G networks), this doesn't
42// work well.
43const int STUN_MAX_RTO = 8000; // milliseconds, or 5 doublings
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000044
Tomas Gunnarssonf22dfdd2022-04-13 09:07:30 +000045StunRequestManager::StunRequestManager(
Tommi7ef4f512022-06-14 14:51:29 +020046 webrtc::TaskQueueBase* thread,
Tomas Gunnarssonf22dfdd2022-04-13 09:07:30 +000047 std::function<void(const void*, size_t, StunRequest*)> send_packet)
48 : thread_(thread), send_packet_(std::move(send_packet)) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000049
Tommi25452572022-04-12 12:51:40 +020050StunRequestManager::~StunRequestManager() = default;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000051
52void StunRequestManager::Send(StunRequest* request) {
53 SendDelayed(request, 0);
54}
55
56void StunRequestManager::SendDelayed(StunRequest* request, int delay) {
Tommi86aa03e2022-04-12 09:17:57 +020057 RTC_DCHECK_RUN_ON(thread_);
58 RTC_DCHECK_EQ(this, request->manager());
Tommi25452572022-04-12 12:51:40 +020059 auto [iter, was_inserted] =
60 requests_.emplace(request->id(), absl::WrapUnique(request));
61 RTC_DCHECK(was_inserted);
Tommi7ef4f512022-06-14 14:51:29 +020062 request->Send(webrtc::TimeDelta::Millis(delay));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000063}
64
Tommi86aa03e2022-04-12 09:17:57 +020065void StunRequestManager::FlushForTest(int msg_type) {
66 RTC_DCHECK_RUN_ON(thread_);
Tommi25452572022-04-12 12:51:40 +020067 for (const auto& [unused, request] : requests_) {
honghaiz6b9ab922016-01-05 09:06:12 -080068 if (msg_type == kAllRequests || msg_type == request->type()) {
Tommi7ef4f512022-06-14 14:51:29 +020069 // Calling `Send` implies starting the send operation which may be posted
70 // on a timer and be repeated on a timer until timeout. To make sure that
71 // a call to `Send` doesn't conflict with a previously started `Send`
72 // operation, we reset the `task_safety_` flag here, which has the effect
73 // of canceling any outstanding tasks and prepare a new flag for
74 // operations related to this call to `Send`.
75 request->ResetTasksForTest();
76 request->Send(webrtc::TimeDelta::Millis(0));
honghaiz6b9ab922016-01-05 09:06:12 -080077 }
Honghai Zhang85975432015-11-12 11:07:12 -080078 }
79}
80
Tommi86aa03e2022-04-12 09:17:57 +020081bool StunRequestManager::HasRequestForTest(int msg_type) {
82 RTC_DCHECK_RUN_ON(thread_);
Tommi25452572022-04-12 12:51:40 +020083 for (const auto& [unused, request] : requests_) {
honghaize2af9ef2016-03-03 08:27:47 -080084 if (msg_type == kAllRequests || msg_type == request->type()) {
85 return true;
86 }
87 }
88 return false;
89}
90
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000091void StunRequestManager::Clear() {
Tommi86aa03e2022-04-12 09:17:57 +020092 RTC_DCHECK_RUN_ON(thread_);
Tommi25452572022-04-12 12:51:40 +020093 requests_.clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000094}
95
96bool StunRequestManager::CheckResponse(StunMessage* msg) {
Tommi86aa03e2022-04-12 09:17:57 +020097 RTC_DCHECK_RUN_ON(thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000098 RequestMap::iterator iter = requests_.find(msg->transaction_id());
Tommi7ef4f512022-06-14 14:51:29 +020099 if (iter == requests_.end())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000100 return false;
101
Tommi25452572022-04-12 12:51:40 +0200102 StunRequest* request = iter->second.get();
Harald Alvestrand07d83c82021-03-02 08:09:53 +0000103
104 // Now that we know the request, we can see if the response is
105 // integrity-protected or not.
106 // For some tests, the message integrity is not set in the request.
107 // Complain, and then don't check.
108 bool skip_integrity_checking = false;
109 if (request->msg()->integrity() == StunMessage::IntegrityStatus::kNotSet) {
110 skip_integrity_checking = true;
111 } else {
112 msg->ValidateMessageIntegrity(request->msg()->password());
113 }
114
Tommi25452572022-04-12 12:51:40 +0200115 bool success = true;
116
Taylor Brandstetterfb4351b2020-03-23 16:00:31 -0700117 if (!msg->GetNonComprehendedAttributes().empty()) {
118 // If a response contains unknown comprehension-required attributes, it's
119 // simply discarded and the transaction is considered failed. See RFC5389
120 // sections 7.3.3 and 7.3.4.
121 RTC_LOG(LS_ERROR) << ": Discarding response due to unknown "
122 "comprehension-required attribute.";
Tommi25452572022-04-12 12:51:40 +0200123 success = false;
Taylor Brandstetterfb4351b2020-03-23 16:00:31 -0700124 } else if (msg->type() == GetStunSuccessResponseType(request->type())) {
Harald Alvestrand07d83c82021-03-02 08:09:53 +0000125 if (!msg->IntegrityOk() && !skip_integrity_checking) {
126 return false;
127 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000128 request->OnResponse(msg);
129 } else if (msg->type() == GetStunErrorResponseType(request->type())) {
130 request->OnErrorResponse(msg);
131 } else {
Harald Alvestrand5f341302021-11-24 10:01:32 +0000132 RTC_LOG(LS_ERROR) << "Received response with wrong type: " << msg->type()
133 << " (expecting "
134 << GetStunSuccessResponseType(request->type()) << ")";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000135 return false;
136 }
137
Tommi25452572022-04-12 12:51:40 +0200138 requests_.erase(iter);
139 return success;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000140}
141
Tommi86aa03e2022-04-12 09:17:57 +0200142bool StunRequestManager::empty() const {
143 RTC_DCHECK_RUN_ON(thread_);
144 return requests_.empty();
145}
146
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000147bool StunRequestManager::CheckResponse(const char* data, size_t size) {
Tommi86aa03e2022-04-12 09:17:57 +0200148 RTC_DCHECK_RUN_ON(thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000149 // Check the appropriate bytes of the stream to see if they match the
150 // transaction ID of a response we are expecting.
151
152 if (size < 20)
153 return false;
154
155 std::string id;
156 id.append(data + kStunTransactionIdOffset, kStunTransactionIdLength);
157
158 RequestMap::iterator iter = requests_.find(id);
Tommi7ef4f512022-06-14 14:51:29 +0200159 if (iter == requests_.end())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000160 return false;
161
162 // Parse the STUN message and continue processing as usual.
163
jbauchf1f87202016-03-30 06:43:37 -0700164 rtc::ByteBufferReader buf(data, size);
kwiberg3ec46792016-04-27 07:22:53 -0700165 std::unique_ptr<StunMessage> response(iter->second->msg_->CreateNew());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700166 if (!response->Read(&buf)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100167 RTC_LOG(LS_WARNING) << "Failed to read STUN response "
168 << rtc::hex_encode(id);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000169 return false;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700170 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000171
172 return CheckResponse(response.get());
173}
174
Tommi25452572022-04-12 12:51:40 +0200175void StunRequestManager::OnRequestTimedOut(StunRequest* request) {
176 RTC_DCHECK_RUN_ON(thread_);
177 requests_.erase(request->id());
178}
179
Tomas Gunnarssonf22dfdd2022-04-13 09:07:30 +0000180void StunRequestManager::SendPacket(const void* data,
181 size_t size,
182 StunRequest* request) {
183 RTC_DCHECK_EQ(this, request->manager());
184 send_packet_(data, size, request);
185}
186
Tommi86aa03e2022-04-12 09:17:57 +0200187StunRequest::StunRequest(StunRequestManager& manager)
188 : manager_(manager),
Tommi408143d2022-06-01 15:29:31 +0200189 msg_(new StunMessage(STUN_INVALID_MESSAGE_TYPE)),
Tommi86aa03e2022-04-12 09:17:57 +0200190 tstamp_(0),
191 count_(0),
Tommi7ef4f512022-06-14 14:51:29 +0200192 timeout_(false) {
193 RTC_DCHECK_RUN_ON(network_thread());
194}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000195
Tommi86aa03e2022-04-12 09:17:57 +0200196StunRequest::StunRequest(StunRequestManager& manager,
Tommi278b19d2022-04-12 14:03:40 +0200197 std::unique_ptr<StunMessage> message)
Tommi86aa03e2022-04-12 09:17:57 +0200198 : manager_(manager),
Tommi278b19d2022-04-12 14:03:40 +0200199 msg_(std::move(message)),
Tommi86aa03e2022-04-12 09:17:57 +0200200 tstamp_(0),
201 count_(0),
202 timeout_(false) {
Tommi7ef4f512022-06-14 14:51:29 +0200203 RTC_DCHECK_RUN_ON(network_thread());
Tommi408143d2022-06-01 15:29:31 +0200204 RTC_DCHECK(!msg_->transaction_id().empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000205}
206
Tommi7ef4f512022-06-14 14:51:29 +0200207StunRequest::~StunRequest() {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000208
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000209int StunRequest::type() {
nisseede5da42017-01-12 05:15:36 -0800210 RTC_DCHECK(msg_ != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000211 return msg_->type();
212}
213
214const StunMessage* StunRequest::msg() const {
Tommi86aa03e2022-04-12 09:17:57 +0200215 return msg_.get();
Jonas Orelandbdcee282017-10-10 14:01:40 +0200216}
217
honghaiz34b11eb2016-03-16 08:55:44 -0700218int StunRequest::Elapsed() const {
Tommi86aa03e2022-04-12 09:17:57 +0200219 RTC_DCHECK_RUN_ON(network_thread());
nisse1bffc1d2016-05-02 08:18:55 -0700220 return static_cast<int>(rtc::TimeMillis() - tstamp_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000221}
222
Tommi7ef4f512022-06-14 14:51:29 +0200223void StunRequest::SendInternal() {
Tommi86aa03e2022-04-12 09:17:57 +0200224 RTC_DCHECK_RUN_ON(network_thread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000225 if (timeout_) {
226 OnTimeout();
Tommi25452572022-04-12 12:51:40 +0200227 manager_.OnRequestTimedOut(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000228 return;
229 }
230
nisse1bffc1d2016-05-02 08:18:55 -0700231 tstamp_ = rtc::TimeMillis();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000232
jbauchf1f87202016-03-30 06:43:37 -0700233 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000234 msg_->Write(&buf);
Tomas Gunnarssonf22dfdd2022-04-13 09:07:30 +0000235 manager_.SendPacket(buf.Data(), buf.Length(), this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000236
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700237 OnSent();
Tommi7ef4f512022-06-14 14:51:29 +0200238 SendDelayed(webrtc::TimeDelta::Millis(resend_delay()));
239}
240
241void StunRequest::SendDelayed(webrtc::TimeDelta delay) {
242 network_thread()->PostDelayedTask(
243 webrtc::ToQueuedTask(task_safety_, [this]() { SendInternal(); }),
244 delay.ms());
245}
246
247void StunRequest::Send(webrtc::TimeDelta delay) {
248 RTC_DCHECK_RUN_ON(network_thread());
249 RTC_DCHECK_GE(delay.ms(), 0);
250
251 RTC_DCHECK(!task_safety_.flag()->alive()) << "Send already called?";
252 task_safety_.flag()->SetAlive();
253
254 delay.IsZero() ? SendInternal() : SendDelayed(delay);
255}
256
257void StunRequest::ResetTasksForTest() {
258 RTC_DCHECK_RUN_ON(network_thread());
259 task_safety_.reset(webrtc::PendingTaskSafetyFlag::CreateDetachedInactive());
260 count_ = 0;
261 RTC_DCHECK(!timeout_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000262}
263
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700264void StunRequest::OnSent() {
Tommi86aa03e2022-04-12 09:17:57 +0200265 RTC_DCHECK_RUN_ON(network_thread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000266 count_ += 1;
pthatcher94a2f212017-02-08 14:42:22 -0800267 int retransmissions = (count_ - 1);
Mirko Bonadeif3879462020-04-14 13:44:09 +0200268 if (retransmissions >= STUN_MAX_RETRANSMISSIONS) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000269 timeout_ = true;
Taylor Brandstetter5ef034a2016-05-25 17:20:35 -0700270 }
Tommi86aa03e2022-04-12 09:17:57 +0200271 RTC_DLOG(LS_VERBOSE) << "Sent STUN request " << count_
272 << "; resend delay = " << resend_delay();
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700273}
274
275int StunRequest::resend_delay() {
Tommi86aa03e2022-04-12 09:17:57 +0200276 RTC_DCHECK_RUN_ON(network_thread());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700277 if (count_ == 0) {
278 return 0;
279 }
pthatcher94a2f212017-02-08 14:42:22 -0800280 int retransmissions = (count_ - 1);
281 int rto = STUN_INITIAL_RTO << retransmissions;
282 return std::min(rto, STUN_MAX_RTO);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000283}
284
Tommi86aa03e2022-04-12 09:17:57 +0200285void StunRequest::set_timed_out() {
286 RTC_DCHECK_RUN_ON(network_thread());
287 timeout_ = true;
288}
289
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000290} // namespace cricket