blob: ad1598f214ece97462ee8fa8d9a9a8cc14f9697c [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
Markus Handell1366b0f2021-04-21 10:22:34 +020017#include "api/ref_counted_base.h"
18#include "rtc_base/synchronization/mutex.h"
19#include "rtc_base/thread_annotations.h"
20
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010021#if defined(WEBRTC_WIN)
22#include <ws2spi.h>
23#include <ws2tcpip.h>
24
25#include "rtc_base/win32.h"
26#endif
27#if defined(WEBRTC_POSIX) && !defined(__native_client__)
28#if defined(WEBRTC_ANDROID)
29#include "rtc_base/ifaddrs_android.h"
30#else
31#include <ifaddrs.h>
32#endif
33#endif // defined(WEBRTC_POSIX) && !defined(__native_client__)
34
35#include "api/task_queue/task_queue_base.h"
36#include "rtc_base/ip_address.h"
37#include "rtc_base/logging.h"
Markus Handell1366b0f2021-04-21 10:22:34 +020038#include "rtc_base/platform_thread.h"
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010039#include "rtc_base/task_queue.h"
40#include "rtc_base/task_utils/to_queued_task.h"
41#include "rtc_base/third_party/sigslot/sigslot.h" // for signal_with_thread...
42
Byoungchan Lee7284bd42021-10-06 20:25:39 +090043#if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
Byoungchan Lee08438fc2021-10-12 22:53:35 +090044#include <dispatch/dispatch.h>
Byoungchan Lee7284bd42021-10-06 20:25:39 +090045#endif
46
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010047namespace rtc {
48
Byoungchan Lee08438fc2021-10-12 22:53:35 +090049#if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
50namespace {
51
52void GlobalGcdRunTask(void* context) {
53 std::unique_ptr<webrtc::QueuedTask> task(
54 static_cast<webrtc::QueuedTask*>(context));
55 task->Run();
56}
57
58// Post a task into the system-defined global concurrent queue.
59void PostTaskToGlobalQueue(std::unique_ptr<webrtc::QueuedTask> task) {
60 dispatch_queue_global_t global_queue =
61 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
62 webrtc::QueuedTask* context = task.release();
63 dispatch_async_f(global_queue, context, &GlobalGcdRunTask);
64}
65
66} // namespace
67#endif
68
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010069int ResolveHostname(const std::string& hostname,
70 int family,
71 std::vector<IPAddress>* addresses) {
72#ifdef __native_client__
Artem Titovd3251962021-11-15 16:57:07 +010073 RTC_DCHECK_NOTREACHED();
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010074 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 16:03:14 +020084 // `family` here will almost always be AF_UNSPEC, because `family` comes from
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010085 // 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 = getaddrinfo(hostname.c_str(), nullptr, &hints, &result);
103 if (ret != 0) {
104 return ret;
105 }
106 struct addrinfo* cursor = result;
107 for (; cursor; cursor = cursor->ai_next) {
108 if (family == AF_UNSPEC || cursor->ai_family == family) {
109 IPAddress ip;
110 if (IPFromAddrInfo(cursor, &ip)) {
111 addresses->push_back(ip);
112 }
113 }
114 }
115 freeaddrinfo(result);
116 return 0;
117#endif // !__native_client__
118}
119
Markus Handell1366b0f2021-04-21 10:22:34 +0200120struct AsyncResolver::State : public RefCountedBase {
121 webrtc::Mutex mutex;
122 enum class Status {
123 kLive,
124 kDead
125 } status RTC_GUARDED_BY(mutex) = Status::kLive;
126};
127
128AsyncResolver::AsyncResolver() : error_(-1), state_(new State) {}
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100129
130AsyncResolver::~AsyncResolver() {
131 RTC_DCHECK_RUN_ON(&sequence_checker_);
Markus Handell1366b0f2021-04-21 10:22:34 +0200132
133 // Ensure the thread isn't using a stale reference to the current task queue,
134 // or calling into ResolveDone post destruction.
135 webrtc::MutexLock lock(&state_->mutex);
136 state_->status = State::Status::kDead;
137}
138
139void RunResolution(void* obj) {
140 std::function<void()>* function_ptr =
141 static_cast<std::function<void()>*>(obj);
142 (*function_ptr)();
143 delete function_ptr;
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100144}
145
146void AsyncResolver::Start(const SocketAddress& addr) {
147 RTC_DCHECK_RUN_ON(&sequence_checker_);
148 RTC_DCHECK(!destroy_called_);
149 addr_ = addr;
Byoungchan Lee7284bd42021-10-06 20:25:39 +0900150 auto thread_function =
Markus Handell1366b0f2021-04-21 10:22:34 +0200151 [this, addr, caller_task_queue = webrtc::TaskQueueBase::Current(),
152 state = state_] {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100153 std::vector<IPAddress> addresses;
154 int error =
155 ResolveHostname(addr.hostname().c_str(), addr.family(), &addresses);
Markus Handell1366b0f2021-04-21 10:22:34 +0200156 webrtc::MutexLock lock(&state->mutex);
157 if (state->status == State::Status::kLive) {
158 caller_task_queue->PostTask(webrtc::ToQueuedTask(
159 [this, error, addresses = std::move(addresses), state] {
160 bool live;
161 {
162 // ResolveDone can lead to instance destruction, so make sure
163 // we don't deadlock.
164 webrtc::MutexLock lock(&state->mutex);
165 live = state->status == State::Status::kLive;
166 }
167 if (live) {
168 RTC_DCHECK_RUN_ON(&sequence_checker_);
169 ResolveDone(std::move(addresses), error);
170 }
171 }));
172 }
Byoungchan Lee7284bd42021-10-06 20:25:39 +0900173 };
174#if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
Byoungchan Lee08438fc2021-10-12 22:53:35 +0900175 PostTaskToGlobalQueue(webrtc::ToQueuedTask(std::move(thread_function)));
Byoungchan Lee7284bd42021-10-06 20:25:39 +0900176#else
177 PlatformThread::SpawnDetached(std::move(thread_function), "AsyncResolver");
178#endif
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100179}
180
181bool AsyncResolver::GetResolvedAddress(int family, SocketAddress* addr) const {
182 RTC_DCHECK_RUN_ON(&sequence_checker_);
183 RTC_DCHECK(!destroy_called_);
184 if (error_ != 0 || addresses_.empty())
185 return false;
186
187 *addr = addr_;
188 for (size_t i = 0; i < addresses_.size(); ++i) {
189 if (family == addresses_[i].family()) {
190 addr->SetResolvedIP(addresses_[i]);
191 return true;
192 }
193 }
194 return false;
195}
196
197int AsyncResolver::GetError() const {
198 RTC_DCHECK_RUN_ON(&sequence_checker_);
199 RTC_DCHECK(!destroy_called_);
200 return error_;
201}
202
203void AsyncResolver::Destroy(bool wait) {
204 // Some callers have trouble guaranteeing that Destroy is called on the
Artem Titov96e3b992021-07-26 16:03:14 +0200205 // sequence guarded by `sequence_checker_`.
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100206 // RTC_DCHECK_RUN_ON(&sequence_checker_);
207 RTC_DCHECK(!destroy_called_);
208 destroy_called_ = true;
209 MaybeSelfDestruct();
210}
211
212const std::vector<IPAddress>& AsyncResolver::addresses() const {
213 RTC_DCHECK_RUN_ON(&sequence_checker_);
214 RTC_DCHECK(!destroy_called_);
215 return addresses_;
216}
217
218void AsyncResolver::ResolveDone(std::vector<IPAddress> addresses, int error) {
219 addresses_ = addresses;
220 error_ = error;
221 recursion_check_ = true;
222 SignalDone(this);
223 MaybeSelfDestruct();
224}
225
226void AsyncResolver::MaybeSelfDestruct() {
227 if (!recursion_check_) {
228 delete this;
229 } else {
230 recursion_check_ = false;
231 }
232}
233
234} // namespace rtc