blob: 3fe02aff22ff5e6fd3667138d8376116f72a1020 [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"
Artem Titovc374d112022-06-16 21:27:45 +020019#include "api/task_queue/to_queued_task.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 {
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_) {
Tommif7b30e02022-07-06 12:26:48 +020068 if (msg_type == kAllRequestsForTest || 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_);
Tommif7b30e02022-07-06 12:26:48 +020083 RTC_DCHECK_NE(msg_type, kAllRequestsForTest);
Tommi25452572022-04-12 12:51:40 +020084 for (const auto& [unused, request] : requests_) {
Tommif7b30e02022-07-06 12:26:48 +020085 if (msg_type == request->type()) {
honghaize2af9ef2016-03-03 08:27:47 -080086 return true;
87 }
88 }
89 return false;
90}
91
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000092void StunRequestManager::Clear() {
Tommi86aa03e2022-04-12 09:17:57 +020093 RTC_DCHECK_RUN_ON(thread_);
Tommi25452572022-04-12 12:51:40 +020094 requests_.clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000095}
96
97bool StunRequestManager::CheckResponse(StunMessage* msg) {
Tommi86aa03e2022-04-12 09:17:57 +020098 RTC_DCHECK_RUN_ON(thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000099 RequestMap::iterator iter = requests_.find(msg->transaction_id());
Tommi7ef4f512022-06-14 14:51:29 +0200100 if (iter == requests_.end())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000101 return false;
102
Tommi25452572022-04-12 12:51:40 +0200103 StunRequest* request = iter->second.get();
Harald Alvestrand07d83c82021-03-02 08:09:53 +0000104
105 // Now that we know the request, we can see if the response is
106 // integrity-protected or not.
107 // For some tests, the message integrity is not set in the request.
108 // Complain, and then don't check.
109 bool skip_integrity_checking = false;
110 if (request->msg()->integrity() == StunMessage::IntegrityStatus::kNotSet) {
111 skip_integrity_checking = true;
112 } else {
113 msg->ValidateMessageIntegrity(request->msg()->password());
114 }
115
Tommi25452572022-04-12 12:51:40 +0200116 bool success = true;
117
Taylor Brandstetterfb4351b2020-03-23 16:00:31 -0700118 if (!msg->GetNonComprehendedAttributes().empty()) {
119 // If a response contains unknown comprehension-required attributes, it's
120 // simply discarded and the transaction is considered failed. See RFC5389
121 // sections 7.3.3 and 7.3.4.
122 RTC_LOG(LS_ERROR) << ": Discarding response due to unknown "
123 "comprehension-required attribute.";
Tommi25452572022-04-12 12:51:40 +0200124 success = false;
Taylor Brandstetterfb4351b2020-03-23 16:00:31 -0700125 } else if (msg->type() == GetStunSuccessResponseType(request->type())) {
Harald Alvestrand07d83c82021-03-02 08:09:53 +0000126 if (!msg->IntegrityOk() && !skip_integrity_checking) {
127 return false;
128 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000129 request->OnResponse(msg);
130 } else if (msg->type() == GetStunErrorResponseType(request->type())) {
131 request->OnErrorResponse(msg);
132 } else {
Harald Alvestrand5f341302021-11-24 10:01:32 +0000133 RTC_LOG(LS_ERROR) << "Received response with wrong type: " << msg->type()
134 << " (expecting "
135 << GetStunSuccessResponseType(request->type()) << ")";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000136 return false;
137 }
138
Tommi25452572022-04-12 12:51:40 +0200139 requests_.erase(iter);
140 return success;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000141}
142
Tommi86aa03e2022-04-12 09:17:57 +0200143bool StunRequestManager::empty() const {
144 RTC_DCHECK_RUN_ON(thread_);
145 return requests_.empty();
146}
147
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000148bool StunRequestManager::CheckResponse(const char* data, size_t size) {
Tommi86aa03e2022-04-12 09:17:57 +0200149 RTC_DCHECK_RUN_ON(thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000150 // Check the appropriate bytes of the stream to see if they match the
151 // transaction ID of a response we are expecting.
152
153 if (size < 20)
154 return false;
155
156 std::string id;
157 id.append(data + kStunTransactionIdOffset, kStunTransactionIdLength);
158
159 RequestMap::iterator iter = requests_.find(id);
Tommi7ef4f512022-06-14 14:51:29 +0200160 if (iter == requests_.end())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000161 return false;
162
163 // Parse the STUN message and continue processing as usual.
164
jbauchf1f87202016-03-30 06:43:37 -0700165 rtc::ByteBufferReader buf(data, size);
kwiberg3ec46792016-04-27 07:22:53 -0700166 std::unique_ptr<StunMessage> response(iter->second->msg_->CreateNew());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700167 if (!response->Read(&buf)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100168 RTC_LOG(LS_WARNING) << "Failed to read STUN response "
169 << rtc::hex_encode(id);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000170 return false;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700171 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000172
173 return CheckResponse(response.get());
174}
175
Tommi25452572022-04-12 12:51:40 +0200176void StunRequestManager::OnRequestTimedOut(StunRequest* request) {
177 RTC_DCHECK_RUN_ON(thread_);
178 requests_.erase(request->id());
179}
180
Tomas Gunnarssonf22dfdd2022-04-13 09:07:30 +0000181void StunRequestManager::SendPacket(const void* data,
182 size_t size,
183 StunRequest* request) {
184 RTC_DCHECK_EQ(this, request->manager());
185 send_packet_(data, size, request);
186}
187
Tommi86aa03e2022-04-12 09:17:57 +0200188StunRequest::StunRequest(StunRequestManager& manager)
189 : manager_(manager),
Tommi408143d2022-06-01 15:29:31 +0200190 msg_(new StunMessage(STUN_INVALID_MESSAGE_TYPE)),
Tommi86aa03e2022-04-12 09:17:57 +0200191 tstamp_(0),
192 count_(0),
Tommi7ef4f512022-06-14 14:51:29 +0200193 timeout_(false) {
194 RTC_DCHECK_RUN_ON(network_thread());
195}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000196
Tommi86aa03e2022-04-12 09:17:57 +0200197StunRequest::StunRequest(StunRequestManager& manager,
Tommi278b19d2022-04-12 14:03:40 +0200198 std::unique_ptr<StunMessage> message)
Tommi86aa03e2022-04-12 09:17:57 +0200199 : manager_(manager),
Tommi278b19d2022-04-12 14:03:40 +0200200 msg_(std::move(message)),
Tommi86aa03e2022-04-12 09:17:57 +0200201 tstamp_(0),
202 count_(0),
203 timeout_(false) {
Tommi7ef4f512022-06-14 14:51:29 +0200204 RTC_DCHECK_RUN_ON(network_thread());
Tommi408143d2022-06-01 15:29:31 +0200205 RTC_DCHECK(!msg_->transaction_id().empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000206}
207
Tommi7ef4f512022-06-14 14:51:29 +0200208StunRequest::~StunRequest() {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000209
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000210int StunRequest::type() {
nisseede5da42017-01-12 05:15:36 -0800211 RTC_DCHECK(msg_ != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000212 return msg_->type();
213}
214
215const StunMessage* StunRequest::msg() const {
Tommi86aa03e2022-04-12 09:17:57 +0200216 return msg_.get();
Jonas Orelandbdcee282017-10-10 14:01:40 +0200217}
218
honghaiz34b11eb2016-03-16 08:55:44 -0700219int StunRequest::Elapsed() const {
Tommi86aa03e2022-04-12 09:17:57 +0200220 RTC_DCHECK_RUN_ON(network_thread());
nisse1bffc1d2016-05-02 08:18:55 -0700221 return static_cast<int>(rtc::TimeMillis() - tstamp_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000222}
223
Tommi7ef4f512022-06-14 14:51:29 +0200224void StunRequest::SendInternal() {
Tommi86aa03e2022-04-12 09:17:57 +0200225 RTC_DCHECK_RUN_ON(network_thread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000226 if (timeout_) {
227 OnTimeout();
Tommi25452572022-04-12 12:51:40 +0200228 manager_.OnRequestTimedOut(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000229 return;
230 }
231
nisse1bffc1d2016-05-02 08:18:55 -0700232 tstamp_ = rtc::TimeMillis();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000233
jbauchf1f87202016-03-30 06:43:37 -0700234 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000235 msg_->Write(&buf);
Tomas Gunnarssonf22dfdd2022-04-13 09:07:30 +0000236 manager_.SendPacket(buf.Data(), buf.Length(), this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000237
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700238 OnSent();
Tommi7ef4f512022-06-14 14:51:29 +0200239 SendDelayed(webrtc::TimeDelta::Millis(resend_delay()));
240}
241
242void StunRequest::SendDelayed(webrtc::TimeDelta delay) {
243 network_thread()->PostDelayedTask(
244 webrtc::ToQueuedTask(task_safety_, [this]() { SendInternal(); }),
245 delay.ms());
246}
247
248void StunRequest::Send(webrtc::TimeDelta delay) {
249 RTC_DCHECK_RUN_ON(network_thread());
250 RTC_DCHECK_GE(delay.ms(), 0);
251
252 RTC_DCHECK(!task_safety_.flag()->alive()) << "Send already called?";
253 task_safety_.flag()->SetAlive();
254
255 delay.IsZero() ? SendInternal() : SendDelayed(delay);
256}
257
258void StunRequest::ResetTasksForTest() {
259 RTC_DCHECK_RUN_ON(network_thread());
260 task_safety_.reset(webrtc::PendingTaskSafetyFlag::CreateDetachedInactive());
261 count_ = 0;
262 RTC_DCHECK(!timeout_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000263}
264
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700265void StunRequest::OnSent() {
Tommi86aa03e2022-04-12 09:17:57 +0200266 RTC_DCHECK_RUN_ON(network_thread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000267 count_ += 1;
pthatcher94a2f212017-02-08 14:42:22 -0800268 int retransmissions = (count_ - 1);
Mirko Bonadeif3879462020-04-14 13:44:09 +0200269 if (retransmissions >= STUN_MAX_RETRANSMISSIONS) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000270 timeout_ = true;
Taylor Brandstetter5ef034a2016-05-25 17:20:35 -0700271 }
Tommi86aa03e2022-04-12 09:17:57 +0200272 RTC_DLOG(LS_VERBOSE) << "Sent STUN request " << count_
273 << "; resend delay = " << resend_delay();
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700274}
275
276int StunRequest::resend_delay() {
Tommi86aa03e2022-04-12 09:17:57 +0200277 RTC_DCHECK_RUN_ON(network_thread());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700278 if (count_ == 0) {
279 return 0;
280 }
pthatcher94a2f212017-02-08 14:42:22 -0800281 int retransmissions = (count_ - 1);
282 int rto = STUN_INITIAL_RTO << retransmissions;
283 return std::min(rto, STUN_MAX_RTO);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000284}
285
Tommi86aa03e2022-04-12 09:17:57 +0200286void StunRequest::set_timed_out() {
287 RTC_DCHECK_RUN_ON(network_thread());
288 timeout_ = true;
289}
290
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000291} // namespace cricket