1 /*
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
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
StunRequestManager(webrtc::TaskQueueBase * thread,std::function<void (const void *,size_t,StunRequest *)> send_packet)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
Send(StunRequest * request)53 void StunRequestManager::Send(StunRequest* request) {
54 SendDelayed(request, 0);
55 }
56
SendDelayed(StunRequest * request,int delay)57 void StunRequestManager::SendDelayed(StunRequest* request, int delay) {
58 RTC_DCHECK_RUN_ON(thread_);
59 RTC_DCHECK_EQ(this, request->manager());
60 auto [iter, was_inserted] =
61 requests_.emplace(request->id(), absl::WrapUnique(request));
62 RTC_DCHECK(was_inserted);
63 request->Send(webrtc::TimeDelta::Millis(delay));
64 }
65
FlushForTest(int msg_type)66 void StunRequestManager::FlushForTest(int msg_type) {
67 RTC_DCHECK_RUN_ON(thread_);
68 for (const auto& [unused, request] : requests_) {
69 if (msg_type == kAllRequestsForTest || msg_type == request->type()) {
70 // 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();
77 request->Send(webrtc::TimeDelta::Zero());
78 }
79 }
80 }
81
HasRequestForTest(int msg_type)82 bool StunRequestManager::HasRequestForTest(int msg_type) {
83 RTC_DCHECK_RUN_ON(thread_);
84 RTC_DCHECK_NE(msg_type, kAllRequestsForTest);
85 for (const auto& [unused, request] : requests_) {
86 if (msg_type == request->type()) {
87 return true;
88 }
89 }
90 return false;
91 }
92
Clear()93 void StunRequestManager::Clear() {
94 RTC_DCHECK_RUN_ON(thread_);
95 requests_.clear();
96 }
97
CheckResponse(StunMessage * msg)98 bool StunRequestManager::CheckResponse(StunMessage* msg) {
99 RTC_DCHECK_RUN_ON(thread_);
100 RequestMap::iterator iter = requests_.find(msg->transaction_id());
101 if (iter == requests_.end())
102 return false;
103
104 StunRequest* request = iter->second.get();
105
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 =
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!";
117 } else {
118 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 }
134 }
135
136 bool success = true;
137
138 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.";
144 success = false;
145 } else if (msg->type() == GetStunSuccessResponseType(request->type())) {
146 if (!msg->IntegrityOk() && !skip_integrity_checking) {
147 return false;
148 }
149 request->OnResponse(msg);
150 } else if (msg->type() == GetStunErrorResponseType(request->type())) {
151 request->OnErrorResponse(msg);
152 } else {
153 RTC_LOG(LS_ERROR) << "Received response with wrong type: " << msg->type()
154 << " (expecting "
155 << GetStunSuccessResponseType(request->type()) << ")";
156 return false;
157 }
158
159 requests_.erase(iter);
160 return success;
161 }
162
empty() const163 bool StunRequestManager::empty() const {
164 RTC_DCHECK_RUN_ON(thread_);
165 return requests_.empty();
166 }
167
CheckResponse(const char * data,size_t size)168 bool StunRequestManager::CheckResponse(const char* data, size_t size) {
169 RTC_DCHECK_RUN_ON(thread_);
170 // 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);
180 if (iter == requests_.end())
181 return false;
182
183 // Parse the STUN message and continue processing as usual.
184
185 rtc::ByteBufferReader buf(data, size);
186 std::unique_ptr<StunMessage> response(iter->second->msg_->CreateNew());
187 if (!response->Read(&buf)) {
188 RTC_LOG(LS_WARNING) << "Failed to read STUN response "
189 << rtc::hex_encode(id);
190 return false;
191 }
192
193 return CheckResponse(response.get());
194 }
195
OnRequestTimedOut(StunRequest * request)196 void StunRequestManager::OnRequestTimedOut(StunRequest* request) {
197 RTC_DCHECK_RUN_ON(thread_);
198 requests_.erase(request->id());
199 }
200
SendPacket(const void * data,size_t size,StunRequest * request)201 void 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
StunRequest(StunRequestManager & manager)208 StunRequest::StunRequest(StunRequestManager& manager)
209 : manager_(manager),
210 msg_(new StunMessage(STUN_INVALID_MESSAGE_TYPE)),
211 tstamp_(0),
212 count_(0),
213 timeout_(false) {
214 RTC_DCHECK_RUN_ON(network_thread());
215 }
216
StunRequest(StunRequestManager & manager,std::unique_ptr<StunMessage> message)217 StunRequest::StunRequest(StunRequestManager& manager,
218 std::unique_ptr<StunMessage> message)
219 : manager_(manager),
220 msg_(std::move(message)),
221 tstamp_(0),
222 count_(0),
223 timeout_(false) {
224 RTC_DCHECK_RUN_ON(network_thread());
225 RTC_DCHECK(!msg_->transaction_id().empty());
226 }
227
~StunRequest()228 StunRequest::~StunRequest() {}
229
type()230 int StunRequest::type() {
231 RTC_DCHECK(msg_ != NULL);
232 return msg_->type();
233 }
234
msg() const235 const StunMessage* StunRequest::msg() const {
236 return msg_.get();
237 }
238
Elapsed() const239 int StunRequest::Elapsed() const {
240 RTC_DCHECK_RUN_ON(network_thread());
241 return static_cast<int>(rtc::TimeMillis() - tstamp_);
242 }
243
SendInternal()244 void StunRequest::SendInternal() {
245 RTC_DCHECK_RUN_ON(network_thread());
246 if (timeout_) {
247 OnTimeout();
248 manager_.OnRequestTimedOut(this);
249 return;
250 }
251
252 tstamp_ = rtc::TimeMillis();
253
254 rtc::ByteBufferWriter buf;
255 msg_->Write(&buf);
256 manager_.SendPacket(buf.Data(), buf.Length(), this);
257
258 OnSent();
259 SendDelayed(webrtc::TimeDelta::Millis(resend_delay()));
260 }
261
SendDelayed(webrtc::TimeDelta delay)262 void StunRequest::SendDelayed(webrtc::TimeDelta delay) {
263 network_thread()->PostDelayedTask(
264 SafeTask(task_safety_.flag(), [this]() { SendInternal(); }), delay);
265 }
266
Send(webrtc::TimeDelta delay)267 void 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
ResetTasksForTest()277 void StunRequest::ResetTasksForTest() {
278 RTC_DCHECK_RUN_ON(network_thread());
279 task_safety_.reset(webrtc::PendingTaskSafetyFlag::CreateDetachedInactive());
280 count_ = 0;
281 RTC_DCHECK(!timeout_);
282 }
283
OnSent()284 void StunRequest::OnSent() {
285 RTC_DCHECK_RUN_ON(network_thread());
286 count_ += 1;
287 int retransmissions = (count_ - 1);
288 if (retransmissions >= STUN_MAX_RETRANSMISSIONS) {
289 timeout_ = true;
290 }
291 RTC_DLOG(LS_VERBOSE) << "Sent STUN request " << count_
292 << "; resend delay = " << resend_delay();
293 }
294
resend_delay()295 int StunRequest::resend_delay() {
296 RTC_DCHECK_RUN_ON(network_thread());
297 if (count_ == 0) {
298 return 0;
299 }
300 int retransmissions = (count_ - 1);
301 int rto = STUN_INITIAL_RTO << retransmissions;
302 return std::min(rto, STUN_MAX_RTO);
303 }
304
set_timed_out()305 void StunRequest::set_timed_out() {
306 RTC_DCHECK_RUN_ON(network_thread());
307 timeout_ = true;
308 }
309
310 } // namespace cricket
311