blob: 6939227ef9c7a53a3fb6664cfa71c0c206058b1a [file] [log] [blame]
Mike Yub601ff72018-11-01 20:07:00 +08001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ken Chen5471dca2019-04-15 15:25:35 +080017#define LOG_TAG "resolv"
Mike Yub601ff72018-11-01 20:07:00 +080018
Mike Yu303b0df2018-12-24 17:05:02 +080019#include "PrivateDnsConfiguration.h"
20
Mike Yu3d5130d2020-12-21 17:57:18 +080021#include <android-base/format.h>
chenbruceaff85842019-05-31 15:46:42 +080022#include <android-base/logging.h>
Mike Yu04f1d482019-08-08 11:09:32 +080023#include <android-base/stringprintf.h>
Mike Yu1aede812021-05-11 14:49:30 +080024#include <netdutils/Stopwatch.h>
Mike Yu04f1d482019-08-08 11:09:32 +080025#include <netdutils/ThreadUtil.h>
Mike Yub601ff72018-11-01 20:07:00 +080026#include <sys/socket.h>
27
Bernie Innocentiec4219b2019-01-30 11:16:36 +090028#include "DnsTlsTransport.h"
Mike Yu1aede812021-05-11 14:49:30 +080029#include "Experiments.h"
Mike Yu303b0df2018-12-24 17:05:02 +080030#include "ResolverEventReporter.h"
Bernie Innocentiec4219b2019-01-30 11:16:36 +090031#include "netd_resolv/resolv.h"
Mike Yu1aede812021-05-11 14:49:30 +080032#include "resolv_cache.h"
33#include "resolv_private.h"
Mike Yu9c720102019-11-14 11:34:33 +080034#include "util.h"
Mike Yub601ff72018-11-01 20:07:00 +080035
paulhu0664f692020-12-14 16:48:26 +080036using aidl::android::net::resolv::aidl::IDnsResolverUnsolicitedEventListener;
37using aidl::android::net::resolv::aidl::PrivateDnsValidationEventParcel;
Mike Yucb902c92020-05-20 19:26:56 +080038using android::base::StringPrintf;
39using android::netdutils::setThreadName;
Mike Yu1aede812021-05-11 14:49:30 +080040using android::netdutils::Stopwatch;
Mike Yua772c202019-09-23 17:47:21 +080041using std::chrono::milliseconds;
42
Mike Yub601ff72018-11-01 20:07:00 +080043namespace android {
Mike Yub601ff72018-11-01 20:07:00 +080044namespace net {
45
Mike Yub601ff72018-11-01 20:07:00 +080046bool parseServer(const char* server, sockaddr_storage* parsed) {
Nick Desaulnierscd6395a2019-10-11 09:15:24 -070047 addrinfo hints = {
48 .ai_flags = AI_NUMERICHOST | AI_NUMERICSERV,
49 .ai_family = AF_UNSPEC,
50 };
Mike Yub601ff72018-11-01 20:07:00 +080051 addrinfo* res;
52
53 int err = getaddrinfo(server, "853", &hints, &res);
54 if (err != 0) {
chenbruceaff85842019-05-31 15:46:42 +080055 LOG(WARNING) << "Failed to parse server address (" << server << "): " << gai_strerror(err);
Mike Yub601ff72018-11-01 20:07:00 +080056 return false;
57 }
58
59 memcpy(parsed, res->ai_addr, res->ai_addrlen);
60 freeaddrinfo(res);
61 return true;
62}
63
Mike Yub601ff72018-11-01 20:07:00 +080064int PrivateDnsConfiguration::set(int32_t netId, uint32_t mark,
65 const std::vector<std::string>& servers, const std::string& name,
Mike Yu40e67072019-10-09 21:14:09 +080066 const std::string& caCert) {
Mike Yu04f1d482019-08-08 11:09:32 +080067 LOG(DEBUG) << "PrivateDnsConfiguration::set(" << netId << ", 0x" << std::hex << mark << std::dec
Mike Yu40e67072019-10-09 21:14:09 +080068 << ", " << servers.size() << ", " << name << ")";
Mike Yub601ff72018-11-01 20:07:00 +080069
70 // Parse the list of servers that has been passed in
Mike Yufa985f72020-11-23 20:24:21 +080071 PrivateDnsTracker tmp;
Mike Yu40e67072019-10-09 21:14:09 +080072 for (const auto& s : servers) {
Mike Yub601ff72018-11-01 20:07:00 +080073 sockaddr_storage parsed;
Mike Yu40e67072019-10-09 21:14:09 +080074 if (!parseServer(s.c_str(), &parsed)) {
Mike Yub601ff72018-11-01 20:07:00 +080075 return -EINVAL;
76 }
Mike Yucf56d232021-04-29 19:37:25 +080077 auto server = std::make_unique<DnsTlsServer>(parsed);
78 server->name = name;
79 server->certificate = caCert;
80 server->mark = mark;
81 tmp[ServerIdentity(*server)] = std::move(server);
Mike Yub601ff72018-11-01 20:07:00 +080082 }
83
84 std::lock_guard guard(mPrivateDnsLock);
waynema0e73c2e2019-07-31 15:04:08 +080085 if (!name.empty()) {
Mike Yub601ff72018-11-01 20:07:00 +080086 mPrivateDnsModes[netId] = PrivateDnsMode::STRICT;
Mike Yufa985f72020-11-23 20:24:21 +080087 } else if (!tmp.empty()) {
Mike Yub601ff72018-11-01 20:07:00 +080088 mPrivateDnsModes[netId] = PrivateDnsMode::OPPORTUNISTIC;
89 } else {
90 mPrivateDnsModes[netId] = PrivateDnsMode::OFF;
91 mPrivateDnsTransports.erase(netId);
Mike Yuf7717f52020-11-24 17:31:12 +080092 // TODO: signal validation threads to stop.
Mike Yub601ff72018-11-01 20:07:00 +080093 return 0;
94 }
95
96 // Create the tracker if it was not present
Mike Yuf7717f52020-11-24 17:31:12 +080097 auto& tracker = mPrivateDnsTransports[netId];
Mike Yub601ff72018-11-01 20:07:00 +080098
Mike Yuf7717f52020-11-24 17:31:12 +080099 // Add the servers if not contained in tracker.
Mike Yucf56d232021-04-29 19:37:25 +0800100 for (auto& [identity, server] : tmp) {
Mike Yuf7717f52020-11-24 17:31:12 +0800101 if (tracker.find(identity) == tracker.end()) {
Mike Yucf56d232021-04-29 19:37:25 +0800102 tracker[identity] = std::move(server);
Mike Yuf7717f52020-11-24 17:31:12 +0800103 }
104 }
Mike Yu3334a5e2020-11-19 13:33:17 +0800105
Mike Yuf7717f52020-11-24 17:31:12 +0800106 for (auto& [identity, server] : tracker) {
107 const bool active = tmp.find(identity) != tmp.end();
Mike Yucf56d232021-04-29 19:37:25 +0800108 server->setActive(active);
Mike Yuf7717f52020-11-24 17:31:12 +0800109
110 // For simplicity, deem the validation result of inactive servers as unreliable.
Mike Yucf56d232021-04-29 19:37:25 +0800111 if (!server->active() && server->validationState() == Validation::success) {
Mike Yuf7717f52020-11-24 17:31:12 +0800112 updateServerState(identity, Validation::success_but_expired, netId);
113 }
114
Mike Yucf56d232021-04-29 19:37:25 +0800115 if (needsValidation(*server)) {
Mike Yufa985f72020-11-23 20:24:21 +0800116 updateServerState(identity, Validation::in_process, netId);
Mike Yuad96ef82021-02-20 18:35:14 +0800117 startValidation(identity, netId, false);
Mike Yub601ff72018-11-01 20:07:00 +0800118 }
119 }
Mike Yue655b1d2019-08-28 17:49:59 +0800120
Mike Yu8d9da4a2020-11-09 17:09:14 +0800121 return 0;
Mike Yub601ff72018-11-01 20:07:00 +0800122}
123
Mike Yu82ae84b2020-12-02 21:04:40 +0800124PrivateDnsStatus PrivateDnsConfiguration::getStatus(unsigned netId) const {
Mike Yub601ff72018-11-01 20:07:00 +0800125 PrivateDnsStatus status{PrivateDnsMode::OFF, {}};
Mike Yub601ff72018-11-01 20:07:00 +0800126 std::lock_guard guard(mPrivateDnsLock);
127
128 const auto mode = mPrivateDnsModes.find(netId);
129 if (mode == mPrivateDnsModes.end()) return status;
130 status.mode = mode->second;
131
132 const auto netPair = mPrivateDnsTransports.find(netId);
133 if (netPair != mPrivateDnsTransports.end()) {
Mike Yufa985f72020-11-23 20:24:21 +0800134 for (const auto& [_, server] : netPair->second) {
Mike Yucf56d232021-04-29 19:37:25 +0800135 if (server->isDot() && server->active()) {
136 DnsTlsServer& dotServer = *static_cast<DnsTlsServer*>(server.get());
137 status.serversMap.emplace(dotServer, server->validationState());
Mike Yuf7717f52020-11-24 17:31:12 +0800138 }
Mike Yucf56d232021-04-29 19:37:25 +0800139 // TODO: also add DoH server to the map.
Mike Yub601ff72018-11-01 20:07:00 +0800140 }
141 }
142
143 return status;
144}
145
Mike Yub601ff72018-11-01 20:07:00 +0800146void PrivateDnsConfiguration::clear(unsigned netId) {
chenbruceaff85842019-05-31 15:46:42 +0800147 LOG(DEBUG) << "PrivateDnsConfiguration::clear(" << netId << ")";
Mike Yub601ff72018-11-01 20:07:00 +0800148 std::lock_guard guard(mPrivateDnsLock);
149 mPrivateDnsModes.erase(netId);
150 mPrivateDnsTransports.erase(netId);
151}
152
Mike Yu82ae84b2020-12-02 21:04:40 +0800153base::Result<void> PrivateDnsConfiguration::requestValidation(unsigned netId,
Mike Yuad96ef82021-02-20 18:35:14 +0800154 const ServerIdentity& identity,
Mike Yu82ae84b2020-12-02 21:04:40 +0800155 uint32_t mark) {
Mike Yue60ab412020-12-01 17:56:12 +0800156 std::lock_guard guard(mPrivateDnsLock);
Mike Yu82ae84b2020-12-02 21:04:40 +0800157
158 // Running revalidation requires to mark the server as in_process, which means the server
159 // won't be used until the validation passes. It's necessary and safe to run revalidation
160 // when in private DNS opportunistic mode, because there's a fallback mechanics even if
161 // all of the private DNS servers are in in_process state.
162 if (auto it = mPrivateDnsModes.find(netId); it == mPrivateDnsModes.end()) {
163 return Errorf("NetId not found in mPrivateDnsModes");
164 } else if (it->second != PrivateDnsMode::OPPORTUNISTIC) {
165 return Errorf("Private DNS setting is not opportunistic mode");
166 }
167
Mike Yuad96ef82021-02-20 18:35:14 +0800168 auto result = getPrivateDnsLocked(identity, netId);
169 if (!result.ok()) {
170 return result.error();
Mike Yue60ab412020-12-01 17:56:12 +0800171 }
172
Mike Yucf56d232021-04-29 19:37:25 +0800173 const IPrivateDnsServer* server = result.value();
Mike Yue60ab412020-12-01 17:56:12 +0800174
Mike Yucf56d232021-04-29 19:37:25 +0800175 if (!server->active()) return Errorf("Server is not active");
Mike Yue60ab412020-12-01 17:56:12 +0800176
Mike Yucf56d232021-04-29 19:37:25 +0800177 if (server->validationState() != Validation::success) {
Mike Yu82ae84b2020-12-02 21:04:40 +0800178 return Errorf("Server validation state mismatched");
179 }
Mike Yue60ab412020-12-01 17:56:12 +0800180
181 // Don't run the validation if |mark| (from android_net_context.dns_mark) is different.
182 // This is to protect validation from running on unexpected marks.
183 // Validation should be associated with a mark gotten by system permission.
Mike Yucf56d232021-04-29 19:37:25 +0800184 if (server->validationMark() != mark) return Errorf("Socket mark mismatched");
Mike Yue60ab412020-12-01 17:56:12 +0800185
186 updateServerState(identity, Validation::in_process, netId);
Mike Yuad96ef82021-02-20 18:35:14 +0800187 startValidation(identity, netId, true);
Mike Yu82ae84b2020-12-02 21:04:40 +0800188 return {};
Mike Yue60ab412020-12-01 17:56:12 +0800189}
190
Mike Yuad96ef82021-02-20 18:35:14 +0800191void PrivateDnsConfiguration::startValidation(const ServerIdentity& identity, unsigned netId,
192 bool isRevalidation) {
193 // This ensures that the thread sends probe at least once in case
194 // the server is removed before the thread starts running.
195 // TODO: consider moving these code to the thread.
196 const auto result = getPrivateDnsLocked(identity, netId);
197 if (!result.ok()) return;
Mike Yucf56d232021-04-29 19:37:25 +0800198 DnsTlsServer server = *static_cast<const DnsTlsServer*>(result.value());
Mike Yuad96ef82021-02-20 18:35:14 +0800199
200 std::thread validate_thread([this, identity, server, netId, isRevalidation] {
Mike Yucb902c92020-05-20 19:26:56 +0800201 setThreadName(StringPrintf("TlsVerify_%u", netId).c_str());
Mike Yu04f1d482019-08-08 11:09:32 +0800202
Mike Yu1aede812021-05-11 14:49:30 +0800203 const bool avoidBadPrivateDns =
204 Experiments::getInstance()->getFlag("avoid_bad_private_dns", 0);
205 std::optional<int64_t> latencyThreshold;
206 if (avoidBadPrivateDns) {
207 const int maxLatency = Experiments::getInstance()->getFlag(
208 "max_private_dns_latency_threshold_ms", kMaxPrivateDnsLatencyThresholdMs);
209 const int minLatency = Experiments::getInstance()->getFlag(
210 "min_private_dns_latency_threshold_ms", kMinPrivateDnsLatencyThresholdMs);
211 const auto do53Latency = resolv_stats_get_average_response_time(netId, PROTO_UDP);
212 const int target =
213 do53Latency.has_value() ? (3 * do53Latency.value().count() / 1000) : 0;
214
215 // The time is limited to the range [minLatency, maxLatency].
216 latencyThreshold = std::clamp(target, minLatency, maxLatency);
217 }
218 const bool isOpportunisticMode = server.name.empty();
219
Mike Yub601ff72018-11-01 20:07:00 +0800220 // cat /proc/sys/net/ipv4/tcp_syn_retries yields "6".
221 //
222 // Start with a 1 minute delay and backoff to once per hour.
223 //
224 // Assumptions:
225 // [1] Each TLS validation is ~10KB of certs+handshake+payload.
226 // [2] Network typically provision clients with <=4 nameservers.
227 // [3] Average month has 30 days.
228 //
229 // Each validation pass in a given hour is ~1.2MB of data. And 24
230 // such validation passes per day is about ~30MB per month, in the
231 // worst case. Otherwise, this will cost ~600 SYNs per month
232 // (6 SYNs per ip, 4 ips per validation pass, 24 passes per day).
Mike Yu8058bd02021-05-13 16:44:18 +0800233 auto backoff = mBackoffBuilder.build();
Mike Yub601ff72018-11-01 20:07:00 +0800234
235 while (true) {
236 // ::validate() is a blocking call that performs network operations.
237 // It can take milliseconds to minutes, up to the SYN retry limit.
Mike Yu74770542020-12-15 14:25:21 +0800238 LOG(WARNING) << "Validating DnsTlsServer " << server.toIpString() << " with mark 0x"
Mike Yu690b19f2021-02-08 20:32:57 +0800239 << std::hex << server.validationMark();
Mike Yub601ff72018-11-01 20:07:00 +0800240
Mike Yu1aede812021-05-11 14:49:30 +0800241 Stopwatch stopwatch;
242 const bool gotAnswer = DnsTlsTransport::validate(server, server.validationMark());
243 const int32_t timeTaken = saturate_cast<int32_t>(stopwatch.timeTakenUs() / 1000);
244 LOG(WARNING) << fmt::format("validateDnsTlsServer returned {} for {}, took {}ms",
245 gotAnswer, server.toIpString(), timeTaken);
246
247 const int64_t targetTime = latencyThreshold.value_or(INT64_MAX);
248 bool latencyTooHigh = false;
249 if (isOpportunisticMode && timeTaken > targetTime) {
250 latencyTooHigh = true;
251 LOG(WARNING) << "validateDnsTlsServer took too long: threshold is " << targetTime
252 << "ms";
253 }
254
255 // TODO: combine these boolean variables into a bitwise variable.
256 const bool needs_reeval = this->recordPrivateDnsValidation(
257 identity, netId, gotAnswer, isRevalidation, latencyTooHigh);
Mike Yu82ae84b2020-12-02 21:04:40 +0800258
Mike Yub601ff72018-11-01 20:07:00 +0800259 if (!needs_reeval) {
260 break;
261 }
262
263 if (backoff.hasNextTimeout()) {
Mike Yuf7717f52020-11-24 17:31:12 +0800264 // TODO: make the thread able to receive signals to shutdown early.
Mike Yub601ff72018-11-01 20:07:00 +0800265 std::this_thread::sleep_for(backoff.getNextTimeout());
266 } else {
267 break;
268 }
269 }
Mike Yu1aede812021-05-11 14:49:30 +0800270
271 this->updateServerLatencyThreshold(identity, latencyThreshold, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800272 });
273 validate_thread.detach();
274}
275
Mike Yuad96ef82021-02-20 18:35:14 +0800276void PrivateDnsConfiguration::sendPrivateDnsValidationEvent(const ServerIdentity& identity,
paulhu0664f692020-12-14 16:48:26 +0800277 unsigned netId, bool success) {
278 LOG(DEBUG) << "Sending validation " << (success ? "success" : "failure") << " event on netId "
Mike Yuad96ef82021-02-20 18:35:14 +0800279 << netId << " for " << identity.sockaddr.ip().toString() << " with hostname {"
280 << identity.provider << "}";
paulhu0664f692020-12-14 16:48:26 +0800281 // Send a validation event to NetdEventListenerService.
282 const auto& listeners = ResolverEventReporter::getInstance().getListeners();
283 if (listeners.empty()) {
284 LOG(ERROR)
285 << "Validation event not sent since no INetdEventListener receiver is available.";
286 }
287 for (const auto& it : listeners) {
Mike Yuad96ef82021-02-20 18:35:14 +0800288 it->onPrivateDnsValidationEvent(netId, identity.sockaddr.ip().toString(), identity.provider,
289 success);
paulhu0664f692020-12-14 16:48:26 +0800290 }
291
292 // Send a validation event to unsolicited event listeners.
293 const auto& unsolEventListeners = ResolverEventReporter::getInstance().getUnsolEventListeners();
294 const PrivateDnsValidationEventParcel validationEvent = {
295 .netId = static_cast<int32_t>(netId),
Mike Yuad96ef82021-02-20 18:35:14 +0800296 .ipAddress = identity.sockaddr.ip().toString(),
297 .hostname = identity.provider,
paulhu0664f692020-12-14 16:48:26 +0800298 .validation = success ? IDnsResolverUnsolicitedEventListener::VALIDATION_RESULT_SUCCESS
299 : IDnsResolverUnsolicitedEventListener::VALIDATION_RESULT_FAILURE,
300 };
301 for (const auto& it : unsolEventListeners) {
302 it->onPrivateDnsValidationEvent(validationEvent);
303 }
304}
305
Mike Yuad96ef82021-02-20 18:35:14 +0800306bool PrivateDnsConfiguration::recordPrivateDnsValidation(const ServerIdentity& identity,
Mike Yu1aede812021-05-11 14:49:30 +0800307 unsigned netId, bool gotAnswer,
308 bool isRevalidation, bool latencyTooHigh) {
Mike Yub601ff72018-11-01 20:07:00 +0800309 constexpr bool NEEDS_REEVALUATION = true;
310 constexpr bool DONT_REEVALUATE = false;
311
312 std::lock_guard guard(mPrivateDnsLock);
313
314 auto netPair = mPrivateDnsTransports.find(netId);
315 if (netPair == mPrivateDnsTransports.end()) {
chenbruceaff85842019-05-31 15:46:42 +0800316 LOG(WARNING) << "netId " << netId << " was erased during private DNS validation";
Mike Yu453b5e42021-02-19 20:03:07 +0800317 notifyValidationStateUpdate(identity.sockaddr, Validation::fail, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800318 return DONT_REEVALUATE;
319 }
320
321 const auto mode = mPrivateDnsModes.find(netId);
322 if (mode == mPrivateDnsModes.end()) {
chenbruceaff85842019-05-31 15:46:42 +0800323 LOG(WARNING) << "netId " << netId << " has no private DNS validation mode";
Mike Yu453b5e42021-02-19 20:03:07 +0800324 notifyValidationStateUpdate(identity.sockaddr, Validation::fail, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800325 return DONT_REEVALUATE;
326 }
Mike Yub601ff72018-11-01 20:07:00 +0800327
Mike Yu82ae84b2020-12-02 21:04:40 +0800328 bool reevaluationStatus = NEEDS_REEVALUATION;
Mike Yu1aede812021-05-11 14:49:30 +0800329 if (gotAnswer) {
330 if (!latencyTooHigh) {
331 reevaluationStatus = DONT_REEVALUATE;
332 }
Mike Yu82ae84b2020-12-02 21:04:40 +0800333 } else if (mode->second == PrivateDnsMode::OFF) {
334 reevaluationStatus = DONT_REEVALUATE;
335 } else if (mode->second == PrivateDnsMode::OPPORTUNISTIC && !isRevalidation) {
336 reevaluationStatus = DONT_REEVALUATE;
337 }
Mike Yub601ff72018-11-01 20:07:00 +0800338
Mike Yu1aede812021-05-11 14:49:30 +0800339 bool success = gotAnswer;
Mike Yub601ff72018-11-01 20:07:00 +0800340 auto& tracker = netPair->second;
Mike Yufa985f72020-11-23 20:24:21 +0800341 auto serverPair = tracker.find(identity);
Mike Yub601ff72018-11-01 20:07:00 +0800342 if (serverPair == tracker.end()) {
Mike Yuad96ef82021-02-20 18:35:14 +0800343 LOG(WARNING) << "Server " << identity.sockaddr.ip().toString()
chenbruceaff85842019-05-31 15:46:42 +0800344 << " was removed during private DNS validation";
Mike Yub601ff72018-11-01 20:07:00 +0800345 success = false;
346 reevaluationStatus = DONT_REEVALUATE;
Mike Yucf56d232021-04-29 19:37:25 +0800347 } else if (!serverPair->second->active()) {
Mike Yuad96ef82021-02-20 18:35:14 +0800348 LOG(WARNING) << "Server " << identity.sockaddr.ip().toString()
349 << " was removed from the configuration";
Mike Yuf7717f52020-11-24 17:31:12 +0800350 success = false;
351 reevaluationStatus = DONT_REEVALUATE;
Mike Yub601ff72018-11-01 20:07:00 +0800352 }
353
Mike Yu1aede812021-05-11 14:49:30 +0800354 const bool succeededQuickly = success && !latencyTooHigh;
Mike Yub601ff72018-11-01 20:07:00 +0800355
Mike Yu1aede812021-05-11 14:49:30 +0800356 // Send private dns validation result to listeners.
357 sendPrivateDnsValidationEvent(identity, netId, succeededQuickly);
358
359 if (succeededQuickly) {
Mike Yufa985f72020-11-23 20:24:21 +0800360 updateServerState(identity, Validation::success, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800361 } else {
362 // Validation failure is expected if a user is on a captive portal.
363 // TODO: Trigger a second validation attempt after captive portal login
364 // succeeds.
Mike Yu3334a5e2020-11-19 13:33:17 +0800365 const auto result = (reevaluationStatus == NEEDS_REEVALUATION) ? Validation::in_process
366 : Validation::fail;
Mike Yufa985f72020-11-23 20:24:21 +0800367 updateServerState(identity, result, netId);
Mike Yub601ff72018-11-01 20:07:00 +0800368 }
Mike Yu1aede812021-05-11 14:49:30 +0800369 LOG(WARNING) << "Validation " << (succeededQuickly ? "success" : "failed");
Mike Yub601ff72018-11-01 20:07:00 +0800370
371 return reevaluationStatus;
372}
373
Mike Yufa985f72020-11-23 20:24:21 +0800374void PrivateDnsConfiguration::updateServerState(const ServerIdentity& identity, Validation state,
Mike Yu3334a5e2020-11-19 13:33:17 +0800375 uint32_t netId) {
Mike Yuad96ef82021-02-20 18:35:14 +0800376 const auto result = getPrivateDnsLocked(identity, netId);
377 if (!result.ok()) {
Mike Yu453b5e42021-02-19 20:03:07 +0800378 notifyValidationStateUpdate(identity.sockaddr, Validation::fail, netId);
Mike Yufa985f72020-11-23 20:24:21 +0800379 return;
Mike Yu3334a5e2020-11-19 13:33:17 +0800380 }
381
Mike Yuad96ef82021-02-20 18:35:14 +0800382 auto* server = result.value();
Mike Yufa985f72020-11-23 20:24:21 +0800383
Mike Yuad96ef82021-02-20 18:35:14 +0800384 server->setValidationState(state);
Mike Yu453b5e42021-02-19 20:03:07 +0800385 notifyValidationStateUpdate(identity.sockaddr, state, netId);
Mike Yu3d5130d2020-12-21 17:57:18 +0800386
387 RecordEntry record(netId, identity, state);
388 mPrivateDnsLog.push(std::move(record));
Mike Yu3334a5e2020-11-19 13:33:17 +0800389}
390
Mike Yucf56d232021-04-29 19:37:25 +0800391bool PrivateDnsConfiguration::needsValidation(const IPrivateDnsServer& server) const {
Mike Yuf7717f52020-11-24 17:31:12 +0800392 // The server is not expected to be used on the network.
393 if (!server.active()) return false;
Zhang Wei-e7976c1d68adb2019-08-23 23:13:22 -0500394
Mike Yuf7717f52020-11-24 17:31:12 +0800395 // The server is newly added.
396 if (server.validationState() == Validation::unknown_server) return true;
Zhang Wei-e7976c1d68adb2019-08-23 23:13:22 -0500397
Mike Yuf7717f52020-11-24 17:31:12 +0800398 // The server has failed at least one validation attempt. Give it another try.
399 if (server.validationState() == Validation::fail) return true;
400
401 // The previous validation result might be unreliable.
402 if (server.validationState() == Validation::success_but_expired) return true;
403
404 return false;
Mike Yub601ff72018-11-01 20:07:00 +0800405}
406
Mike Yucf56d232021-04-29 19:37:25 +0800407base::Result<IPrivateDnsServer*> PrivateDnsConfiguration::getPrivateDns(
408 const ServerIdentity& identity, unsigned netId) {
Mike Yuad96ef82021-02-20 18:35:14 +0800409 std::lock_guard guard(mPrivateDnsLock);
410 return getPrivateDnsLocked(identity, netId);
411}
412
Mike Yucf56d232021-04-29 19:37:25 +0800413base::Result<IPrivateDnsServer*> PrivateDnsConfiguration::getPrivateDnsLocked(
Mike Yuad96ef82021-02-20 18:35:14 +0800414 const ServerIdentity& identity, unsigned netId) {
415 auto netPair = mPrivateDnsTransports.find(netId);
416 if (netPair == mPrivateDnsTransports.end()) {
417 return Errorf("Failed to get private DNS: netId {} not found", netId);
418 }
419
420 auto iter = netPair->second.find(identity);
421 if (iter == netPair->second.end()) {
422 return Errorf("Failed to get private DNS: server {{{}/{}}} not found", identity.sockaddr,
423 identity.provider);
424 }
425
Mike Yucf56d232021-04-29 19:37:25 +0800426 return iter->second.get();
Mike Yuad96ef82021-02-20 18:35:14 +0800427}
428
Mike Yu1aede812021-05-11 14:49:30 +0800429void PrivateDnsConfiguration::updateServerLatencyThreshold(const ServerIdentity& identity,
430 std::optional<int64_t> latencyThreshold,
431 uint32_t netId) {
432 std::lock_guard guard(mPrivateDnsLock);
433
434 const auto result = getPrivateDnsLocked(identity, netId);
435 if (!result.ok()) return;
436
437 if (result.value()->isDot()) {
438 DnsTlsServer& server = *static_cast<DnsTlsServer*>(result.value());
439 server.setLatencyThreshold(latencyThreshold);
440 LOG(INFO) << "Set latencyThreshold "
441 << (latencyThreshold ? std::to_string(latencyThreshold.value()) + "ms"
442 : "nullopt")
443 << " to " << server.toIpString();
444 }
445}
446
Mike Yua6853e82020-12-11 19:47:06 +0800447void PrivateDnsConfiguration::setObserver(PrivateDnsValidationObserver* observer) {
Mike Yu0ee1dc92020-11-09 14:56:54 +0800448 std::lock_guard guard(mPrivateDnsLock);
449 mObserver = observer;
450}
451
Mike Yu453b5e42021-02-19 20:03:07 +0800452void PrivateDnsConfiguration::notifyValidationStateUpdate(const netdutils::IPSockAddr& sockaddr,
Mike Yu74770542020-12-15 14:25:21 +0800453 Validation validation,
454 uint32_t netId) const {
Mike Yu0ee1dc92020-11-09 14:56:54 +0800455 if (mObserver) {
Mike Yu453b5e42021-02-19 20:03:07 +0800456 mObserver->onValidationStateUpdate(sockaddr.ip().toString(), validation, netId);
Mike Yu0ee1dc92020-11-09 14:56:54 +0800457 }
458}
459
Mike Yu3d5130d2020-12-21 17:57:18 +0800460void PrivateDnsConfiguration::dump(netdutils::DumpWriter& dw) const {
461 dw.println("PrivateDnsLog:");
462 netdutils::ScopedIndent indentStats(dw);
463
464 for (const auto& record : mPrivateDnsLog.copy()) {
Mike Yu453b5e42021-02-19 20:03:07 +0800465 dw.println(fmt::format(
466 "{} - netId={} PrivateDns={{{}/{}}} state={}", timestampToString(record.timestamp),
467 record.netId, record.serverIdentity.sockaddr.toString(),
468 record.serverIdentity.provider, validationStatusToString(record.state)));
Mike Yu3d5130d2020-12-21 17:57:18 +0800469 }
470 dw.blankline();
471}
472
Mike Yub601ff72018-11-01 20:07:00 +0800473} // namespace net
474} // namespace android