blob: 1228e4e148dba26dd9de6a949ce8876037b67d57 [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.
110 bool skip_integrity_checking = false;
111 if (request->msg()->integrity() == StunMessage::IntegrityStatus::kNotSet) {
112 skip_integrity_checking = true;
113 } else {
114 msg->ValidateMessageIntegrity(request->msg()->password());
115 }
116
Tommi25452572022-04-12 12:51:40 +0200117 bool success = true;
118
Taylor Brandstetterfb4351b2020-03-23 16:00:31 -0700119 if (!msg->GetNonComprehendedAttributes().empty()) {
120 // If a response contains unknown comprehension-required attributes, it's
121 // simply discarded and the transaction is considered failed. See RFC5389
122 // sections 7.3.3 and 7.3.4.
123 RTC_LOG(LS_ERROR) << ": Discarding response due to unknown "
124 "comprehension-required attribute.";
Tommi25452572022-04-12 12:51:40 +0200125 success = false;
Taylor Brandstetterfb4351b2020-03-23 16:00:31 -0700126 } else if (msg->type() == GetStunSuccessResponseType(request->type())) {
Harald Alvestrand07d83c82021-03-02 08:09:53 +0000127 if (!msg->IntegrityOk() && !skip_integrity_checking) {
128 return false;
129 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000130 request->OnResponse(msg);
131 } else if (msg->type() == GetStunErrorResponseType(request->type())) {
132 request->OnErrorResponse(msg);
133 } else {
Harald Alvestrand5f341302021-11-24 10:01:32 +0000134 RTC_LOG(LS_ERROR) << "Received response with wrong type: " << msg->type()
135 << " (expecting "
136 << GetStunSuccessResponseType(request->type()) << ")";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000137 return false;
138 }
139
Tommi25452572022-04-12 12:51:40 +0200140 requests_.erase(iter);
141 return success;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000142}
143
Tommi86aa03e2022-04-12 09:17:57 +0200144bool StunRequestManager::empty() const {
145 RTC_DCHECK_RUN_ON(thread_);
146 return requests_.empty();
147}
148
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000149bool StunRequestManager::CheckResponse(const char* data, size_t size) {
Tommi86aa03e2022-04-12 09:17:57 +0200150 RTC_DCHECK_RUN_ON(thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000151 // Check the appropriate bytes of the stream to see if they match the
152 // transaction ID of a response we are expecting.
153
154 if (size < 20)
155 return false;
156
157 std::string id;
158 id.append(data + kStunTransactionIdOffset, kStunTransactionIdLength);
159
160 RequestMap::iterator iter = requests_.find(id);
Tommi7ef4f512022-06-14 14:51:29 +0200161 if (iter == requests_.end())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000162 return false;
163
164 // Parse the STUN message and continue processing as usual.
165
jbauchf1f87202016-03-30 06:43:37 -0700166 rtc::ByteBufferReader buf(data, size);
kwiberg3ec46792016-04-27 07:22:53 -0700167 std::unique_ptr<StunMessage> response(iter->second->msg_->CreateNew());
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700168 if (!response->Read(&buf)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100169 RTC_LOG(LS_WARNING) << "Failed to read STUN response "
170 << rtc::hex_encode(id);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000171 return false;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700172 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000173
174 return CheckResponse(response.get());
175}
176
Tommi25452572022-04-12 12:51:40 +0200177void StunRequestManager::OnRequestTimedOut(StunRequest* request) {
178 RTC_DCHECK_RUN_ON(thread_);
179 requests_.erase(request->id());
180}
181
Tomas Gunnarssonf22dfdd2022-04-13 09:07:30 +0000182void StunRequestManager::SendPacket(const void* data,
183 size_t size,
184 StunRequest* request) {
185 RTC_DCHECK_EQ(this, request->manager());
186 send_packet_(data, size, request);
187}
188
Tommi86aa03e2022-04-12 09:17:57 +0200189StunRequest::StunRequest(StunRequestManager& manager)
190 : manager_(manager),
Tommi408143d2022-06-01 15:29:31 +0200191 msg_(new StunMessage(STUN_INVALID_MESSAGE_TYPE)),
Tommi86aa03e2022-04-12 09:17:57 +0200192 tstamp_(0),
193 count_(0),
Tommi7ef4f512022-06-14 14:51:29 +0200194 timeout_(false) {
195 RTC_DCHECK_RUN_ON(network_thread());
196}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000197
Tommi86aa03e2022-04-12 09:17:57 +0200198StunRequest::StunRequest(StunRequestManager& manager,
Tommi278b19d2022-04-12 14:03:40 +0200199 std::unique_ptr<StunMessage> message)
Tommi86aa03e2022-04-12 09:17:57 +0200200 : manager_(manager),
Tommi278b19d2022-04-12 14:03:40 +0200201 msg_(std::move(message)),
Tommi86aa03e2022-04-12 09:17:57 +0200202 tstamp_(0),
203 count_(0),
204 timeout_(false) {
Tommi7ef4f512022-06-14 14:51:29 +0200205 RTC_DCHECK_RUN_ON(network_thread());
Tommi408143d2022-06-01 15:29:31 +0200206 RTC_DCHECK(!msg_->transaction_id().empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000207}
208
Tommi7ef4f512022-06-14 14:51:29 +0200209StunRequest::~StunRequest() {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000210
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000211int StunRequest::type() {
nisseede5da42017-01-12 05:15:36 -0800212 RTC_DCHECK(msg_ != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000213 return msg_->type();
214}
215
216const StunMessage* StunRequest::msg() const {
Tommi86aa03e2022-04-12 09:17:57 +0200217 return msg_.get();
Jonas Orelandbdcee282017-10-10 14:01:40 +0200218}
219
honghaiz34b11eb2016-03-16 08:55:44 -0700220int StunRequest::Elapsed() const {
Tommi86aa03e2022-04-12 09:17:57 +0200221 RTC_DCHECK_RUN_ON(network_thread());
nisse1bffc1d2016-05-02 08:18:55 -0700222 return static_cast<int>(rtc::TimeMillis() - tstamp_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000223}
224
Tommi7ef4f512022-06-14 14:51:29 +0200225void StunRequest::SendInternal() {
Tommi86aa03e2022-04-12 09:17:57 +0200226 RTC_DCHECK_RUN_ON(network_thread());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000227 if (timeout_) {
228 OnTimeout();
Tommi25452572022-04-12 12:51:40 +0200229 manager_.OnRequestTimedOut(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000230 return;
231 }
232
nisse1bffc1d2016-05-02 08:18:55 -0700233 tstamp_ = rtc::TimeMillis();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000234
jbauchf1f87202016-03-30 06:43:37 -0700235 rtc::ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000236 msg_->Write(&buf);
Tomas Gunnarssonf22dfdd2022-04-13 09:07:30 +0000237 manager_.SendPacket(buf.Data(), buf.Length(), this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000238
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700239 OnSent();
Tommi7ef4f512022-06-14 14:51:29 +0200240 SendDelayed(webrtc::TimeDelta::Millis(resend_delay()));
241}
242
243void StunRequest::SendDelayed(webrtc::TimeDelta delay) {
244 network_thread()->PostDelayedTask(
Danil Chapovalov7b190362022-07-07 14:13:02 +0200245 SafeTask(task_safety_.flag(), [this]() { SendInternal(); }), delay);
Tommi7ef4f512022-06-14 14:51:29 +0200246}
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