blob: d15a3e65e2cb4bcd36c9e1263c00d733e7f738a8 [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"
Danil Chapovalov7b190362022-07-07 14:13:02 +020019#include "api/task_queue/pending_task_safety_flag.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "rtc_base/checks.h"
21#include "rtc_base/helpers.h"
22#include "rtc_base/logging.h"
Steve Antonf4172382020-01-27 15:45:02 -080023#include "rtc_base/string_encode.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 {
Danil Chapovalov7b190362022-07-07 14:13:02 +020027using ::webrtc::SafeTask;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000028
pthatcher94a2f212017-02-08 14:42:22 -080029// 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.
33const 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).
Jonas Olssona4d87372019-07-05 19:08:33 +020038const int STUN_MAX_RETRANSMISSIONS = 8; // Total sends: 9
pthatcher94a2f212017-02-08 14:42:22 -080039
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.
44const int STUN_MAX_RTO = 8000; // milliseconds, or 5 doublings
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000045
Tomas Gunnarssonf22dfdd2022-04-13 09:07:30 +000046StunRequestManager::StunRequestManager(
Tommi7ef4f512022-06-14 14:51:29 +020047 webrtc::TaskQueueBase* thread,
Tomas Gunnarssonf22dfdd2022-04-13 09:07:30 +000048 std::function<void(const void*, size_t, StunRequest*)> send_packet)
49 : thread_(thread), send_packet_(std::move(send_packet)) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000050
Tommi25452572022-04-12 12:51:40 +020051StunRequestManager::~StunRequestManager() = default;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000052
53void StunRequestManager::Send(StunRequest* request) {
54 SendDelayed(request, 0);
55}
56
57void StunRequestManager::SendDelayed(StunRequest* request, int delay) {
Tommi86aa03e2022-04-12 09:17:57 +020058 RTC_DCHECK_RUN_ON(thread_);
59 RTC_DCHECK_EQ(this, request->manager());
Tommi25452572022-04-12 12:51:40 +020060 auto [iter, was_inserted] =
61 requests_.emplace(request->id(), absl::WrapUnique(request));
62 RTC_DCHECK(was_inserted);
Tommi7ef4f512022-06-14 14:51:29 +020063 request->Send(webrtc::TimeDelta::Millis(delay));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000064}
65
Tommi86aa03e2022-04-12 09:17:57 +020066void StunRequestManager::FlushForTest(int msg_type) {
67 RTC_DCHECK_RUN_ON(thread_);
Tommi25452572022-04-12 12:51:40 +020068 for (const auto& [unused, request] : requests_) {
Tommif7b30e02022-07-06 12:26:48 +020069 if (msg_type == kAllRequestsForTest || msg_type == request->type()) {
Tommi7ef4f512022-06-14 14:51:29 +020070 // Calling `Send` implies starting the send operation which may be posted
71 // on a timer and be repeated on a timer until timeout. To make sure that
72 // a call to `Send` doesn't conflict with a previously started `Send`
73 // operation, we reset the `task_safety_` flag here, which has the effect
74 // of canceling any outstanding tasks and prepare a new flag for
75 // operations related to this call to `Send`.
76 request->ResetTasksForTest();
Philipp Hanckea204ad22022-07-08 18:43:25 +020077 request->Send(webrtc::TimeDelta::Zero());
honghaiz6b9ab922016-01-05 09:06:12 -080078 }
Honghai Zhang85975432015-11-12 11:07:12 -080079 }
80}
81
Tommi86aa03e2022-04-12 09:17:57 +020082bool StunRequestManager::HasRequestForTest(int msg_type) {
83 RTC_DCHECK_RUN_ON(thread_);
Tommif7b30e02022-07-06 12:26:48 +020084 RTC_DCHECK_NE(msg_type, kAllRequestsForTest);
Tommi25452572022-04-12 12:51:40 +020085 for (const auto& [unused, request] : requests_) {
Tommif7b30e02022-07-06 12:26:48 +020086 if (msg_type == request->type()) {
honghaize2af9ef2016-03-03 08:27:47 -080087 return true;
88 }
89 }
90 return false;
91}
92
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000093void StunRequestManager::Clear() {
Tommi86aa03e2022-04-12 09:17:57 +020094 RTC_DCHECK_RUN_ON(thread_);
Tommi25452572022-04-12 12:51:40 +020095 requests_.clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000096}
97
98bool StunRequestManager::CheckResponse(StunMessage* msg) {
Tommi86aa03e2022-04-12 09:17:57 +020099 RTC_DCHECK_RUN_ON(thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000100 RequestMap::iterator iter = requests_.find(msg->transaction_id());
Tommi7ef4f512022-06-14 14:51:29 +0200101 if (iter == requests_.end())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000102 return false;
103
Tommi25452572022-04-12 12:51:40 +0200104 StunRequest* request = iter->second.get();
Harald Alvestrand07d83c82021-03-02 08:09:53 +0000105
106 // Now that we know the request, we can see if the response is
107 // integrity-protected or not.
108 // For some tests, the message integrity is not set in the request.
109 // Complain, and then don't check.
Harald Alvestrand47627622022-10-13 09:57:05 +0000110 bool skip_integrity_checking =
111 (request->msg()->integrity() == StunMessage::IntegrityStatus::kNotSet);
112 if (skip_integrity_checking) {
113 // This indicates lazy test writing (not adding integrity attribute).
114 // Complain, but only in debug mode (while developing).
115 RTC_DLOG(LS_ERROR)
116 << "CheckResponse called on a passwordless request. Fix test!";
Harald Alvestrand07d83c82021-03-02 08:09:53 +0000117 } else {
Harald Alvestrand47627622022-10-13 09:57:05 +0000118 if (msg->integrity() == StunMessage::IntegrityStatus::kNotSet) {
119 // Checking status for the first time. Normal.
120 msg->ValidateMessageIntegrity(request->msg()->password());
121 } else if (msg->integrity() == StunMessage::IntegrityStatus::kIntegrityOk &&
122 msg->password() == request->msg()->password()) {
123 // Status is already checked, with the same password. This is the case
124 // we would want to see happen.
125 } else if (msg->integrity() ==
126 StunMessage::IntegrityStatus::kIntegrityBad) {
127 // This indicates that the original check had the wrong password.
128 // Bad design, needs revisiting.
129 // TODO(crbug.com/1177125): Fix this.
130 msg->RevalidateMessageIntegrity(request->msg()->password());
131 } else {
132 RTC_CHECK_NOTREACHED();
133 }
Harald Alvestrand07d83c82021-03-02 08:09:53 +0000134 }
135
Tommi25452572022-04-12 12:51:40 +0200136 bool success = true;
137
Taylor Brandstetterfb4351b2020-03-23 16:00:31 -0700138 if (!msg->GetNonComprehendedAttributes().empty()) {
139 // If a response contains unknown comprehension-required attributes, it's
140 // simply discarded and the transaction is considered failed. See RFC5389
141 // sections 7.3.3 and 7.3.4.
142 RTC_LOG(LS_ERROR) << ": Discarding response due to unknown "
143 "comprehension-required attribute.";
Tommi25452572022-04-12 12:51:40 +0200144 success = false;
Taylor Brandstetterfb4351b2020-03-23 16:00:31 -0700145 } else if (msg->type() == GetStunSuccessResponseType(request->type())) {
Harald Alvestrand07d83c82021-03-02 08:09:53 +0000146 if (!msg->IntegrityOk() && !skip_integrity_checking) {
147 return false;
148 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000149 request->OnResponse(msg);
150 } else if (msg->type() == GetStunErrorResponseType(request->type())) {
151 request->OnErrorResponse(msg);
152 } else {
Harald Alvestrand5f341302021-11-24 10:01:32 +0000153 RTC_LOG(LS_ERROR) << "Received response with wrong type: " << msg->type()
154 << " (expecting "
155 << GetStunSuccessResponseType(request->type()) << ")";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000156 return false;
157 }
158
Tommi25452572022-04-12 12:51:40 +0200159 requests_.erase(iter);
160 return success;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000161}
162
Tommi86aa03e2022-04-12 09:17:57 +0200163bool StunRequestManager::empty() const {
164 RTC_DCHECK_RUN_ON(thread_);
165 return requests_.empty();
166}
167
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000168bool StunRequestManager::CheckResponse(const char* data, size_t size) {
Tommi86aa03e2022-04-12 09:17:57 +0200169 RTC_DCHECK_RUN_ON(thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000170 // Check the appropriate bytes of the stream to see if they match the
171 // transaction ID of a response we are expecting.
172
173 if (size < 20)
174 return false;
175
176 std::string id;
177 id.append(data + kStunTransactionIdOffset, kStunTransactionIdLength);
178
179 RequestMap::iterator iter = requests_.find(id);
Tommi7ef4f512022-06-14 14:51:29 +0200180 if (iter == requests_.end())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000181 return false;
182
183 // Parse the STUN message and continue processing as usual.
184
jbauchf1f87202016-03-30 06:43:37 -0700185 rtc::ByteBufferReader buf(data, size);
kwiberg3ec46792016-04-27 07:22:53 -0700186 std::unique_ptr<StunMessage> response(iter->second->msg_->CreateNew());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700187 if (!response->Read(&buf)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100188 RTC_LOG(LS_WARNING) << "Failed to read STUN response "
189 << rtc::hex_encode(id);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000190 return false;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700191 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000192
193 return CheckResponse(response.get());
194}
195
Tommi25452572022-04-12 12:51:40 +0200196void StunRequestManager::OnRequestTimedOut(StunRequest* request) {
197 RTC_DCHECK_RUN_ON(thread_);
198 requests_.erase(request->id());
199}
200
Tomas Gunnarssonf22dfdd2022-04-13 09:07:30 +0000201void StunRequestManager::SendPacket(const void* data,
202 size_t size,
203 StunRequest* request) {
204 RTC_DCHECK_EQ(this, request->manager());
205 send_packet_(data, size, request);
206}
207
Tommi86aa03e2022-04-12 09:17:57 +0200208StunRequest::StunRequest(StunRequestManager& manager)
209 : manager_(manager),
Tommi408143d2022-06-01 15:29:31 +0200210 msg_(new StunMessage(STUN_INVALID_MESSAGE_TYPE)),
Tommi86aa03e2022-04-12 09:17:57 +0200211 tstamp_(0),
212 count_(0),
Tommi7ef4f512022-06-14 14:51:29 +0200213 timeout_(false) {
214 RTC_DCHECK_RUN_ON(network_thread());
215}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000216
Tommi86aa03e2022-04-12 09:17:57 +0200217StunRequest::StunRequest(StunRequestManager& manager,
Tommi278b19d2022-04-12 14:03:40 +0200218 std::unique_ptr<StunMessage> message)
Tommi86aa03e2022-04-12 09:17:57 +0200219 : manager_(manager),
Tommi278b19d2022-04-12 14:03:40 +0200220 msg_(std::move(message)),
Tommi86aa03e2022-04-12 09:17:57 +0200221 tstamp_(0),
222 count_(0),
223 timeout_(false) {
Tommi7ef4f512022-06-14 14:51:29 +0200224 RTC_DCHECK_RUN_ON(network_thread());
Tommi408143d2022-06-01 15:29:31 +0200225 RTC_DCHECK(!msg_->transaction_id().empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000226}
227
Tommi7ef4f512022-06-14 14:51:29 +0200228StunRequest::~StunRequest() {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000229
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000230int StunRequest::type() {
nisseede5da42017-01-12 05:15:36 -0800231 RTC_DCHECK(msg_ != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000232 return msg_->type();
233}
234
235const StunMessage* StunRequest::msg() const {
Tommi86aa03e2022-04-12 09:17:57 +0200236 return msg_.get();
Jonas Orelandbdcee282017-10-10 14:01:40 +0200237}
238
honghaiz34b11eb2016-03-16 08:55:44 -0700239int StunRequest::Elapsed() const {
Tommi86aa03e2022-04-12 09:17:57 +0200240 RTC_DCHECK_RUN_ON(network_thread());
nisse1bffc1d2016-05-02 08:18:55 -0700241 return static_cast<int>(rtc::TimeMillis() - tstamp_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000242}
243
Tommi7ef4f512022-06-14 14:51:29 +0200244void StunRequest::SendInternal() {
Tommi86aa03e2022-04-12 09:17:57 +0200245 RTC_DCHECK_RUN_ON(network_thread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000246 if (timeout_) {
247 OnTimeout();
Tommi25452572022-04-12 12:51:40 +0200248 manager_.OnRequestTimedOut(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000249 return;
250 }
251
nisse1bffc1d2016-05-02 08:18:55 -0700252 tstamp_ = rtc::TimeMillis();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000253
jbauchf1f87202016-03-30 06:43:37 -0700254 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000255 msg_->Write(&buf);
Tomas Gunnarssonf22dfdd2022-04-13 09:07:30 +0000256 manager_.SendPacket(buf.Data(), buf.Length(), this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000257
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700258 OnSent();
Tommi7ef4f512022-06-14 14:51:29 +0200259 SendDelayed(webrtc::TimeDelta::Millis(resend_delay()));
260}
261
262void StunRequest::SendDelayed(webrtc::TimeDelta delay) {
263 network_thread()->PostDelayedTask(
Danil Chapovalov7b190362022-07-07 14:13:02 +0200264 SafeTask(task_safety_.flag(), [this]() { SendInternal(); }), delay);
Tommi7ef4f512022-06-14 14:51:29 +0200265}
266
267void StunRequest::Send(webrtc::TimeDelta delay) {
268 RTC_DCHECK_RUN_ON(network_thread());
269 RTC_DCHECK_GE(delay.ms(), 0);
270
271 RTC_DCHECK(!task_safety_.flag()->alive()) << "Send already called?";
272 task_safety_.flag()->SetAlive();
273
274 delay.IsZero() ? SendInternal() : SendDelayed(delay);
275}
276
277void StunRequest::ResetTasksForTest() {
278 RTC_DCHECK_RUN_ON(network_thread());
279 task_safety_.reset(webrtc::PendingTaskSafetyFlag::CreateDetachedInactive());
280 count_ = 0;
281 RTC_DCHECK(!timeout_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000282}
283
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700284void StunRequest::OnSent() {
Tommi86aa03e2022-04-12 09:17:57 +0200285 RTC_DCHECK_RUN_ON(network_thread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000286 count_ += 1;
pthatcher94a2f212017-02-08 14:42:22 -0800287 int retransmissions = (count_ - 1);
Mirko Bonadeif3879462020-04-14 13:44:09 +0200288 if (retransmissions >= STUN_MAX_RETRANSMISSIONS) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000289 timeout_ = true;
Taylor Brandstetter5ef034a2016-05-25 17:20:35 -0700290 }
Tommi86aa03e2022-04-12 09:17:57 +0200291 RTC_DLOG(LS_VERBOSE) << "Sent STUN request " << count_
292 << "; resend delay = " << resend_delay();
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700293}
294
295int StunRequest::resend_delay() {
Tommi86aa03e2022-04-12 09:17:57 +0200296 RTC_DCHECK_RUN_ON(network_thread());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700297 if (count_ == 0) {
298 return 0;
299 }
pthatcher94a2f212017-02-08 14:42:22 -0800300 int retransmissions = (count_ - 1);
301 int rto = STUN_INITIAL_RTO << retransmissions;
302 return std::min(rto, STUN_MAX_RTO);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000303}
304
Tommi86aa03e2022-04-12 09:17:57 +0200305void StunRequest::set_timed_out() {
306 RTC_DCHECK_RUN_ON(network_thread());
307 timeout_ = true;
308}
309
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000310} // namespace cricket