blob: 7c1a6fe78daa75c36070f7c73f7a2c39d4731239 [file] [log] [blame]
Mirko Bonadeie5f4c6b2021-01-15 09:41:011/*
2 * Copyright 2008 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 "rtc_base/async_resolver.h"
12
Markus Handell1366b0f2021-04-21 08:22:3413#include <memory>
Mirko Bonadeie5f4c6b2021-01-15 09:41:0114#include <string>
15#include <utility>
16
Ali Tofigh2ab914c2022-04-13 10:55:1517#include "absl/strings/string_view.h"
Markus Handell1366b0f2021-04-21 08:22:3418#include "api/ref_counted_base.h"
19#include "rtc_base/synchronization/mutex.h"
20#include "rtc_base/thread_annotations.h"
21
Mirko Bonadeie5f4c6b2021-01-15 09:41:0122#if defined(WEBRTC_WIN)
23#include <ws2spi.h>
24#include <ws2tcpip.h>
25
26#include "rtc_base/win32.h"
27#endif
28#if defined(WEBRTC_POSIX) && !defined(__native_client__)
29#if defined(WEBRTC_ANDROID)
30#include "rtc_base/ifaddrs_android.h"
31#else
32#include <ifaddrs.h>
33#endif
34#endif // defined(WEBRTC_POSIX) && !defined(__native_client__)
35
36#include "api/task_queue/task_queue_base.h"
37#include "rtc_base/ip_address.h"
38#include "rtc_base/logging.h"
Markus Handell1366b0f2021-04-21 08:22:3439#include "rtc_base/platform_thread.h"
Mirko Bonadeie5f4c6b2021-01-15 09:41:0140#include "rtc_base/task_queue.h"
Mirko Bonadeie5f4c6b2021-01-15 09:41:0141#include "rtc_base/third_party/sigslot/sigslot.h" // for signal_with_thread...
42
Byoungchan Lee7284bd42021-10-06 11:25:3943#if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
Byoungchan Lee08438fc2021-10-12 13:53:3544#include <dispatch/dispatch.h>
Byoungchan Lee7284bd42021-10-06 11:25:3945#endif
46
Mirko Bonadeie5f4c6b2021-01-15 09:41:0147namespace rtc {
48
Byoungchan Lee08438fc2021-10-12 13:53:3549#if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
50namespace {
51
52void GlobalGcdRunTask(void* context) {
Danil Chapovalov5286dcf2022-07-18 15:04:5653 std::unique_ptr<absl::AnyInvocable<void() &&>> task(
54 static_cast<absl::AnyInvocable<void() &&>*>(context));
55 std::move (*task)();
Byoungchan Lee08438fc2021-10-12 13:53:3556}
57
58// Post a task into the system-defined global concurrent queue.
Danil Chapovalov5286dcf2022-07-18 15:04:5659void PostTaskToGlobalQueue(
60 std::unique_ptr<absl::AnyInvocable<void() &&>> task) {
Byoungchan Lee08438fc2021-10-12 13:53:3561 dispatch_queue_global_t global_queue =
62 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
Danil Chapovalov5286dcf2022-07-18 15:04:5663 dispatch_async_f(global_queue, task.release(), &GlobalGcdRunTask);
Byoungchan Lee08438fc2021-10-12 13:53:3564}
65
66} // namespace
67#endif
68
Ali Tofigh2ab914c2022-04-13 10:55:1569int ResolveHostname(absl::string_view hostname,
Mirko Bonadeie5f4c6b2021-01-15 09:41:0170 int family,
71 std::vector<IPAddress>* addresses) {
72#ifdef __native_client__
Artem Titovd3251962021-11-15 15:57:0773 RTC_DCHECK_NOTREACHED();
Mirko Bonadeie5f4c6b2021-01-15 09:41:0174 RTC_LOG(LS_WARNING) << "ResolveHostname() is not implemented for NaCl";
75 return -1;
76#else // __native_client__
77 if (!addresses) {
78 return -1;
79 }
80 addresses->clear();
81 struct addrinfo* result = nullptr;
82 struct addrinfo hints = {0};
83 hints.ai_family = family;
Artem Titov96e3b992021-07-26 14:03:1484 // `family` here will almost always be AF_UNSPEC, because `family` comes from
Mirko Bonadeie5f4c6b2021-01-15 09:41:0185 // AsyncResolver::addr_.family(), which comes from a SocketAddress constructed
86 // with a hostname. When a SocketAddress is constructed with a hostname, its
87 // family is AF_UNSPEC. However, if someday in the future we construct
88 // a SocketAddress with both a hostname and a family other than AF_UNSPEC,
89 // then it would be possible to get a specific family value here.
90
91 // The behavior of AF_UNSPEC is roughly "get both ipv4 and ipv6", as
92 // documented by the various operating systems:
93 // Linux: http://man7.org/linux/man-pages/man3/getaddrinfo.3.html
94 // Windows: https://msdn.microsoft.com/en-us/library/windows/desktop/
95 // ms738520(v=vs.85).aspx
96 // Mac: https://developer.apple.com/legacy/library/documentation/Darwin/
97 // Reference/ManPages/man3/getaddrinfo.3.html
98 // Android (source code, not documentation):
99 // https://android.googlesource.com/platform/bionic/+/
100 // 7e0bfb511e85834d7c6cb9631206b62f82701d60/libc/netbsd/net/getaddrinfo.c#1657
101 hints.ai_flags = AI_ADDRCONFIG;
Ali Tofigh2ab914c2022-04-13 10:55:15102 int ret =
103 getaddrinfo(std::string(hostname).c_str(), nullptr, &hints, &result);
Mirko Bonadeie5f4c6b2021-01-15 09:41:01104 if (ret != 0) {
105 return ret;
106 }
107 struct addrinfo* cursor = result;
108 for (; cursor; cursor = cursor->ai_next) {
109 if (family == AF_UNSPEC || cursor->ai_family == family) {
110 IPAddress ip;
111 if (IPFromAddrInfo(cursor, &ip)) {
112 addresses->push_back(ip);
113 }
114 }
115 }
116 freeaddrinfo(result);
117 return 0;
118#endif // !__native_client__
119}
120
Markus Handell1366b0f2021-04-21 08:22:34121struct AsyncResolver::State : public RefCountedBase {
122 webrtc::Mutex mutex;
123 enum class Status {
124 kLive,
125 kDead
126 } status RTC_GUARDED_BY(mutex) = Status::kLive;
127};
128
129AsyncResolver::AsyncResolver() : error_(-1), state_(new State) {}
Mirko Bonadeie5f4c6b2021-01-15 09:41:01130
131AsyncResolver::~AsyncResolver() {
132 RTC_DCHECK_RUN_ON(&sequence_checker_);
Markus Handell1366b0f2021-04-21 08:22:34133
134 // Ensure the thread isn't using a stale reference to the current task queue,
135 // or calling into ResolveDone post destruction.
136 webrtc::MutexLock lock(&state_->mutex);
137 state_->status = State::Status::kDead;
138}
139
140void RunResolution(void* obj) {
141 std::function<void()>* function_ptr =
142 static_cast<std::function<void()>*>(obj);
143 (*function_ptr)();
144 delete function_ptr;
Mirko Bonadeie5f4c6b2021-01-15 09:41:01145}
146
147void AsyncResolver::Start(const SocketAddress& addr) {
Sameer Vijaykarb787e262022-08-11 09:52:57148 Start(addr, addr.family());
149}
150
151void AsyncResolver::Start(const SocketAddress& addr, int family) {
Mirko Bonadeie5f4c6b2021-01-15 09:41:01152 RTC_DCHECK_RUN_ON(&sequence_checker_);
153 RTC_DCHECK(!destroy_called_);
154 addr_ = addr;
Byoungchan Lee7284bd42021-10-06 11:25:39155 auto thread_function =
Sameer Vijaykarb787e262022-08-11 09:52:57156 [this, addr, family, caller_task_queue = webrtc::TaskQueueBase::Current(),
Markus Handell1366b0f2021-04-21 08:22:34157 state = state_] {
Mirko Bonadeie5f4c6b2021-01-15 09:41:01158 std::vector<IPAddress> addresses;
Sameer Vijaykarb787e262022-08-11 09:52:57159 int error = ResolveHostname(addr.hostname(), family, &addresses);
Markus Handell1366b0f2021-04-21 08:22:34160 webrtc::MutexLock lock(&state->mutex);
161 if (state->status == State::Status::kLive) {
Danil Chapovalov5286dcf2022-07-18 15:04:56162 caller_task_queue->PostTask(
Markus Handell1366b0f2021-04-21 08:22:34163 [this, error, addresses = std::move(addresses), state] {
164 bool live;
165 {
166 // ResolveDone can lead to instance destruction, so make sure
167 // we don't deadlock.
168 webrtc::MutexLock lock(&state->mutex);
169 live = state->status == State::Status::kLive;
170 }
171 if (live) {
172 RTC_DCHECK_RUN_ON(&sequence_checker_);
173 ResolveDone(std::move(addresses), error);
174 }
Danil Chapovalov5286dcf2022-07-18 15:04:56175 });
Markus Handell1366b0f2021-04-21 08:22:34176 }
Byoungchan Lee7284bd42021-10-06 11:25:39177 };
178#if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
Danil Chapovalov5286dcf2022-07-18 15:04:56179 PostTaskToGlobalQueue(
180 std::make_unique<absl::AnyInvocable<void() &&>>(thread_function));
Byoungchan Lee7284bd42021-10-06 11:25:39181#else
182 PlatformThread::SpawnDetached(std::move(thread_function), "AsyncResolver");
183#endif
Mirko Bonadeie5f4c6b2021-01-15 09:41:01184}
185
186bool AsyncResolver::GetResolvedAddress(int family, SocketAddress* addr) const {
187 RTC_DCHECK_RUN_ON(&sequence_checker_);
188 RTC_DCHECK(!destroy_called_);
189 if (error_ != 0 || addresses_.empty())
190 return false;
191
192 *addr = addr_;
193 for (size_t i = 0; i < addresses_.size(); ++i) {
194 if (family == addresses_[i].family()) {
195 addr->SetResolvedIP(addresses_[i]);
196 return true;
197 }
198 }
199 return false;
200}
201
202int AsyncResolver::GetError() const {
203 RTC_DCHECK_RUN_ON(&sequence_checker_);
204 RTC_DCHECK(!destroy_called_);
205 return error_;
206}
207
208void AsyncResolver::Destroy(bool wait) {
209 // Some callers have trouble guaranteeing that Destroy is called on the
Artem Titov96e3b992021-07-26 14:03:14210 // sequence guarded by `sequence_checker_`.
Mirko Bonadeie5f4c6b2021-01-15 09:41:01211 // RTC_DCHECK_RUN_ON(&sequence_checker_);
212 RTC_DCHECK(!destroy_called_);
213 destroy_called_ = true;
214 MaybeSelfDestruct();
215}
216
217const std::vector<IPAddress>& AsyncResolver::addresses() const {
218 RTC_DCHECK_RUN_ON(&sequence_checker_);
219 RTC_DCHECK(!destroy_called_);
220 return addresses_;
221}
222
223void AsyncResolver::ResolveDone(std::vector<IPAddress> addresses, int error) {
224 addresses_ = addresses;
225 error_ = error;
226 recursion_check_ = true;
227 SignalDone(this);
228 MaybeSelfDestruct();
229}
230
231void AsyncResolver::MaybeSelfDestruct() {
232 if (!recursion_check_) {
233 delete this;
234 } else {
235 recursion_check_ = false;
236 }
237}
238
239} // namespace rtc