blob: 9cc3ca4e5eeb3889f3e898c39af566c93314197e [file] [log] [blame]
Mike Yu939e3692019-10-29 17:28:34 +08001/*
2 * Copyright (C) 2019 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 */
17
18#include "DnsQueryLog.h"
19
Mike Yu3d5130d2020-12-21 17:57:18 +080020#include "util.h"
Mike Yu939e3692019-10-29 17:28:34 +080021
22namespace android::net {
23
24namespace {
25
26std::string maskHostname(const std::string& hostname) {
27 // Boundary issue is handled in substr().
28 return hostname.substr(0, 1) + "***";
29}
30
31// Return the string of masked addresses of the first v4 address and the first v6 address.
32std::string maskIps(const std::vector<std::string>& ips) {
33 std::string ret;
34 bool v4Found = false, v6Found = false;
35 for (const auto& ip : ips) {
36 if (auto pos = ip.find_first_of(':'); pos != ip.npos && !v6Found) {
37 ret += ip.substr(0, pos + 1) + "***, ";
38 v6Found = true;
39 } else if (auto pos = ip.find_first_of('.'); pos != ip.npos && !v4Found) {
40 ret += ip.substr(0, pos + 1) + "***, ";
41 v4Found = true;
42 }
43 if (v6Found && v4Found) break;
44 }
45 return ret.empty() ? "" : ret.substr(0, ret.length() - 2);
46}
47
Mike Yu939e3692019-10-29 17:28:34 +080048} // namespace
49
50void DnsQueryLog::push(Record&& record) {
Mike Yua86a9702020-12-21 19:30:25 +080051 mQueue.push(std::move(record));
Mike Yu939e3692019-10-29 17:28:34 +080052}
53
54void DnsQueryLog::dump(netdutils::DumpWriter& dw) const {
Mike Yu39df0b12019-10-31 16:12:23 +080055 dw.println("DNS query log (last %lld minutes):", (mValidityTimeMs / 60000).count());
Mike Yu939e3692019-10-29 17:28:34 +080056 netdutils::ScopedIndent indentStats(dw);
57 const auto now = std::chrono::system_clock::now();
58
Mike Yua86a9702020-12-21 19:30:25 +080059 for (const auto& record : mQueue.copy()) {
Mike Yu39df0b12019-10-31 16:12:23 +080060 if (now - record.timestamp > mValidityTimeMs) continue;
Mike Yu939e3692019-10-29 17:28:34 +080061
62 const std::string maskedHostname = maskHostname(record.hostname);
63 const std::string maskedIpsStr = maskIps(record.addrs);
64 const std::string time = timestampToString(record.timestamp);
65 dw.println("time=%s netId=%u uid=%u pid=%d hostname=%s answer=[%s] (%dms)", time.c_str(),
66 record.netId, record.uid, record.pid, maskedHostname.c_str(),
67 maskedIpsStr.c_str(), record.timeTaken);
68 }
69}
70
71} // namespace android::net