blob: 231e4fad989b9940d1e3a371c5538f1c7d48d613 [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)
44#include "rtc_base/task_queue_gcd.h"
45#endif
46
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010047namespace rtc {
48
49int ResolveHostname(const std::string& hostname,
50 int family,
51 std::vector<IPAddress>* addresses) {
52#ifdef __native_client__
53 RTC_NOTREACHED();
54 RTC_LOG(LS_WARNING) << "ResolveHostname() is not implemented for NaCl";
55 return -1;
56#else // __native_client__
57 if (!addresses) {
58 return -1;
59 }
60 addresses->clear();
61 struct addrinfo* result = nullptr;
62 struct addrinfo hints = {0};
63 hints.ai_family = family;
Artem Titov96e3b992021-07-26 16:03:14 +020064 // `family` here will almost always be AF_UNSPEC, because `family` comes from
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010065 // AsyncResolver::addr_.family(), which comes from a SocketAddress constructed
66 // with a hostname. When a SocketAddress is constructed with a hostname, its
67 // family is AF_UNSPEC. However, if someday in the future we construct
68 // a SocketAddress with both a hostname and a family other than AF_UNSPEC,
69 // then it would be possible to get a specific family value here.
70
71 // The behavior of AF_UNSPEC is roughly "get both ipv4 and ipv6", as
72 // documented by the various operating systems:
73 // Linux: http://man7.org/linux/man-pages/man3/getaddrinfo.3.html
74 // Windows: https://msdn.microsoft.com/en-us/library/windows/desktop/
75 // ms738520(v=vs.85).aspx
76 // Mac: https://developer.apple.com/legacy/library/documentation/Darwin/
77 // Reference/ManPages/man3/getaddrinfo.3.html
78 // Android (source code, not documentation):
79 // https://android.googlesource.com/platform/bionic/+/
80 // 7e0bfb511e85834d7c6cb9631206b62f82701d60/libc/netbsd/net/getaddrinfo.c#1657
81 hints.ai_flags = AI_ADDRCONFIG;
82 int ret = getaddrinfo(hostname.c_str(), nullptr, &hints, &result);
83 if (ret != 0) {
84 return ret;
85 }
86 struct addrinfo* cursor = result;
87 for (; cursor; cursor = cursor->ai_next) {
88 if (family == AF_UNSPEC || cursor->ai_family == family) {
89 IPAddress ip;
90 if (IPFromAddrInfo(cursor, &ip)) {
91 addresses->push_back(ip);
92 }
93 }
94 }
95 freeaddrinfo(result);
96 return 0;
97#endif // !__native_client__
98}
99
Markus Handell1366b0f2021-04-21 10:22:34 +0200100struct AsyncResolver::State : public RefCountedBase {
101 webrtc::Mutex mutex;
102 enum class Status {
103 kLive,
104 kDead
105 } status RTC_GUARDED_BY(mutex) = Status::kLive;
106};
107
108AsyncResolver::AsyncResolver() : error_(-1), state_(new State) {}
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100109
110AsyncResolver::~AsyncResolver() {
111 RTC_DCHECK_RUN_ON(&sequence_checker_);
Markus Handell1366b0f2021-04-21 10:22:34 +0200112
113 // Ensure the thread isn't using a stale reference to the current task queue,
114 // or calling into ResolveDone post destruction.
115 webrtc::MutexLock lock(&state_->mutex);
116 state_->status = State::Status::kDead;
117}
118
119void RunResolution(void* obj) {
120 std::function<void()>* function_ptr =
121 static_cast<std::function<void()>*>(obj);
122 (*function_ptr)();
123 delete function_ptr;
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100124}
125
126void AsyncResolver::Start(const SocketAddress& addr) {
127 RTC_DCHECK_RUN_ON(&sequence_checker_);
128 RTC_DCHECK(!destroy_called_);
129 addr_ = addr;
Byoungchan Lee7284bd42021-10-06 20:25:39 +0900130 auto thread_function =
Markus Handell1366b0f2021-04-21 10:22:34 +0200131 [this, addr, caller_task_queue = webrtc::TaskQueueBase::Current(),
132 state = state_] {
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100133 std::vector<IPAddress> addresses;
134 int error =
135 ResolveHostname(addr.hostname().c_str(), addr.family(), &addresses);
Markus Handell1366b0f2021-04-21 10:22:34 +0200136 webrtc::MutexLock lock(&state->mutex);
137 if (state->status == State::Status::kLive) {
138 caller_task_queue->PostTask(webrtc::ToQueuedTask(
139 [this, error, addresses = std::move(addresses), state] {
140 bool live;
141 {
142 // ResolveDone can lead to instance destruction, so make sure
143 // we don't deadlock.
144 webrtc::MutexLock lock(&state->mutex);
145 live = state->status == State::Status::kLive;
146 }
147 if (live) {
148 RTC_DCHECK_RUN_ON(&sequence_checker_);
149 ResolveDone(std::move(addresses), error);
150 }
151 }));
152 }
Byoungchan Lee7284bd42021-10-06 20:25:39 +0900153 };
154#if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
155 webrtc::PostTaskToGlobalQueue(
156 webrtc::ToQueuedTask(std::move(thread_function)));
157#else
158 PlatformThread::SpawnDetached(std::move(thread_function), "AsyncResolver");
159#endif
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100160}
161
162bool AsyncResolver::GetResolvedAddress(int family, SocketAddress* addr) const {
163 RTC_DCHECK_RUN_ON(&sequence_checker_);
164 RTC_DCHECK(!destroy_called_);
165 if (error_ != 0 || addresses_.empty())
166 return false;
167
168 *addr = addr_;
169 for (size_t i = 0; i < addresses_.size(); ++i) {
170 if (family == addresses_[i].family()) {
171 addr->SetResolvedIP(addresses_[i]);
172 return true;
173 }
174 }
175 return false;
176}
177
178int AsyncResolver::GetError() const {
179 RTC_DCHECK_RUN_ON(&sequence_checker_);
180 RTC_DCHECK(!destroy_called_);
181 return error_;
182}
183
184void AsyncResolver::Destroy(bool wait) {
185 // Some callers have trouble guaranteeing that Destroy is called on the
Artem Titov96e3b992021-07-26 16:03:14 +0200186 // sequence guarded by `sequence_checker_`.
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +0100187 // RTC_DCHECK_RUN_ON(&sequence_checker_);
188 RTC_DCHECK(!destroy_called_);
189 destroy_called_ = true;
190 MaybeSelfDestruct();
191}
192
193const std::vector<IPAddress>& AsyncResolver::addresses() const {
194 RTC_DCHECK_RUN_ON(&sequence_checker_);
195 RTC_DCHECK(!destroy_called_);
196 return addresses_;
197}
198
199void AsyncResolver::ResolveDone(std::vector<IPAddress> addresses, int error) {
200 addresses_ = addresses;
201 error_ = error;
202 recursion_check_ = true;
203 SignalDone(this);
204 MaybeSelfDestruct();
205}
206
207void AsyncResolver::MaybeSelfDestruct() {
208 if (!recursion_check_) {
209 delete this;
210 } else {
211 recursion_check_ = false;
212 }
213}
214
215} // namespace rtc