blob: 2975d9f078790438477d21f438513c030a29303a [file] [log] [blame]
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +01001/*
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 10:22:34 +020013#include <memory>
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010014#include <string>
15#include <utility>
16
Ali Tofigh2ab914c2022-04-13 12:55:15 +020017#include "absl/strings/string_view.h"
Markus Handell1366b0f2021-04-21 10:22:34 +020018#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 10:41:01 +010022#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"
Artem Titovc374d112022-06-16 21:27:45 +020037#include "api/task_queue/to_queued_task.h"
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010038#include "rtc_base/ip_address.h"
39#include "rtc_base/logging.h"
Markus Handell1366b0f2021-04-21 10:22:34 +020040#include "rtc_base/platform_thread.h"
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010041#include "rtc_base/task_queue.h"
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010042#include "rtc_base/third_party/sigslot/sigslot.h" // for signal_with_thread...
43
Byoungchan Lee7284bd42021-10-06 20:25:39 +090044#if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
Byoungchan Lee08438fc2021-10-12 22:53:35 +090045#include <dispatch/dispatch.h>
Byoungchan Lee7284bd42021-10-06 20:25:39 +090046#endif
47
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010048namespace rtc {
49
Byoungchan Lee08438fc2021-10-12 22:53:35 +090050#if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
51namespace {
52
53void GlobalGcdRunTask(void* context) {
54 std::unique_ptr<webrtc::QueuedTask> task(
55 static_cast<webrtc::QueuedTask*>(context));
56 task->Run();
57}
58
59// Post a task into the system-defined global concurrent queue.
60void PostTaskToGlobalQueue(std::unique_ptr<webrtc::QueuedTask> task) {
61 dispatch_queue_global_t global_queue =
62 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
63 webrtc::QueuedTask* context = task.release();
64 dispatch_async_f(global_queue, context, &GlobalGcdRunTask);
65}
66
67} // namespace
68#endif
69
Ali Tofigh2ab914c2022-04-13 12:55:15 +020070int ResolveHostname(absl::string_view hostname,
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010071 int family,
72 std::vector<IPAddress>* addresses) {
73#ifdef __native_client__
Artem Titovd3251962021-11-15 16:57:07 +010074 RTC_DCHECK_NOTREACHED();
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010075 RTC_LOG(LS_WARNING) << "ResolveHostname() is not implemented for NaCl";
76 return -1;
77#else // __native_client__
78 if (!addresses) {
79 return -1;
80 }
81 addresses->clear();
82 struct addrinfo* result = nullptr;
83 struct addrinfo hints = {0};
84 hints.ai_family = family;
Artem Titov96e3b992021-07-26 16:03:14 +020085 // `family` here will almost always be AF_UNSPEC, because `family` comes from
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010086 // AsyncResolver::addr_.family(), which comes from a SocketAddress constructed
87 // with a hostname. When a SocketAddress is constructed with a hostname, its
88 // family is AF_UNSPEC. However, if someday in the future we construct
89 // a SocketAddress with both a hostname and a family other than AF_UNSPEC,
90 // then it would be possible to get a specific family value here.
91
92 // The behavior of AF_UNSPEC is roughly "get both ipv4 and ipv6", as
93 // documented by the various operating systems:
94 // Linux: http://man7.org/linux/man-pages/man3/getaddrinfo.3.html
95 // Windows: https://msdn.microsoft.com/en-us/library/windows/desktop/
96 // ms738520(v=vs.85).aspx
97 // Mac: https://developer.apple.com/legacy/library/documentation/Darwin/
98 // Reference/ManPages/man3/getaddrinfo.3.html
99 // Android (source code, not documentation):
100 // https://android.googlesource.com/platform/bionic/+/
101 // 7e0bfb511e85834d7c6cb9631206b62f82701d60/libc/netbsd/net/getaddrinfo.c#1657
102 hints.ai_flags = AI_ADDRCONFIG;
Ali Tofigh2ab914c2022-04-13 12:55:15 +0200103 int ret =
104 getaddrinfo(std::string(hostname).c_str(), nullptr, &hints, &result);
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100105 if (ret != 0) {
106 return ret;
107 }
108 struct addrinfo* cursor = result;
109 for (; cursor; cursor = cursor->ai_next) {
110 if (family == AF_UNSPEC || cursor->ai_family == family) {
111 IPAddress ip;
112 if (IPFromAddrInfo(cursor, &ip)) {
113 addresses->push_back(ip);
114 }
115 }
116 }
117 freeaddrinfo(result);
118 return 0;
119#endif // !__native_client__
120}
121
Markus Handell1366b0f2021-04-21 10:22:34 +0200122struct AsyncResolver::State : public RefCountedBase {
123 webrtc::Mutex mutex;
124 enum class Status {
125 kLive,
126 kDead
127 } status RTC_GUARDED_BY(mutex) = Status::kLive;
128};
129
130AsyncResolver::AsyncResolver() : error_(-1), state_(new State) {}
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100131
132AsyncResolver::~AsyncResolver() {
133 RTC_DCHECK_RUN_ON(&sequence_checker_);
Markus Handell1366b0f2021-04-21 10:22:34 +0200134
135 // Ensure the thread isn't using a stale reference to the current task queue,
136 // or calling into ResolveDone post destruction.
137 webrtc::MutexLock lock(&state_->mutex);
138 state_->status = State::Status::kDead;
139}
140
141void RunResolution(void* obj) {
142 std::function<void()>* function_ptr =
143 static_cast<std::function<void()>*>(obj);
144 (*function_ptr)();
145 delete function_ptr;
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100146}
147
148void AsyncResolver::Start(const SocketAddress& addr) {
149 RTC_DCHECK_RUN_ON(&sequence_checker_);
150 RTC_DCHECK(!destroy_called_);
151 addr_ = addr;
Byoungchan Lee7284bd42021-10-06 20:25:39 +0900152 auto thread_function =
Markus Handell1366b0f2021-04-21 10:22:34 +0200153 [this, addr, caller_task_queue = webrtc::TaskQueueBase::Current(),
154 state = state_] {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100155 std::vector<IPAddress> addresses;
Ali Tofigh2ab914c2022-04-13 12:55:15 +0200156 int error = ResolveHostname(addr.hostname(), addr.family(), &addresses);
Markus Handell1366b0f2021-04-21 10:22:34 +0200157 webrtc::MutexLock lock(&state->mutex);
158 if (state->status == State::Status::kLive) {
159 caller_task_queue->PostTask(webrtc::ToQueuedTask(
160 [this, error, addresses = std::move(addresses), state] {
161 bool live;
162 {
163 // ResolveDone can lead to instance destruction, so make sure
164 // we don't deadlock.
165 webrtc::MutexLock lock(&state->mutex);
166 live = state->status == State::Status::kLive;
167 }
168 if (live) {
169 RTC_DCHECK_RUN_ON(&sequence_checker_);
170 ResolveDone(std::move(addresses), error);
171 }
172 }));
173 }
Byoungchan Lee7284bd42021-10-06 20:25:39 +0900174 };
175#if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
Byoungchan Lee08438fc2021-10-12 22:53:35 +0900176 PostTaskToGlobalQueue(webrtc::ToQueuedTask(std::move(thread_function)));
Byoungchan Lee7284bd42021-10-06 20:25:39 +0900177#else
178 PlatformThread::SpawnDetached(std::move(thread_function), "AsyncResolver");
179#endif
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100180}
181
182bool AsyncResolver::GetResolvedAddress(int family, SocketAddress* addr) const {
183 RTC_DCHECK_RUN_ON(&sequence_checker_);
184 RTC_DCHECK(!destroy_called_);
185 if (error_ != 0 || addresses_.empty())
186 return false;
187
188 *addr = addr_;
189 for (size_t i = 0; i < addresses_.size(); ++i) {
190 if (family == addresses_[i].family()) {
191 addr->SetResolvedIP(addresses_[i]);
192 return true;
193 }
194 }
195 return false;
196}
197
198int AsyncResolver::GetError() const {
199 RTC_DCHECK_RUN_ON(&sequence_checker_);
200 RTC_DCHECK(!destroy_called_);
201 return error_;
202}
203
204void AsyncResolver::Destroy(bool wait) {
205 // Some callers have trouble guaranteeing that Destroy is called on the
Artem Titov96e3b992021-07-26 16:03:14 +0200206 // sequence guarded by `sequence_checker_`.
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100207 // RTC_DCHECK_RUN_ON(&sequence_checker_);
208 RTC_DCHECK(!destroy_called_);
209 destroy_called_ = true;
210 MaybeSelfDestruct();
211}
212
213const std::vector<IPAddress>& AsyncResolver::addresses() const {
214 RTC_DCHECK_RUN_ON(&sequence_checker_);
215 RTC_DCHECK(!destroy_called_);
216 return addresses_;
217}
218
219void AsyncResolver::ResolveDone(std::vector<IPAddress> addresses, int error) {
220 addresses_ = addresses;
221 error_ = error;
222 recursion_check_ = true;
223 SignalDone(this);
224 MaybeSelfDestruct();
225}
226
227void AsyncResolver::MaybeSelfDestruct() {
228 if (!recursion_check_) {
229 delete this;
230 } else {
231 recursion_check_ = false;
232 }
233}
234
235} // namespace rtc