1 /*
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
13 #include <memory>
14 #include <string>
15 #include <utility>
16
17 #include "absl/strings/string_view.h"
18 #include "api/ref_counted_base.h"
19 #include "rtc_base/synchronization/mutex.h"
20 #include "rtc_base/thread_annotations.h"
21
22 #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"
39 #include "rtc_base/platform_thread.h"
40 #include "rtc_base/task_queue.h"
41 #include "rtc_base/third_party/sigslot/sigslot.h" // for signal_with_thread...
42
43 #if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
44 #include <dispatch/dispatch.h>
45 #endif
46
47 namespace rtc {
48
49 #if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
50 namespace {
51
GlobalGcdRunTask(void * context)52 void GlobalGcdRunTask(void* context) {
53 std::unique_ptr<absl::AnyInvocable<void() &&>> task(
54 static_cast<absl::AnyInvocable<void() &&>*>(context));
55 std::move (*task)();
56 }
57
58 // Post a task into the system-defined global concurrent queue.
PostTaskToGlobalQueue(std::unique_ptr<absl::AnyInvocable<void ()&&>> task)59 void PostTaskToGlobalQueue(
60 std::unique_ptr<absl::AnyInvocable<void() &&>> task) {
61 dispatch_queue_global_t global_queue =
62 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
63 dispatch_async_f(global_queue, task.release(), &GlobalGcdRunTask);
64 }
65
66 } // namespace
67 #endif
68
ResolveHostname(absl::string_view hostname,int family,std::vector<IPAddress> * addresses)69 int ResolveHostname(absl::string_view hostname,
70 int family,
71 std::vector<IPAddress>* addresses) {
72 #ifdef __native_client__
73 RTC_DCHECK_NOTREACHED();
74 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;
84 // `family` here will almost always be AF_UNSPEC, because `family` comes from
85 // 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;
102 int ret =
103 getaddrinfo(std::string(hostname).c_str(), nullptr, &hints, &result);
104 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
121 struct 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
AsyncResolver()129 AsyncResolver::AsyncResolver() : error_(-1), state_(new State) {}
130
~AsyncResolver()131 AsyncResolver::~AsyncResolver() {
132 RTC_DCHECK_RUN_ON(&sequence_checker_);
133
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
RunResolution(void * obj)140 void RunResolution(void* obj) {
141 std::function<void()>* function_ptr =
142 static_cast<std::function<void()>*>(obj);
143 (*function_ptr)();
144 delete function_ptr;
145 }
146
Start(const SocketAddress & addr)147 void AsyncResolver::Start(const SocketAddress& addr) {
148 Start(addr, addr.family());
149 }
150
Start(const SocketAddress & addr,int family)151 void AsyncResolver::Start(const SocketAddress& addr, int family) {
152 RTC_DCHECK_RUN_ON(&sequence_checker_);
153 RTC_DCHECK(!destroy_called_);
154 addr_ = addr;
155 auto thread_function =
156 [this, addr, family, caller_task_queue = webrtc::TaskQueueBase::Current(),
157 state = state_] {
158 std::vector<IPAddress> addresses;
159 int error = ResolveHostname(addr.hostname(), family, &addresses);
160 webrtc::MutexLock lock(&state->mutex);
161 if (state->status == State::Status::kLive) {
162 caller_task_queue->PostTask(
163 [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 }
175 });
176 }
177 };
178 #if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
179 PostTaskToGlobalQueue(
180 std::make_unique<absl::AnyInvocable<void() &&>>(thread_function));
181 #else
182 PlatformThread::SpawnDetached(std::move(thread_function), "AsyncResolver");
183 #endif
184 }
185
GetResolvedAddress(int family,SocketAddress * addr) const186 bool 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
GetError() const202 int AsyncResolver::GetError() const {
203 RTC_DCHECK_RUN_ON(&sequence_checker_);
204 RTC_DCHECK(!destroy_called_);
205 return error_;
206 }
207
Destroy(bool wait)208 void AsyncResolver::Destroy(bool wait) {
209 // Some callers have trouble guaranteeing that Destroy is called on the
210 // sequence guarded by `sequence_checker_`.
211 // RTC_DCHECK_RUN_ON(&sequence_checker_);
212 RTC_DCHECK(!destroy_called_);
213 destroy_called_ = true;
214 MaybeSelfDestruct();
215 }
216
addresses() const217 const std::vector<IPAddress>& AsyncResolver::addresses() const {
218 RTC_DCHECK_RUN_ON(&sequence_checker_);
219 RTC_DCHECK(!destroy_called_);
220 return addresses_;
221 }
222
ResolveDone(std::vector<IPAddress> addresses,int error)223 void 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
MaybeSelfDestruct()231 void AsyncResolver::MaybeSelfDestruct() {
232 if (!recursion_check_) {
233 delete this;
234 } else {
235 recursion_check_ = false;
236 }
237 }
238
239 } // namespace rtc
240