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