• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 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 #define LOG_TAG "TrafficController"
18 #include <inttypes.h>
19 #include <linux/bpf.h>
20 #include <linux/if_ether.h>
21 #include <linux/in.h>
22 #include <linux/inet_diag.h>
23 #include <linux/netlink.h>
24 #include <linux/sock_diag.h>
25 #include <linux/unistd.h>
26 #include <net/if.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/socket.h>
30 #include <sys/stat.h>
31 #include <sys/types.h>
32 #include <sys/utsname.h>
33 #include <sys/wait.h>
34 #include <mutex>
35 #include <unordered_set>
36 #include <vector>
37 
38 #include <android-base/stringprintf.h>
39 #include <android-base/strings.h>
40 #include <android-base/unique_fd.h>
41 #include <logwrap/logwrap.h>
42 #include <netdutils/StatusOr.h>
43 
44 #include <netdutils/Misc.h>
45 #include <netdutils/Syscalls.h>
46 #include <processgroup/processgroup.h>
47 #include "TrafficController.h"
48 #include "bpf/BpfMap.h"
49 
50 #include "FirewallController.h"
51 #include "InterfaceController.h"
52 #include "NetlinkListener.h"
53 #include "netdutils/DumpWriter.h"
54 #include "qtaguid/qtaguid.h"
55 
56 using namespace android::bpf;  // NOLINT(google-build-using-namespace): grandfathered
57 
58 namespace android {
59 namespace net {
60 
61 using base::StringPrintf;
62 using base::unique_fd;
63 using netdutils::DumpWriter;
64 using netdutils::extract;
65 using netdutils::ScopedIndent;
66 using netdutils::Slice;
67 using netdutils::sSyscalls;
68 using netdutils::Status;
69 using netdutils::statusFromErrno;
70 using netdutils::StatusOr;
71 using netdutils::status::ok;
72 
73 constexpr int kSockDiagMsgType = SOCK_DIAG_BY_FAMILY;
74 constexpr int kSockDiagDoneMsgType = NLMSG_DONE;
75 constexpr int PER_UID_STATS_ENTRIES_LIMIT = 500;
76 // At most 90% of the stats map may be used by tagged traffic entries. This ensures
77 // that 10% of the map is always available to count untagged traffic, one entry per UID.
78 // Otherwise, apps would be able to avoid data usage accounting entirely by filling up the
79 // map with tagged traffic entries.
80 constexpr int TOTAL_UID_STATS_ENTRIES_LIMIT = STATS_MAP_SIZE * 0.9;
81 
82 static_assert(BPF_PERMISSION_INTERNET == INetd::PERMISSION_INTERNET,
83               "Mismatch between BPF and AIDL permissions: PERMISSION_INTERNET");
84 static_assert(BPF_PERMISSION_UPDATE_DEVICE_STATS == INetd::PERMISSION_UPDATE_DEVICE_STATS,
85               "Mismatch between BPF and AIDL permissions: PERMISSION_UPDATE_DEVICE_STATS");
86 static_assert(STATS_MAP_SIZE - TOTAL_UID_STATS_ENTRIES_LIMIT > 100,
87               "The limit for stats map is to high, stats data may be lost due to overflow");
88 
89 #define FLAG_MSG_TRANS(result, flag, value)            \
90     do {                                               \
91         if (value & flag) {                            \
92             result.append(StringPrintf(" %s", #flag)); \
93             value &= ~flag;                            \
94         }                                              \
95     } while (0)
96 
uidMatchTypeToString(uint8_t match)97 const std::string uidMatchTypeToString(uint8_t match) {
98     std::string matchType;
99     FLAG_MSG_TRANS(matchType, HAPPY_BOX_MATCH, match);
100     FLAG_MSG_TRANS(matchType, PENALTY_BOX_MATCH, match);
101     FLAG_MSG_TRANS(matchType, DOZABLE_MATCH, match);
102     FLAG_MSG_TRANS(matchType, STANDBY_MATCH, match);
103     FLAG_MSG_TRANS(matchType, POWERSAVE_MATCH, match);
104     FLAG_MSG_TRANS(matchType, IIF_MATCH, match);
105     if (match) {
106         return StringPrintf("Unknown match: %u", match);
107     }
108     return matchType;
109 }
110 
hasUpdateDeviceStatsPermission(uid_t uid)111 bool TrafficController::hasUpdateDeviceStatsPermission(uid_t uid) {
112     // This implementation is the same logic as method ActivityManager#checkComponentPermission.
113     // It implies that the calling uid can never be the same as PER_USER_RANGE.
114     uint32_t appId = uid % PER_USER_RANGE;
115     return ((appId == AID_ROOT) || (appId == AID_SYSTEM) ||
116             mPrivilegedUser.find(appId) != mPrivilegedUser.end());
117 }
118 
UidPermissionTypeToString(uint8_t permission)119 const std::string UidPermissionTypeToString(uint8_t permission) {
120     if (permission == INetd::PERMISSION_NONE) {
121         return "PERMISSION_NONE";
122     }
123     if (permission == INetd::PERMISSION_UNINSTALLED) {
124         // This should never appear in the map, complain loudly if it does.
125         return "PERMISSION_UNINSTALLED error!";
126     }
127     std::string permissionType;
128     FLAG_MSG_TRANS(permissionType, BPF_PERMISSION_INTERNET, permission);
129     FLAG_MSG_TRANS(permissionType, BPF_PERMISSION_UPDATE_DEVICE_STATS, permission);
130     if (permission) {
131         return StringPrintf("Unknown permission: %u", permission);
132     }
133     return permissionType;
134 }
135 
makeSkDestroyListener()136 StatusOr<std::unique_ptr<NetlinkListenerInterface>> TrafficController::makeSkDestroyListener() {
137     const auto& sys = sSyscalls.get();
138     ASSIGN_OR_RETURN(auto event, sys.eventfd(0, EFD_CLOEXEC));
139     const int domain = AF_NETLINK;
140     const int type = SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK;
141     const int protocol = NETLINK_INET_DIAG;
142     ASSIGN_OR_RETURN(auto sock, sys.socket(domain, type, protocol));
143 
144     // TODO: if too many sockets are closed too quickly, we can overflow the socket buffer, and
145     // some entries in mCookieTagMap will not be freed. In order to fix this we would need to
146     // periodically dump all sockets and remove the tag entries for sockets that have been closed.
147     // For now, set a large-enough buffer that we can close hundreds of sockets without getting
148     // ENOBUFS and leaking mCookieTagMap entries.
149     int rcvbuf = 512 * 1024;
150     auto ret = sys.setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf));
151     if (!ret.ok()) {
152         ALOGW("Failed to set SkDestroyListener buffer size to %d: %s", rcvbuf, ret.msg().c_str());
153     }
154 
155     sockaddr_nl addr = {
156         .nl_family = AF_NETLINK,
157         .nl_groups = 1 << (SKNLGRP_INET_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET_UDP_DESTROY - 1) |
158                      1 << (SKNLGRP_INET6_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET6_UDP_DESTROY - 1)};
159     RETURN_IF_NOT_OK(sys.bind(sock, addr));
160 
161     const sockaddr_nl kernel = {.nl_family = AF_NETLINK};
162     RETURN_IF_NOT_OK(sys.connect(sock, kernel));
163 
164     std::unique_ptr<NetlinkListenerInterface> listener =
165             std::make_unique<NetlinkListener>(std::move(event), std::move(sock), "SkDestroyListen");
166 
167     return listener;
168 }
169 
changeOwnerAndMode(const char * path,gid_t group,const char * debugName,bool netdOnly)170 Status changeOwnerAndMode(const char* path, gid_t group, const char* debugName, bool netdOnly) {
171     int ret = chown(path, AID_ROOT, group);
172     if (ret != 0) return statusFromErrno(errno, StringPrintf("change %s group failed", debugName));
173 
174     if (netdOnly) {
175         ret = chmod(path, S_IRWXU);
176     } else {
177         // Allow both netd and system server to obtain map fd from the path.
178         // chmod doesn't grant permission to all processes in that group to
179         // read/write the bpf map. They still need correct sepolicy to
180         // read/write the map.
181         ret = chmod(path, S_IRWXU | S_IRGRP | S_IWGRP);
182     }
183     if (ret != 0) return statusFromErrno(errno, StringPrintf("change %s mode failed", debugName));
184     return netdutils::status::ok;
185 }
186 
TrafficController()187 TrafficController::TrafficController()
188     : mBpfLevel(getBpfSupportLevel()),
189       mPerUidStatsEntriesLimit(PER_UID_STATS_ENTRIES_LIMIT),
190       mTotalUidStatsEntriesLimit(TOTAL_UID_STATS_ENTRIES_LIMIT) {}
191 
TrafficController(uint32_t perUidLimit,uint32_t totalLimit)192 TrafficController::TrafficController(uint32_t perUidLimit, uint32_t totalLimit)
193     : mBpfLevel(getBpfSupportLevel()),
194       mPerUidStatsEntriesLimit(perUidLimit),
195       mTotalUidStatsEntriesLimit(totalLimit) {}
196 
initMaps()197 Status TrafficController::initMaps() {
198     std::lock_guard guard(mMutex);
199     RETURN_IF_NOT_OK(mCookieTagMap.init(COOKIE_TAG_MAP_PATH));
200     RETURN_IF_NOT_OK(changeOwnerAndMode(COOKIE_TAG_MAP_PATH, AID_NET_BW_ACCT, "CookieTagMap",
201                                         false));
202 
203     RETURN_IF_NOT_OK(mUidCounterSetMap.init(UID_COUNTERSET_MAP_PATH));
204     RETURN_IF_NOT_OK(changeOwnerAndMode(UID_COUNTERSET_MAP_PATH, AID_NET_BW_ACCT,
205                                         "UidCounterSetMap", false));
206 
207     RETURN_IF_NOT_OK(mAppUidStatsMap.init(APP_UID_STATS_MAP_PATH));
208     RETURN_IF_NOT_OK(
209         changeOwnerAndMode(APP_UID_STATS_MAP_PATH, AID_NET_BW_STATS, "AppUidStatsMap", false));
210 
211     RETURN_IF_NOT_OK(mStatsMapA.init(STATS_MAP_A_PATH));
212     RETURN_IF_NOT_OK(changeOwnerAndMode(STATS_MAP_A_PATH, AID_NET_BW_STATS, "StatsMapA", false));
213 
214     RETURN_IF_NOT_OK(mStatsMapB.init(STATS_MAP_B_PATH));
215     RETURN_IF_NOT_OK(changeOwnerAndMode(STATS_MAP_B_PATH, AID_NET_BW_STATS, "StatsMapB", false));
216 
217     RETURN_IF_NOT_OK(mIfaceIndexNameMap.init(IFACE_INDEX_NAME_MAP_PATH));
218     RETURN_IF_NOT_OK(changeOwnerAndMode(IFACE_INDEX_NAME_MAP_PATH, AID_NET_BW_STATS,
219                                         "IfaceIndexNameMap", false));
220 
221     RETURN_IF_NOT_OK(mIfaceStatsMap.init(IFACE_STATS_MAP_PATH));
222     RETURN_IF_NOT_OK(changeOwnerAndMode(IFACE_STATS_MAP_PATH, AID_NET_BW_STATS, "IfaceStatsMap",
223                                         false));
224 
225     RETURN_IF_NOT_OK(mConfigurationMap.init(CONFIGURATION_MAP_PATH));
226     RETURN_IF_NOT_OK(changeOwnerAndMode(CONFIGURATION_MAP_PATH, AID_NET_BW_STATS,
227                                         "ConfigurationMap", false));
228     RETURN_IF_NOT_OK(
229             mConfigurationMap.writeValue(UID_RULES_CONFIGURATION_KEY, DEFAULT_CONFIG, BPF_ANY));
230     RETURN_IF_NOT_OK(mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, SELECT_MAP_A,
231                                                   BPF_ANY));
232 
233     RETURN_IF_NOT_OK(mUidOwnerMap.init(UID_OWNER_MAP_PATH));
234     RETURN_IF_NOT_OK(changeOwnerAndMode(UID_OWNER_MAP_PATH, AID_ROOT, "UidOwnerMap", true));
235     RETURN_IF_NOT_OK(mUidOwnerMap.clear());
236     RETURN_IF_NOT_OK(mUidPermissionMap.init(UID_PERMISSION_MAP_PATH));
237     return netdutils::status::ok;
238 }
239 
attachProgramToCgroup(const char * programPath,const int cgroupFd,bpf_attach_type type)240 static Status attachProgramToCgroup(const char* programPath, const int cgroupFd,
241                                     bpf_attach_type type) {
242     unique_fd cgroupProg(bpfFdGet(programPath, 0));
243     if (cgroupProg == -1) {
244         int ret = errno;
245         ALOGE("Failed to get program from %s: %s", programPath, strerror(ret));
246         return statusFromErrno(ret, "cgroup program get failed");
247     }
248     if (android::bpf::attachProgram(type, cgroupProg, cgroupFd)) {
249         int ret = errno;
250         ALOGE("Program from %s attach failed: %s", programPath, strerror(ret));
251         return statusFromErrno(ret, "program attach failed");
252     }
253     return netdutils::status::ok;
254 }
255 
initPrograms()256 static Status initPrograms() {
257     std::string cg2_path;
258 
259     if (!CgroupGetControllerPath(CGROUPV2_CONTROLLER_NAME, &cg2_path)) {
260          int ret = errno;
261          ALOGE("Failed to find cgroup v2 root");
262          return statusFromErrno(ret, "Failed to find cgroup v2 root");
263     }
264 
265     unique_fd cg_fd(open(cg2_path.c_str(), O_DIRECTORY | O_RDONLY | O_CLOEXEC));
266     if (cg_fd == -1) {
267         int ret = errno;
268         ALOGE("Failed to open the cgroup directory: %s", strerror(ret));
269         return statusFromErrno(ret, "Open the cgroup directory failed");
270     }
271     RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_EGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_EGRESS));
272     RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_INGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_INGRESS));
273 
274     // For the devices that support cgroup socket filter, the socket filter
275     // should be loaded successfully by bpfloader. So we attach the filter to
276     // cgroup if the program is pinned properly.
277     // TODO: delete the if statement once all devices should support cgroup
278     // socket filter (ie. the minimum kernel version required is 4.14).
279     if (!access(CGROUP_SOCKET_PROG_PATH, F_OK)) {
280         RETURN_IF_NOT_OK(
281                 attachProgramToCgroup(CGROUP_SOCKET_PROG_PATH, cg_fd, BPF_CGROUP_INET_SOCK_CREATE));
282     }
283     return netdutils::status::ok;
284 }
285 
start()286 Status TrafficController::start() {
287     if (mBpfLevel == BpfLevel::NONE) {
288         return netdutils::status::ok;
289     }
290 
291     /* When netd restarts from a crash without total system reboot, the program
292      * is still attached to the cgroup, detach it so the program can be freed
293      * and we can load and attach new program into the target cgroup.
294      *
295      * TODO: Scrape existing socket when run-time restart and clean up the map
296      * if the socket no longer exist
297      */
298 
299     RETURN_IF_NOT_OK(initMaps());
300 
301     RETURN_IF_NOT_OK(initPrograms());
302 
303     // Fetch the list of currently-existing interfaces. At this point NetlinkHandler is
304     // already running, so it will call addInterface() when any new interface appears.
305     std::map<std::string, uint32_t> ifacePairs;
306     ASSIGN_OR_RETURN(ifacePairs, InterfaceController::getIfaceList());
307     for (const auto& ifacePair:ifacePairs) {
308         addInterface(ifacePair.first.c_str(), ifacePair.second);
309     }
310 
311     auto result = makeSkDestroyListener();
312     if (!isOk(result)) {
313         ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
314     } else {
315         mSkDestroyListener = std::move(result.value());
316     }
317     // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
318     const auto rxHandler = [this](const nlmsghdr&, const Slice msg) {
319         std::lock_guard guard(mMutex);
320         inet_diag_msg diagmsg = {};
321         if (extract(msg, diagmsg) < sizeof(inet_diag_msg)) {
322             ALOGE("Unrecognized netlink message: %s", toString(msg).c_str());
323             return;
324         }
325         uint64_t sock_cookie = static_cast<uint64_t>(diagmsg.id.idiag_cookie[0]) |
326                                (static_cast<uint64_t>(diagmsg.id.idiag_cookie[1]) << 32);
327 
328         Status s = mCookieTagMap.deleteValue(sock_cookie);
329         if (!isOk(s) && s.code() != ENOENT) {
330             ALOGE("Failed to delete cookie %" PRIx64 ": %s", sock_cookie, toString(s).c_str());
331             return;
332         }
333     };
334     expectOk(mSkDestroyListener->subscribe(kSockDiagMsgType, rxHandler));
335 
336     // In case multiple netlink message comes in as a stream, we need to handle the rxDone message
337     // properly.
338     const auto rxDoneHandler = [](const nlmsghdr&, const Slice msg) {
339         // Ignore NLMSG_DONE  messages
340         inet_diag_msg diagmsg = {};
341         extract(msg, diagmsg);
342     };
343     expectOk(mSkDestroyListener->subscribe(kSockDiagDoneMsgType, rxDoneHandler));
344 
345     return netdutils::status::ok;
346 }
347 
tagSocket(int sockFd,uint32_t tag,uid_t uid,uid_t callingUid)348 int TrafficController::tagSocket(int sockFd, uint32_t tag, uid_t uid, uid_t callingUid) {
349     std::lock_guard guard(mMutex);
350     if (uid != callingUid && !hasUpdateDeviceStatsPermission(callingUid)) {
351         return -EPERM;
352     }
353 
354     if (mBpfLevel == BpfLevel::NONE) {
355         if (legacy_tagSocket(sockFd, tag, uid)) return -errno;
356         return 0;
357     }
358 
359     uint64_t sock_cookie = getSocketCookie(sockFd);
360     if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
361     UidTag newKey = {.uid = (uint32_t)uid, .tag = tag};
362 
363     uint32_t totalEntryCount = 0;
364     uint32_t perUidEntryCount = 0;
365     // Now we go through the stats map and count how many entries are associated
366     // with target uid. If the uid entry hit the limit for each uid, we block
367     // the request to prevent the map from overflow. It is safe here to iterate
368     // over the map since when mMutex is hold, system server cannot toggle
369     // the live stats map and clean it. So nobody can delete entries from the map.
370     const auto countUidStatsEntries = [uid, &totalEntryCount, &perUidEntryCount](
371                                               const StatsKey& key, BpfMap<StatsKey, StatsValue>&) {
372         if (key.uid == uid) {
373             perUidEntryCount++;
374         }
375         totalEntryCount++;
376         return netdutils::status::ok;
377     };
378     auto configuration = mConfigurationMap.readValue(CURRENT_STATS_MAP_CONFIGURATION_KEY);
379     if (!isOk(configuration.status())) {
380         ALOGE("Failed to get current configuration: %s, fd: %d",
381               strerror(configuration.status().code()), mConfigurationMap.getMap().get());
382         return -configuration.status().code();
383     }
384     if (configuration.value() != SELECT_MAP_A && configuration.value() != SELECT_MAP_B) {
385         ALOGE("unknown configuration value: %d", configuration.value());
386         return -EINVAL;
387     }
388 
389     BpfMap<StatsKey, StatsValue>& currentMap =
390             (configuration.value() == SELECT_MAP_A) ? mStatsMapA : mStatsMapB;
391     Status res = currentMap.iterate(countUidStatsEntries);
392     if (!isOk(res)) {
393         ALOGE("Failed to count the stats entry in map %d: %s", currentMap.getMap().get(),
394               strerror(res.code()));
395         return -res.code();
396     }
397 
398     if (totalEntryCount > mTotalUidStatsEntriesLimit ||
399         perUidEntryCount > mPerUidStatsEntriesLimit) {
400         ALOGE("Too many stats entries in the map, total count: %u, uid(%u) count: %u, blocking tag"
401               " request to prevent map overflow",
402               totalEntryCount, uid, perUidEntryCount);
403         return -EMFILE;
404     }
405     // Update the tag information of a socket to the cookieUidMap. Use BPF_ANY
406     // flag so it will insert a new entry to the map if that value doesn't exist
407     // yet. And update the tag if there is already a tag stored. Since the eBPF
408     // program in kernel only read this map, and is protected by rcu read lock. It
409     // should be fine to cocurrently update the map while eBPF program is running.
410     res = mCookieTagMap.writeValue(sock_cookie, newKey, BPF_ANY);
411     if (!isOk(res)) {
412         ALOGE("Failed to tag the socket: %s, fd: %d", strerror(res.code()),
413               mCookieTagMap.getMap().get());
414     }
415     return -res.code();
416 }
417 
untagSocket(int sockFd)418 int TrafficController::untagSocket(int sockFd) {
419     std::lock_guard guard(mMutex);
420     if (mBpfLevel == BpfLevel::NONE) {
421         if (legacy_untagSocket(sockFd)) return -errno;
422         return 0;
423     }
424     uint64_t sock_cookie = getSocketCookie(sockFd);
425 
426     if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
427     Status res = mCookieTagMap.deleteValue(sock_cookie);
428     if (!isOk(res)) {
429         ALOGE("Failed to untag socket: %s\n", strerror(res.code()));
430     }
431     return -res.code();
432 }
433 
setCounterSet(int counterSetNum,uid_t uid,uid_t callingUid)434 int TrafficController::setCounterSet(int counterSetNum, uid_t uid, uid_t callingUid) {
435     if (counterSetNum < 0 || counterSetNum >= OVERFLOW_COUNTERSET) return -EINVAL;
436 
437     std::lock_guard guard(mMutex);
438     if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
439 
440     if (mBpfLevel == BpfLevel::NONE) {
441         if (legacy_setCounterSet(counterSetNum, uid)) return -errno;
442         return 0;
443     }
444 
445     // The default counter set for all uid is 0, so deleting the current counterset for that uid
446     // will automatically set it to 0.
447     if (counterSetNum == 0) {
448         Status res = mUidCounterSetMap.deleteValue(uid);
449         if (isOk(res) || (!isOk(res) && res.code() == ENOENT)) {
450             return 0;
451         } else {
452             ALOGE("Failed to delete the counterSet: %s\n", strerror(res.code()));
453             return -res.code();
454         }
455     }
456     uint8_t tmpCounterSetNum = (uint8_t)counterSetNum;
457     Status res = mUidCounterSetMap.writeValue(uid, tmpCounterSetNum, BPF_ANY);
458     if (!isOk(res)) {
459         ALOGE("Failed to set the counterSet: %s, fd: %d", strerror(res.code()),
460               mUidCounterSetMap.getMap().get());
461         return -res.code();
462     }
463     return 0;
464 }
465 
466 // This method only get called by system_server when an app get uinstalled, it
467 // is called inside removeUidsLocked() while holding mStatsLock. So it is safe
468 // to iterate and modify the stats maps.
deleteTagData(uint32_t tag,uid_t uid,uid_t callingUid)469 int TrafficController::deleteTagData(uint32_t tag, uid_t uid, uid_t callingUid) {
470     std::lock_guard guard(mMutex);
471     if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
472 
473     if (mBpfLevel == BpfLevel::NONE) {
474         if (legacy_deleteTagData(tag, uid)) return -errno;
475         return 0;
476     }
477 
478     // First we go through the cookieTagMap to delete the target uid tag combination. Or delete all
479     // the tags related to the uid if the tag is 0.
480     const auto deleteMatchedCookieEntries = [uid, tag](const uint64_t& key, const UidTag& value,
481                                                        BpfMap<uint64_t, UidTag>& map) {
482         if (value.uid == uid && (value.tag == tag || tag == 0)) {
483             Status res = map.deleteValue(key);
484             if (isOk(res) || (res.code() == ENOENT)) {
485                 return netdutils::status::ok;
486             }
487             ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s\n", key, strerror(res.code()));
488         }
489         // Move forward to next cookie in the map.
490         return netdutils::status::ok;
491     };
492     mCookieTagMap.iterateWithValue(deleteMatchedCookieEntries).ignoreError();
493     // Now we go through the Tag stats map and delete the data entry with correct uid and tag
494     // combination. Or all tag stats under that uid if the target tag is 0.
495     const auto deleteMatchedUidTagEntries = [uid, tag](const StatsKey& key,
496                                                        BpfMap<StatsKey, StatsValue>& map) {
497         if (key.uid == uid && (key.tag == tag || tag == 0)) {
498             Status res = map.deleteValue(key);
499             if (isOk(res) || (res.code() == ENOENT)) {
500                 //Entry is deleted, use the current key to get a new nextKey;
501                 return netdutils::status::ok;
502             }
503             ALOGE("Failed to delete data(uid=%u, tag=%u): %s\n", key.uid, key.tag,
504                   strerror(res.code()));
505         }
506         return netdutils::status::ok;
507     };
508     mStatsMapB.iterate(deleteMatchedUidTagEntries).ignoreError();
509     mStatsMapA.iterate(deleteMatchedUidTagEntries).ignoreError();
510     // If the tag is not zero, we already deleted all the data entry required. If tag is 0, we also
511     // need to delete the stats stored in uidStatsMap and counterSet map.
512     if (tag != 0) return 0;
513 
514     Status res = mUidCounterSetMap.deleteValue(uid);
515     if (!isOk(res) && res.code() != ENOENT) {
516         ALOGE("Failed to delete counterSet data(uid=%u, tag=%u): %s\n", uid, tag,
517               strerror(res.code()));
518     }
519 
520     auto deleteAppUidStatsEntry = [uid](const uint32_t& key, BpfMap<uint32_t, StatsValue>& map) {
521         if (key == uid) {
522             Status res = map.deleteValue(key);
523             if (isOk(res) || (res.code() == ENOENT)) {
524                 return netdutils::status::ok;
525             }
526             ALOGE("Failed to delete data(uid=%u): %s", key, strerror(res.code()));
527         }
528         return netdutils::status::ok;
529     };
530     mAppUidStatsMap.iterate(deleteAppUidStatsEntry).ignoreError();
531     return 0;
532 }
533 
addInterface(const char * name,uint32_t ifaceIndex)534 int TrafficController::addInterface(const char* name, uint32_t ifaceIndex) {
535     if (mBpfLevel == BpfLevel::NONE) return 0;
536 
537     IfaceValue iface;
538     if (ifaceIndex == 0) {
539         ALOGE("Unknown interface %s(%d)", name, ifaceIndex);
540         return -1;
541     }
542 
543     strlcpy(iface.name, name, sizeof(IfaceValue));
544     Status res = mIfaceIndexNameMap.writeValue(ifaceIndex, iface, BPF_ANY);
545     if (!isOk(res)) {
546         ALOGE("Failed to add iface %s(%d): %s", name, ifaceIndex, strerror(res.code()));
547         return -res.code();
548     }
549     return 0;
550 }
551 
updateOwnerMapEntry(UidOwnerMatchType match,uid_t uid,FirewallRule rule,FirewallType type)552 Status TrafficController::updateOwnerMapEntry(UidOwnerMatchType match, uid_t uid, FirewallRule rule,
553                                               FirewallType type) {
554     std::lock_guard guard(mMutex);
555     if ((rule == ALLOW && type == WHITELIST) || (rule == DENY && type == BLACKLIST)) {
556         RETURN_IF_NOT_OK(addRule(mUidOwnerMap, uid, match));
557     } else if ((rule == ALLOW && type == BLACKLIST) || (rule == DENY && type == WHITELIST)) {
558         RETURN_IF_NOT_OK(removeRule(mUidOwnerMap, uid, match));
559     } else {
560         //Cannot happen.
561         return statusFromErrno(EINVAL, "");
562     }
563     return netdutils::status::ok;
564 }
565 
jumpOpToMatch(BandwidthController::IptJumpOp jumpHandling)566 UidOwnerMatchType TrafficController::jumpOpToMatch(BandwidthController::IptJumpOp jumpHandling) {
567     switch (jumpHandling) {
568         case BandwidthController::IptJumpReject:
569             return PENALTY_BOX_MATCH;
570         case BandwidthController::IptJumpReturn:
571             return HAPPY_BOX_MATCH;
572         case BandwidthController::IptJumpNoAdd:
573             return NO_MATCH;
574     }
575 }
576 
removeRule(BpfMap<uint32_t,UidOwnerValue> & map,uint32_t uid,UidOwnerMatchType match)577 Status TrafficController::removeRule(BpfMap<uint32_t, UidOwnerValue>& map, uint32_t uid,
578                                      UidOwnerMatchType match) {
579     auto oldMatch = map.readValue(uid);
580     if (isOk(oldMatch)) {
581         UidOwnerValue newMatch = {.rule = static_cast<uint8_t>(oldMatch.value().rule & ~match),
582                                   .iif = (match == IIF_MATCH) ? 0 : oldMatch.value().iif};
583         if (newMatch.rule == 0) {
584             RETURN_IF_NOT_OK(map.deleteValue(uid));
585         } else {
586             RETURN_IF_NOT_OK(map.writeValue(uid, newMatch, BPF_ANY));
587         }
588     } else {
589         return statusFromErrno(ENOENT, StringPrintf("uid: %u does not exist in map", uid));
590     }
591     return netdutils::status::ok;
592 }
593 
addRule(BpfMap<uint32_t,UidOwnerValue> & map,uint32_t uid,UidOwnerMatchType match,uint32_t iif)594 Status TrafficController::addRule(BpfMap<uint32_t, UidOwnerValue>& map, uint32_t uid,
595                                   UidOwnerMatchType match, uint32_t iif) {
596     // iif should be non-zero if and only if match == MATCH_IIF
597     if (match == IIF_MATCH && iif == 0) {
598         return statusFromErrno(EINVAL, "Interface match must have nonzero interface index");
599     } else if (match != IIF_MATCH && iif != 0) {
600         return statusFromErrno(EINVAL, "Non-interface match must have zero interface index");
601     }
602     auto oldMatch = map.readValue(uid);
603     if (isOk(oldMatch)) {
604         UidOwnerValue newMatch = {.rule = static_cast<uint8_t>(oldMatch.value().rule | match),
605                                   .iif = iif ? iif : oldMatch.value().iif};
606         RETURN_IF_NOT_OK(map.writeValue(uid, newMatch, BPF_ANY));
607     } else {
608         UidOwnerValue newMatch = {.rule = static_cast<uint8_t>(match), .iif = iif};
609         RETURN_IF_NOT_OK(map.writeValue(uid, newMatch, BPF_ANY));
610     }
611     return netdutils::status::ok;
612 }
613 
updateUidOwnerMap(const std::vector<std::string> & appStrUids,BandwidthController::IptJumpOp jumpHandling,BandwidthController::IptOp op)614 Status TrafficController::updateUidOwnerMap(const std::vector<std::string>& appStrUids,
615                                             BandwidthController::IptJumpOp jumpHandling,
616                                             BandwidthController::IptOp op) {
617     std::lock_guard guard(mMutex);
618     UidOwnerMatchType match = jumpOpToMatch(jumpHandling);
619     if (match == NO_MATCH) {
620         return statusFromErrno(
621                 EINVAL, StringPrintf("invalid IptJumpOp: %d, command: %d", jumpHandling, match));
622     }
623     for (const auto& appStrUid : appStrUids) {
624         char* endPtr;
625         long uid = strtol(appStrUid.c_str(), &endPtr, 10);
626         if ((errno == ERANGE && (uid == LONG_MAX || uid == LONG_MIN)) ||
627             (endPtr == appStrUid.c_str()) || (*endPtr != '\0')) {
628                return statusFromErrno(errno, "invalid uid string:" + appStrUid);
629         }
630 
631         if (op == BandwidthController::IptOpDelete) {
632             RETURN_IF_NOT_OK(removeRule(mUidOwnerMap, uid, match));
633         } else if (op == BandwidthController::IptOpInsert) {
634             RETURN_IF_NOT_OK(addRule(mUidOwnerMap, uid, match));
635         } else {
636             // Cannot happen.
637             return statusFromErrno(EINVAL, StringPrintf("invalid IptOp: %d, %d", op, match));
638         }
639     }
640     return netdutils::status::ok;
641 }
642 
changeUidOwnerRule(ChildChain chain,uid_t uid,FirewallRule rule,FirewallType type)643 int TrafficController::changeUidOwnerRule(ChildChain chain, uid_t uid, FirewallRule rule,
644                                           FirewallType type) {
645     if (mBpfLevel == BpfLevel::NONE) {
646         ALOGE("bpf is not set up, should use iptables rule");
647         return -ENOSYS;
648     }
649     Status res;
650     switch (chain) {
651         case DOZABLE:
652             res = updateOwnerMapEntry(DOZABLE_MATCH, uid, rule, type);
653             break;
654         case STANDBY:
655             res = updateOwnerMapEntry(STANDBY_MATCH, uid, rule, type);
656             break;
657         case POWERSAVE:
658             res = updateOwnerMapEntry(POWERSAVE_MATCH, uid, rule, type);
659             break;
660         case NONE:
661         default:
662             return -EINVAL;
663     }
664     if (!isOk(res)) {
665         ALOGE("change uid(%u) rule of %d failed: %s, rule: %d, type: %d", uid, chain,
666               res.msg().c_str(), rule, type);
667         return -res.code();
668     }
669     return 0;
670 }
671 
replaceRulesInMap(const UidOwnerMatchType match,const std::vector<int32_t> & uids)672 Status TrafficController::replaceRulesInMap(const UidOwnerMatchType match,
673                                             const std::vector<int32_t>& uids) {
674     std::lock_guard guard(mMutex);
675     std::set<int32_t> uidSet(uids.begin(), uids.end());
676     std::vector<uint32_t> uidsToDelete;
677     auto getUidsToDelete = [&uidsToDelete, &uidSet](const uint32_t& key,
678                                                     const BpfMap<uint32_t, UidOwnerValue>&) {
679         if (uidSet.find((int32_t) key) == uidSet.end()) {
680             uidsToDelete.push_back(key);
681         }
682         return netdutils::status::ok;
683     };
684     RETURN_IF_NOT_OK(mUidOwnerMap.iterate(getUidsToDelete));
685 
686     for(auto uid : uidsToDelete) {
687         RETURN_IF_NOT_OK(removeRule(mUidOwnerMap, uid, match));
688     }
689 
690     for (auto uid : uids) {
691         RETURN_IF_NOT_OK(addRule(mUidOwnerMap, uid, match));
692     }
693     return netdutils::status::ok;
694 }
695 
addUidInterfaceRules(const int iif,const std::vector<int32_t> & uidsToAdd)696 Status TrafficController::addUidInterfaceRules(const int iif,
697                                                const std::vector<int32_t>& uidsToAdd) {
698     if (mBpfLevel == BpfLevel::NONE) {
699         ALOGW("UID ingress interface filtering not possible without BPF owner match");
700         return statusFromErrno(EOPNOTSUPP, "eBPF not supported");
701     }
702     if (!iif) {
703         return statusFromErrno(EINVAL, "Interface rule must specify interface");
704     }
705     std::lock_guard guard(mMutex);
706 
707     for (auto uid : uidsToAdd) {
708         netdutils::Status result = addRule(mUidOwnerMap, uid, IIF_MATCH, iif);
709         if (!isOk(result)) {
710             ALOGW("addRule failed(%d): uid=%d iif=%d", result.code(), uid, iif);
711         }
712     }
713     return netdutils::status::ok;
714 }
715 
removeUidInterfaceRules(const std::vector<int32_t> & uidsToDelete)716 Status TrafficController::removeUidInterfaceRules(const std::vector<int32_t>& uidsToDelete) {
717     if (mBpfLevel == BpfLevel::NONE) {
718         ALOGW("UID ingress interface filtering not possible without BPF owner match");
719         return statusFromErrno(EOPNOTSUPP, "eBPF not supported");
720     }
721     std::lock_guard guard(mMutex);
722 
723     for (auto uid : uidsToDelete) {
724         netdutils::Status result = removeRule(mUidOwnerMap, uid, IIF_MATCH);
725         if (!isOk(result)) {
726             ALOGW("removeRule failed(%d): uid=%d", result.code(), uid);
727         }
728     }
729     return netdutils::status::ok;
730 }
731 
replaceUidOwnerMap(const std::string & name,bool isWhitelist,const std::vector<int32_t> & uids)732 int TrafficController::replaceUidOwnerMap(const std::string& name, bool isWhitelist,
733                                           const std::vector<int32_t>& uids) {
734     FirewallRule rule;
735     FirewallType type;
736     if (isWhitelist) {
737         type = WHITELIST;
738         rule = ALLOW;
739     } else {
740         type = BLACKLIST;
741         rule = DENY;
742     }
743     Status res;
744     if (!name.compare(FirewallController::LOCAL_DOZABLE)) {
745         res = replaceRulesInMap(DOZABLE_MATCH, uids);
746     } else if (!name.compare(FirewallController::LOCAL_STANDBY)) {
747         res = replaceRulesInMap(STANDBY_MATCH, uids);
748     } else if (!name.compare(FirewallController::LOCAL_POWERSAVE)) {
749         res = replaceRulesInMap(POWERSAVE_MATCH, uids);
750     } else {
751         ALOGE("unknown chain name: %s", name.c_str());
752         return -EINVAL;
753     }
754     if (!isOk(res)) {
755         ALOGE("Failed to clean up chain: %s: %s", name.c_str(), res.msg().c_str());
756         return -res.code();
757     }
758     return 0;
759 }
760 
toggleUidOwnerMap(ChildChain chain,bool enable)761 int TrafficController::toggleUidOwnerMap(ChildChain chain, bool enable) {
762     std::lock_guard guard(mMutex);
763     uint32_t key = UID_RULES_CONFIGURATION_KEY;
764     auto oldConfiguration = mConfigurationMap.readValue(key);
765     if (!isOk(oldConfiguration)) {
766         ALOGE("Cannot read the old configuration from map: %s",
767               oldConfiguration.status().msg().c_str());
768         return -oldConfiguration.status().code();
769     }
770     Status res;
771     BpfConfig newConfiguration;
772     uint8_t match;
773     switch (chain) {
774         case DOZABLE:
775             match = DOZABLE_MATCH;
776             break;
777         case STANDBY:
778             match = STANDBY_MATCH;
779             break;
780         case POWERSAVE:
781             match = POWERSAVE_MATCH;
782             break;
783         default:
784             return -EINVAL;
785     }
786     newConfiguration =
787             enable ? (oldConfiguration.value() | match) : (oldConfiguration.value() & (~match));
788     res = mConfigurationMap.writeValue(key, newConfiguration, BPF_EXIST);
789     if (!isOk(res)) {
790         ALOGE("Failed to toggleUidOwnerMap(%d): %s", chain, res.msg().c_str());
791     }
792     return -res.code();
793 }
794 
getBpfLevel()795 BpfLevel TrafficController::getBpfLevel() {
796     return mBpfLevel;
797 }
798 
swapActiveStatsMap()799 Status TrafficController::swapActiveStatsMap() {
800     std::lock_guard guard(mMutex);
801 
802     if (mBpfLevel == BpfLevel::NONE) {
803         return statusFromErrno(EOPNOTSUPP, "This device doesn't have eBPF support");
804     }
805 
806     uint32_t key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
807     auto oldConfiguration = mConfigurationMap.readValue(key);
808     if (!isOk(oldConfiguration)) {
809         ALOGE("Cannot read the old configuration from map: %s",
810               oldConfiguration.status().msg().c_str());
811         return oldConfiguration.status();
812     }
813 
814     // Write to the configuration map to inform the kernel eBPF program to switch
815     // from using one map to the other. Use flag BPF_EXIST here since the map should
816     // be already populated in initMaps.
817     uint8_t newConfigure = (oldConfiguration.value() == SELECT_MAP_A) ? SELECT_MAP_B : SELECT_MAP_A;
818     Status res = mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, newConfigure,
819                                               BPF_EXIST);
820     if (!isOk(res)) {
821         ALOGE("Failed to toggle the stats map: %s", strerror(res.code()));
822         return res;
823     }
824     // After changing the config, we need to make sure all the current running
825     // eBPF programs are finished and all the CPUs are aware of this config change
826     // before we modify the old map. So we do a special hack here to wait for
827     // the kernel to do a synchronize_rcu(). Once the kernel called
828     // synchronize_rcu(), the config we just updated will be available to all cores
829     // and the next eBPF programs triggered inside the kernel will use the new
830     // map configuration. So once this function returns we can safely modify the
831     // old stats map without concerning about race between the kernel and
832     // userspace.
833     int ret = synchronizeKernelRCU();
834     if (ret) {
835         ALOGE("map swap synchronize_rcu() ended with failure: %s", strerror(-ret));
836         return statusFromErrno(-ret, "map swap synchronize_rcu() failed");
837     }
838     return netdutils::status::ok;
839 }
840 
setPermissionForUids(int permission,const std::vector<uid_t> & uids)841 void TrafficController::setPermissionForUids(int permission, const std::vector<uid_t>& uids) {
842     std::lock_guard guard(mMutex);
843     if (permission == INetd::PERMISSION_UNINSTALLED) {
844         for (uid_t uid : uids) {
845             // Clean up all permission information for the related uid if all the
846             // packages related to it are uninstalled.
847             mPrivilegedUser.erase(uid);
848             if (mBpfLevel > BpfLevel::NONE) {
849                 Status ret = mUidPermissionMap.deleteValue(uid);
850                 if (!isOk(ret) && ret.code() != ENONET) {
851                     ALOGE("Failed to clean up the permission for %u: %s", uid,
852                           strerror(ret.code()));
853                 }
854             }
855         }
856         return;
857     }
858 
859     bool privileged = (permission & INetd::PERMISSION_UPDATE_DEVICE_STATS);
860 
861     for (uid_t uid : uids) {
862         if (privileged) {
863             mPrivilegedUser.insert(uid);
864         } else {
865             mPrivilegedUser.erase(uid);
866         }
867 
868         // Skip the bpf map operation if not supported.
869         if (mBpfLevel == BpfLevel::NONE) {
870             continue;
871         }
872         // The map stores all the permissions that the UID has, except if the only permission
873         // the UID has is the INTERNET permission, then the UID should not appear in the map.
874         if (permission != INetd::PERMISSION_INTERNET) {
875             Status ret = mUidPermissionMap.writeValue(uid, permission, BPF_ANY);
876             if (!isOk(ret)) {
877                 ALOGE("Failed to set permission: %s of uid(%u) to permission map: %s",
878                       UidPermissionTypeToString(permission).c_str(), uid, strerror(ret.code()));
879             }
880         } else {
881             Status ret = mUidPermissionMap.deleteValue(uid);
882             if (!isOk(ret) && ret.code() != ENOENT) {
883                 ALOGE("Failed to remove uid %u from permission map: %s", uid, strerror(ret.code()));
884             }
885         }
886     }
887 }
888 
getProgramStatus(const char * path)889 std::string getProgramStatus(const char *path) {
890     int ret = access(path, R_OK);
891     if (ret == 0) {
892         return StringPrintf("OK");
893     }
894     if (ret != 0 && errno == ENOENT) {
895         return StringPrintf("program is missing at: %s", path);
896     }
897     return StringPrintf("check Program %s error: %s", path, strerror(errno));
898 }
899 
getMapStatus(const base::unique_fd & map_fd,const char * path)900 std::string getMapStatus(const base::unique_fd& map_fd, const char* path) {
901     if (map_fd.get() < 0) {
902         return StringPrintf("map fd lost");
903     }
904     if (access(path, F_OK) != 0) {
905         return StringPrintf("map not pinned to location: %s", path);
906     }
907     return StringPrintf("OK");
908 }
909 
910 // NOLINTNEXTLINE(google-runtime-references): grandfathered pass by non-const reference
dumpBpfMap(const std::string & mapName,DumpWriter & dw,const std::string & header)911 void dumpBpfMap(const std::string& mapName, DumpWriter& dw, const std::string& header) {
912     dw.blankline();
913     dw.println("%s:", mapName.c_str());
914     if (!header.empty()) {
915         dw.println(header);
916     }
917 }
918 
919 const String16 TrafficController::DUMP_KEYWORD = String16("trafficcontroller");
920 
dump(DumpWriter & dw,bool verbose)921 void TrafficController::dump(DumpWriter& dw, bool verbose) {
922     std::lock_guard guard(mMutex);
923     ScopedIndent indentTop(dw);
924     dw.println("TrafficController");
925 
926     ScopedIndent indentPreBpfModule(dw);
927     dw.println("BPF module status: %s", BpfLevelToString(mBpfLevel).c_str());
928 
929     if (mBpfLevel == BpfLevel::NONE) {
930         return;
931     }
932 
933     dw.blankline();
934     dw.println("mCookieTagMap status: %s",
935                getMapStatus(mCookieTagMap.getMap(), COOKIE_TAG_MAP_PATH).c_str());
936     dw.println("mUidCounterSetMap status: %s",
937                getMapStatus(mUidCounterSetMap.getMap(), UID_COUNTERSET_MAP_PATH).c_str());
938     dw.println("mAppUidStatsMap status: %s",
939                getMapStatus(mAppUidStatsMap.getMap(), APP_UID_STATS_MAP_PATH).c_str());
940     dw.println("mStatsMapA status: %s",
941                getMapStatus(mStatsMapA.getMap(), STATS_MAP_A_PATH).c_str());
942     dw.println("mStatsMapB status: %s",
943                getMapStatus(mStatsMapB.getMap(), STATS_MAP_B_PATH).c_str());
944     dw.println("mIfaceIndexNameMap status: %s",
945                getMapStatus(mIfaceIndexNameMap.getMap(), IFACE_INDEX_NAME_MAP_PATH).c_str());
946     dw.println("mIfaceStatsMap status: %s",
947                getMapStatus(mIfaceStatsMap.getMap(), IFACE_STATS_MAP_PATH).c_str());
948     dw.println("mConfigurationMap status: %s",
949                getMapStatus(mConfigurationMap.getMap(), CONFIGURATION_MAP_PATH).c_str());
950     dw.println("mUidOwnerMap status: %s",
951                getMapStatus(mUidOwnerMap.getMap(), UID_OWNER_MAP_PATH).c_str());
952 
953     dw.blankline();
954     dw.println("Cgroup ingress program status: %s",
955                getProgramStatus(BPF_INGRESS_PROG_PATH).c_str());
956     dw.println("Cgroup egress program status: %s", getProgramStatus(BPF_EGRESS_PROG_PATH).c_str());
957     dw.println("xt_bpf ingress program status: %s",
958                getProgramStatus(XT_BPF_INGRESS_PROG_PATH).c_str());
959     dw.println("xt_bpf egress program status: %s",
960                getProgramStatus(XT_BPF_EGRESS_PROG_PATH).c_str());
961     dw.println("xt_bpf bandwidth whitelist program status: %s",
962                getProgramStatus(XT_BPF_WHITELIST_PROG_PATH).c_str());
963     dw.println("xt_bpf bandwidth blacklist program status: %s",
964                getProgramStatus(XT_BPF_BLACKLIST_PROG_PATH).c_str());
965 
966     if (!verbose) {
967         return;
968     }
969 
970     dw.blankline();
971     dw.println("BPF map content:");
972 
973     ScopedIndent indentForMapContent(dw);
974 
975     // Print CookieTagMap content.
976     dumpBpfMap("mCookieTagMap", dw, "");
977     const auto printCookieTagInfo = [&dw](const uint64_t& key, const UidTag& value,
978                                           const BpfMap<uint64_t, UidTag>&) {
979         dw.println("cookie=%" PRIu64 " tag=0x%x uid=%u", key, value.tag, value.uid);
980         return netdutils::status::ok;
981     };
982     Status res = mCookieTagMap.iterateWithValue(printCookieTagInfo);
983     if (!isOk(res)) {
984         dw.println("mCookieTagMap print end with error: %s", res.msg().c_str());
985     }
986 
987     // Print UidCounterSetMap Content
988     dumpBpfMap("mUidCounterSetMap", dw, "");
989     const auto printUidInfo = [&dw](const uint32_t& key, const uint8_t& value,
990                                     const BpfMap<uint32_t, uint8_t>&) {
991         dw.println("%u %u", key, value);
992         return netdutils::status::ok;
993     };
994     res = mUidCounterSetMap.iterateWithValue(printUidInfo);
995     if (!isOk(res)) {
996         dw.println("mUidCounterSetMap print end with error: %s", res.msg().c_str());
997     }
998 
999     // Print AppUidStatsMap content
1000     std::string appUidStatsHeader = StringPrintf("uid rxBytes rxPackets txBytes txPackets");
1001     dumpBpfMap("mAppUidStatsMap:", dw, appUidStatsHeader);
1002     auto printAppUidStatsInfo = [&dw](const uint32_t& key, const StatsValue& value,
1003                                       const BpfMap<uint32_t, StatsValue>&) {
1004         dw.println("%u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, value.rxBytes,
1005                    value.rxPackets, value.txBytes, value.txPackets);
1006         return netdutils::status::ok;
1007     };
1008     res = mAppUidStatsMap.iterateWithValue(printAppUidStatsInfo);
1009     if (!res.ok()) {
1010         dw.println("mAppUidStatsMap print end with error: %s", res.msg().c_str());
1011     }
1012 
1013     // Print uidStatsMap content
1014     std::string statsHeader = StringPrintf("ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes"
1015                                            " rxPackets txBytes txPackets");
1016     dumpBpfMap("mStatsMapA", dw, statsHeader);
1017     const auto printStatsInfo = [&dw, this](const StatsKey& key, const StatsValue& value,
1018                                             const BpfMap<StatsKey, StatsValue>&) {
1019         uint32_t ifIndex = key.ifaceIndex;
1020         auto ifname = mIfaceIndexNameMap.readValue(ifIndex);
1021         if (!isOk(ifname)) {
1022             strlcpy(ifname.value().name, "unknown", sizeof(IfaceValue));
1023         }
1024         dw.println("%u %s 0x%x %u %u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, ifIndex,
1025                    ifname.value().name, key.tag, key.uid, key.counterSet, value.rxBytes,
1026                    value.rxPackets, value.txBytes, value.txPackets);
1027         return netdutils::status::ok;
1028     };
1029     res = mStatsMapA.iterateWithValue(printStatsInfo);
1030     if (!isOk(res)) {
1031         dw.println("mStatsMapA print end with error: %s", res.msg().c_str());
1032     }
1033 
1034     // Print TagStatsMap content.
1035     dumpBpfMap("mStatsMapB", dw, statsHeader);
1036     res = mStatsMapB.iterateWithValue(printStatsInfo);
1037     if (!isOk(res)) {
1038         dw.println("mStatsMapB print end with error: %s", res.msg().c_str());
1039     }
1040 
1041     // Print ifaceIndexToNameMap content.
1042     dumpBpfMap("mIfaceIndexNameMap", dw, "");
1043     const auto printIfaceNameInfo = [&dw](const uint32_t& key, const IfaceValue& value,
1044                                           const BpfMap<uint32_t, IfaceValue>&) {
1045         const char* ifname = value.name;
1046         dw.println("ifaceIndex=%u ifaceName=%s", key, ifname);
1047         return netdutils::status::ok;
1048     };
1049     res = mIfaceIndexNameMap.iterateWithValue(printIfaceNameInfo);
1050     if (!isOk(res)) {
1051         dw.println("mIfaceIndexNameMap print end with error: %s", res.msg().c_str());
1052     }
1053 
1054     // Print ifaceStatsMap content
1055     std::string ifaceStatsHeader = StringPrintf("ifaceIndex ifaceName rxBytes rxPackets txBytes"
1056                                                 " txPackets");
1057     dumpBpfMap("mIfaceStatsMap:", dw, ifaceStatsHeader);
1058     const auto printIfaceStatsInfo = [&dw, this](const uint32_t& key, const StatsValue& value,
1059                                                  const BpfMap<uint32_t, StatsValue>&) {
1060         auto ifname = mIfaceIndexNameMap.readValue(key);
1061         if (!isOk(ifname)) {
1062             strlcpy(ifname.value().name, "unknown", sizeof(IfaceValue));
1063         }
1064         dw.println("%u %s %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, ifname.value().name,
1065                    value.rxBytes, value.rxPackets, value.txBytes, value.txPackets);
1066         return netdutils::status::ok;
1067     };
1068     res = mIfaceStatsMap.iterateWithValue(printIfaceStatsInfo);
1069     if (!isOk(res)) {
1070         dw.println("mIfaceStatsMap print end with error: %s", res.msg().c_str());
1071     }
1072 
1073     dw.blankline();
1074 
1075     uint32_t key = UID_RULES_CONFIGURATION_KEY;
1076     auto configuration = mConfigurationMap.readValue(key);
1077     if (isOk(configuration)) {
1078         dw.println("current ownerMatch configuration: %d", configuration.value());
1079     } else {
1080         dw.println("mConfigurationMap read ownerMatch configure failed with error: %s",
1081                    configuration.status().msg().c_str());
1082     }
1083     key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
1084     configuration = mConfigurationMap.readValue(key);
1085     if (isOk(configuration)) {
1086         dw.println("current statsMap configuration: %d", configuration.value());
1087     } else {
1088         dw.println("mConfigurationMap read stats map configure failed with error: %s",
1089                    configuration.status().msg().c_str());
1090     }
1091     dumpBpfMap("mUidOwnerMap", dw, "");
1092     const auto printUidMatchInfo = [&dw, this](const uint32_t& key, const UidOwnerValue& value,
1093                                                const BpfMap<uint32_t, UidOwnerValue>&) {
1094         if (value.rule & IIF_MATCH) {
1095             auto ifname = mIfaceIndexNameMap.readValue(value.iif);
1096             if (isOk(ifname)) {
1097                 dw.println("%u %s %s", key, uidMatchTypeToString(value.rule).c_str(),
1098                            ifname.value().name);
1099             } else {
1100                 dw.println("%u %s %u", key, uidMatchTypeToString(value.rule).c_str(), value.iif);
1101             }
1102         } else {
1103             dw.println("%u %s", key, uidMatchTypeToString(value.rule).c_str());
1104         }
1105         return netdutils::status::ok;
1106     };
1107     res = mUidOwnerMap.iterateWithValue(printUidMatchInfo);
1108     if (!isOk(res)) {
1109         dw.println("mUidOwnerMap print end with error: %s", res.msg().c_str());
1110     }
1111     dumpBpfMap("mUidPermissionMap", dw, "");
1112     const auto printUidPermissionInfo = [&dw](const uint32_t& key, const uint8_t& value,
1113                                               const BpfMap<uint32_t, uint8_t>&) {
1114         dw.println("%u %s", key, UidPermissionTypeToString(value).c_str());
1115         return netdutils::status::ok;
1116     };
1117     res = mUidPermissionMap.iterateWithValue(printUidPermissionInfo);
1118     if (!isOk(res)) {
1119         dw.println("mUidPermissionMap print end with error: %s", res.msg().c_str());
1120     }
1121 
1122     dumpBpfMap("mPrivilegedUser", dw, "");
1123     for (uid_t uid : mPrivilegedUser) {
1124         dw.println("%u ALLOW_UPDATE_DEVICE_STATS", (uint32_t)uid);
1125     }
1126 }
1127 
1128 }  // namespace net
1129 }  // namespace android
1130