1 /*
2  * Copyright (C) 2022 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/if_ether.h>
20 #include <linux/in.h>
21 #include <linux/inet_diag.h>
22 #include <linux/netlink.h>
23 #include <linux/sock_diag.h>
24 #include <linux/unistd.h>
25 #include <net/if.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/socket.h>
29 #include <sys/stat.h>
30 #include <sys/types.h>
31 #include <sys/utsname.h>
32 #include <sys/wait.h>
33 #include <map>
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 <netdutils/StatusOr.h>
42 #include <netdutils/Syscalls.h>
43 #include <netdutils/UidConstants.h>
44 #include <netdutils/Utils.h>
45 #include <private/android_filesystem_config.h>
46 
47 #include "TrafficController.h"
48 #include "bpf/BpfMap.h"
49 #include "netdutils/DumpWriter.h"
50 
51 namespace android {
52 namespace net {
53 
54 using base::StringPrintf;
55 using base::unique_fd;
56 using bpf::BpfMap;
57 using bpf::synchronizeKernelRCU;
58 using netdutils::DumpWriter;
59 using netdutils::NetlinkListener;
60 using netdutils::NetlinkListenerInterface;
61 using netdutils::ScopedIndent;
62 using netdutils::Slice;
63 using netdutils::sSyscalls;
64 using netdutils::Status;
65 using netdutils::statusFromErrno;
66 using netdutils::StatusOr;
67 
68 constexpr int kSockDiagMsgType = SOCK_DIAG_BY_FAMILY;
69 constexpr int kSockDiagDoneMsgType = NLMSG_DONE;
70 
71 const char* TrafficController::LOCAL_DOZABLE = "fw_dozable";
72 const char* TrafficController::LOCAL_STANDBY = "fw_standby";
73 const char* TrafficController::LOCAL_POWERSAVE = "fw_powersave";
74 const char* TrafficController::LOCAL_RESTRICTED = "fw_restricted";
75 const char* TrafficController::LOCAL_LOW_POWER_STANDBY = "fw_low_power_standby";
76 const char* TrafficController::LOCAL_OEM_DENY_1 = "fw_oem_deny_1";
77 const char* TrafficController::LOCAL_OEM_DENY_2 = "fw_oem_deny_2";
78 const char* TrafficController::LOCAL_OEM_DENY_3 = "fw_oem_deny_3";
79 
80 static_assert(BPF_PERMISSION_INTERNET == INetd::PERMISSION_INTERNET,
81               "Mismatch between BPF and AIDL permissions: PERMISSION_INTERNET");
82 static_assert(BPF_PERMISSION_UPDATE_DEVICE_STATS == INetd::PERMISSION_UPDATE_DEVICE_STATS,
83               "Mismatch between BPF and AIDL permissions: PERMISSION_UPDATE_DEVICE_STATS");
84 
85 #define FLAG_MSG_TRANS(result, flag, value) \
86     do {                                    \
87         if ((value) & (flag)) {             \
88             (result).append(" " #flag);     \
89             (value) &= ~(flag);             \
90         }                                   \
91     } while (0)
92 
uidMatchTypeToString(uint32_t match)93 const std::string uidMatchTypeToString(uint32_t match) {
94     std::string matchType;
95     FLAG_MSG_TRANS(matchType, HAPPY_BOX_MATCH, match);
96     FLAG_MSG_TRANS(matchType, PENALTY_BOX_MATCH, match);
97     FLAG_MSG_TRANS(matchType, DOZABLE_MATCH, match);
98     FLAG_MSG_TRANS(matchType, STANDBY_MATCH, match);
99     FLAG_MSG_TRANS(matchType, POWERSAVE_MATCH, match);
100     FLAG_MSG_TRANS(matchType, RESTRICTED_MATCH, match);
101     FLAG_MSG_TRANS(matchType, LOW_POWER_STANDBY_MATCH, match);
102     FLAG_MSG_TRANS(matchType, IIF_MATCH, match);
103     FLAG_MSG_TRANS(matchType, LOCKDOWN_VPN_MATCH, match);
104     FLAG_MSG_TRANS(matchType, OEM_DENY_1_MATCH, match);
105     FLAG_MSG_TRANS(matchType, OEM_DENY_2_MATCH, match);
106     FLAG_MSG_TRANS(matchType, OEM_DENY_3_MATCH, match);
107     if (match) {
108         return StringPrintf("Unknown match: %u", match);
109     }
110     return matchType;
111 }
112 
UidPermissionTypeToString(int permission)113 const std::string UidPermissionTypeToString(int permission) {
114     if (permission == INetd::PERMISSION_NONE) {
115         return "PERMISSION_NONE";
116     }
117     if (permission == INetd::PERMISSION_UNINSTALLED) {
118         // This should never appear in the map, complain loudly if it does.
119         return "PERMISSION_UNINSTALLED error!";
120     }
121     std::string permissionType;
122     FLAG_MSG_TRANS(permissionType, BPF_PERMISSION_INTERNET, permission);
123     FLAG_MSG_TRANS(permissionType, BPF_PERMISSION_UPDATE_DEVICE_STATS, permission);
124     if (permission) {
125         return StringPrintf("Unknown permission: %u", permission);
126     }
127     return permissionType;
128 }
129 
makeSkDestroyListener()130 StatusOr<std::unique_ptr<NetlinkListenerInterface>> TrafficController::makeSkDestroyListener() {
131     const auto& sys = sSyscalls.get();
132     ASSIGN_OR_RETURN(auto event, sys.eventfd(0, EFD_CLOEXEC));
133     const int domain = AF_NETLINK;
134     const int type = SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK;
135     const int protocol = NETLINK_INET_DIAG;
136     ASSIGN_OR_RETURN(auto sock, sys.socket(domain, type, protocol));
137 
138     // TODO: if too many sockets are closed too quickly, we can overflow the socket buffer, and
139     // some entries in mCookieTagMap will not be freed. In order to fix this we would need to
140     // periodically dump all sockets and remove the tag entries for sockets that have been closed.
141     // For now, set a large-enough buffer that we can close hundreds of sockets without getting
142     // ENOBUFS and leaking mCookieTagMap entries.
143     int rcvbuf = 512 * 1024;
144     auto ret = sys.setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf));
145     if (!ret.ok()) {
146         ALOGW("Failed to set SkDestroyListener buffer size to %d: %s", rcvbuf, ret.msg().c_str());
147     }
148 
149     sockaddr_nl addr = {
150         .nl_family = AF_NETLINK,
151         .nl_groups = 1 << (SKNLGRP_INET_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET_UDP_DESTROY - 1) |
152                      1 << (SKNLGRP_INET6_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET6_UDP_DESTROY - 1)};
153     RETURN_IF_NOT_OK(sys.bind(sock, addr));
154 
155     const sockaddr_nl kernel = {.nl_family = AF_NETLINK};
156     RETURN_IF_NOT_OK(sys.connect(sock, kernel));
157 
158     std::unique_ptr<NetlinkListenerInterface> listener =
159             std::make_unique<NetlinkListener>(std::move(event), std::move(sock), "SkDestroyListen");
160 
161     return listener;
162 }
163 
initMaps()164 Status TrafficController::initMaps() {
165     std::lock_guard guard(mMutex);
166 
167     RETURN_IF_NOT_OK(mCookieTagMap.init(COOKIE_TAG_MAP_PATH));
168     RETURN_IF_NOT_OK(mUidCounterSetMap.init(UID_COUNTERSET_MAP_PATH));
169     RETURN_IF_NOT_OK(mAppUidStatsMap.init(APP_UID_STATS_MAP_PATH));
170     RETURN_IF_NOT_OK(mStatsMapA.init(STATS_MAP_A_PATH));
171     RETURN_IF_NOT_OK(mStatsMapB.init(STATS_MAP_B_PATH));
172     RETURN_IF_NOT_OK(mIfaceIndexNameMap.init(IFACE_INDEX_NAME_MAP_PATH));
173     RETURN_IF_NOT_OK(mIfaceStatsMap.init(IFACE_STATS_MAP_PATH));
174 
175     RETURN_IF_NOT_OK(mConfigurationMap.init(CONFIGURATION_MAP_PATH));
176 
177     RETURN_IF_NOT_OK(mUidOwnerMap.init(UID_OWNER_MAP_PATH));
178     RETURN_IF_NOT_OK(mUidPermissionMap.init(UID_PERMISSION_MAP_PATH));
179     ALOGI("%s successfully", __func__);
180 
181     return netdutils::status::ok;
182 }
183 
start(bool startSkDestroyListener)184 Status TrafficController::start(bool startSkDestroyListener) {
185     RETURN_IF_NOT_OK(initMaps());
186 
187     if (!startSkDestroyListener) {
188         return netdutils::status::ok;
189     }
190 
191     auto result = makeSkDestroyListener();
192     if (!isOk(result)) {
193         ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
194     } else {
195         mSkDestroyListener = std::move(result.value());
196     }
197     // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
198     const auto rxHandler = [this](const nlmsghdr&, const Slice msg) {
199         std::lock_guard guard(mMutex);
200         inet_diag_msg diagmsg = {};
201         if (extract(msg, diagmsg) < sizeof(inet_diag_msg)) {
202             ALOGE("Unrecognized netlink message: %s", toString(msg).c_str());
203             return;
204         }
205         uint64_t sock_cookie = static_cast<uint64_t>(diagmsg.id.idiag_cookie[0]) |
206                                (static_cast<uint64_t>(diagmsg.id.idiag_cookie[1]) << 32);
207 
208         Status s = mCookieTagMap.deleteValue(sock_cookie);
209         if (!isOk(s) && s.code() != ENOENT) {
210             ALOGE("Failed to delete cookie %" PRIx64 ": %s", sock_cookie, toString(s).c_str());
211             return;
212         }
213     };
214     expectOk(mSkDestroyListener->subscribe(kSockDiagMsgType, rxHandler));
215 
216     // In case multiple netlink message comes in as a stream, we need to handle the rxDone message
217     // properly.
218     const auto rxDoneHandler = [](const nlmsghdr&, const Slice msg) {
219         // Ignore NLMSG_DONE  messages
220         inet_diag_msg diagmsg = {};
221         extract(msg, diagmsg);
222     };
223     expectOk(mSkDestroyListener->subscribe(kSockDiagDoneMsgType, rxDoneHandler));
224 
225     return netdutils::status::ok;
226 }
227 
updateOwnerMapEntry(UidOwnerMatchType match,uid_t uid,FirewallRule rule,FirewallType type)228 Status TrafficController::updateOwnerMapEntry(UidOwnerMatchType match, uid_t uid, FirewallRule rule,
229                                               FirewallType type) {
230     std::lock_guard guard(mMutex);
231     if ((rule == ALLOW && type == ALLOWLIST) || (rule == DENY && type == DENYLIST)) {
232         RETURN_IF_NOT_OK(addRule(uid, match));
233     } else if ((rule == ALLOW && type == DENYLIST) || (rule == DENY && type == ALLOWLIST)) {
234         RETURN_IF_NOT_OK(removeRule(uid, match));
235     } else {
236         //Cannot happen.
237         return statusFromErrno(EINVAL, "");
238     }
239     return netdutils::status::ok;
240 }
241 
removeRule(uint32_t uid,UidOwnerMatchType match)242 Status TrafficController::removeRule(uint32_t uid, UidOwnerMatchType match) {
243     auto oldMatch = mUidOwnerMap.readValue(uid);
244     if (oldMatch.ok()) {
245         UidOwnerValue newMatch = {
246                 .iif = (match == IIF_MATCH) ? 0 : oldMatch.value().iif,
247                 .rule = oldMatch.value().rule & ~match,
248         };
249         if (newMatch.rule == 0) {
250             RETURN_IF_NOT_OK(mUidOwnerMap.deleteValue(uid));
251         } else {
252             RETURN_IF_NOT_OK(mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY));
253         }
254     } else {
255         return statusFromErrno(ENOENT, StringPrintf("uid: %u does not exist in map", uid));
256     }
257     return netdutils::status::ok;
258 }
259 
addRule(uint32_t uid,UidOwnerMatchType match,uint32_t iif)260 Status TrafficController::addRule(uint32_t uid, UidOwnerMatchType match, uint32_t iif) {
261     if (match != IIF_MATCH && iif != 0) {
262         return statusFromErrno(EINVAL, "Non-interface match must have zero interface index");
263     }
264     auto oldMatch = mUidOwnerMap.readValue(uid);
265     if (oldMatch.ok()) {
266         UidOwnerValue newMatch = {
267                 .iif = (match == IIF_MATCH) ? iif : oldMatch.value().iif,
268                 .rule = oldMatch.value().rule | match,
269         };
270         RETURN_IF_NOT_OK(mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY));
271     } else {
272         UidOwnerValue newMatch = {
273                 .iif = iif,
274                 .rule = match,
275         };
276         RETURN_IF_NOT_OK(mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY));
277     }
278     return netdutils::status::ok;
279 }
280 
updateUidOwnerMap(const uint32_t uid,UidOwnerMatchType matchType,IptOp op)281 Status TrafficController::updateUidOwnerMap(const uint32_t uid,
282                                             UidOwnerMatchType matchType, IptOp op) {
283     std::lock_guard guard(mMutex);
284     if (op == IptOpDelete) {
285         RETURN_IF_NOT_OK(removeRule(uid, matchType));
286     } else if (op == IptOpInsert) {
287         RETURN_IF_NOT_OK(addRule(uid, matchType));
288     } else {
289         // Cannot happen.
290         return statusFromErrno(EINVAL, StringPrintf("invalid IptOp: %d, %d", op, matchType));
291     }
292     return netdutils::status::ok;
293 }
294 
getFirewallType(ChildChain chain)295 FirewallType TrafficController::getFirewallType(ChildChain chain) {
296     switch (chain) {
297         case DOZABLE:
298             return ALLOWLIST;
299         case STANDBY:
300             return DENYLIST;
301         case POWERSAVE:
302             return ALLOWLIST;
303         case RESTRICTED:
304             return ALLOWLIST;
305         case LOW_POWER_STANDBY:
306             return ALLOWLIST;
307         case OEM_DENY_1:
308             return DENYLIST;
309         case OEM_DENY_2:
310             return DENYLIST;
311         case OEM_DENY_3:
312             return DENYLIST;
313         case NONE:
314         default:
315             return DENYLIST;
316     }
317 }
318 
changeUidOwnerRule(ChildChain chain,uid_t uid,FirewallRule rule,FirewallType type)319 int TrafficController::changeUidOwnerRule(ChildChain chain, uid_t uid, FirewallRule rule,
320                                           FirewallType type) {
321     Status res;
322     switch (chain) {
323         case DOZABLE:
324             res = updateOwnerMapEntry(DOZABLE_MATCH, uid, rule, type);
325             break;
326         case STANDBY:
327             res = updateOwnerMapEntry(STANDBY_MATCH, uid, rule, type);
328             break;
329         case POWERSAVE:
330             res = updateOwnerMapEntry(POWERSAVE_MATCH, uid, rule, type);
331             break;
332         case RESTRICTED:
333             res = updateOwnerMapEntry(RESTRICTED_MATCH, uid, rule, type);
334             break;
335         case LOW_POWER_STANDBY:
336             res = updateOwnerMapEntry(LOW_POWER_STANDBY_MATCH, uid, rule, type);
337             break;
338         case OEM_DENY_1:
339             res = updateOwnerMapEntry(OEM_DENY_1_MATCH, uid, rule, type);
340             break;
341         case OEM_DENY_2:
342             res = updateOwnerMapEntry(OEM_DENY_2_MATCH, uid, rule, type);
343             break;
344         case OEM_DENY_3:
345             res = updateOwnerMapEntry(OEM_DENY_3_MATCH, uid, rule, type);
346             break;
347         case NONE:
348         default:
349             ALOGW("Unknown child chain: %d", chain);
350             return -EINVAL;
351     }
352     if (!isOk(res)) {
353         ALOGE("change uid(%u) rule of %d failed: %s, rule: %d, type: %d", uid, chain,
354               res.msg().c_str(), rule, type);
355         return -res.code();
356     }
357     return 0;
358 }
359 
replaceRulesInMap(const UidOwnerMatchType match,const std::vector<int32_t> & uids)360 Status TrafficController::replaceRulesInMap(const UidOwnerMatchType match,
361                                             const std::vector<int32_t>& uids) {
362     std::lock_guard guard(mMutex);
363     std::set<int32_t> uidSet(uids.begin(), uids.end());
364     std::vector<uint32_t> uidsToDelete;
365     auto getUidsToDelete = [&uidsToDelete, &uidSet](const uint32_t& key,
366                                                     const BpfMap<uint32_t, UidOwnerValue>&) {
367         if (uidSet.find((int32_t) key) == uidSet.end()) {
368             uidsToDelete.push_back(key);
369         }
370         return base::Result<void>();
371     };
372     RETURN_IF_NOT_OK(mUidOwnerMap.iterate(getUidsToDelete));
373 
374     for(auto uid : uidsToDelete) {
375         RETURN_IF_NOT_OK(removeRule(uid, match));
376     }
377 
378     for (auto uid : uids) {
379         RETURN_IF_NOT_OK(addRule(uid, match));
380     }
381     return netdutils::status::ok;
382 }
383 
addUidInterfaceRules(const int iif,const std::vector<int32_t> & uidsToAdd)384 Status TrafficController::addUidInterfaceRules(const int iif,
385                                                const std::vector<int32_t>& uidsToAdd) {
386     std::lock_guard guard(mMutex);
387 
388     for (auto uid : uidsToAdd) {
389         netdutils::Status result = addRule(uid, IIF_MATCH, iif);
390         if (!isOk(result)) {
391             ALOGW("addRule failed(%d): uid=%d iif=%d", result.code(), uid, iif);
392         }
393     }
394     return netdutils::status::ok;
395 }
396 
removeUidInterfaceRules(const std::vector<int32_t> & uidsToDelete)397 Status TrafficController::removeUidInterfaceRules(const std::vector<int32_t>& uidsToDelete) {
398     std::lock_guard guard(mMutex);
399 
400     for (auto uid : uidsToDelete) {
401         netdutils::Status result = removeRule(uid, IIF_MATCH);
402         if (!isOk(result)) {
403             ALOGW("removeRule failed(%d): uid=%d", result.code(), uid);
404         }
405     }
406     return netdutils::status::ok;
407 }
408 
updateUidLockdownRule(const uid_t uid,const bool add)409 Status TrafficController::updateUidLockdownRule(const uid_t uid, const bool add) {
410     std::lock_guard guard(mMutex);
411 
412     netdutils::Status result = add ? addRule(uid, LOCKDOWN_VPN_MATCH)
413                                : removeRule(uid, LOCKDOWN_VPN_MATCH);
414     if (!isOk(result)) {
415         ALOGW("%s Lockdown rule failed(%d): uid=%d",
416               (add ? "add": "remove"), result.code(), uid);
417     }
418     return result;
419 }
420 
replaceUidOwnerMap(const std::string & name,bool isAllowlist __unused,const std::vector<int32_t> & uids)421 int TrafficController::replaceUidOwnerMap(const std::string& name, bool isAllowlist __unused,
422                                           const std::vector<int32_t>& uids) {
423     // FirewallRule rule = isAllowlist ? ALLOW : DENY;
424     // FirewallType type = isAllowlist ? ALLOWLIST : DENYLIST;
425     Status res;
426     if (!name.compare(LOCAL_DOZABLE)) {
427         res = replaceRulesInMap(DOZABLE_MATCH, uids);
428     } else if (!name.compare(LOCAL_STANDBY)) {
429         res = replaceRulesInMap(STANDBY_MATCH, uids);
430     } else if (!name.compare(LOCAL_POWERSAVE)) {
431         res = replaceRulesInMap(POWERSAVE_MATCH, uids);
432     } else if (!name.compare(LOCAL_RESTRICTED)) {
433         res = replaceRulesInMap(RESTRICTED_MATCH, uids);
434     } else if (!name.compare(LOCAL_LOW_POWER_STANDBY)) {
435         res = replaceRulesInMap(LOW_POWER_STANDBY_MATCH, uids);
436     } else if (!name.compare(LOCAL_OEM_DENY_1)) {
437         res = replaceRulesInMap(OEM_DENY_1_MATCH, uids);
438     } else if (!name.compare(LOCAL_OEM_DENY_2)) {
439         res = replaceRulesInMap(OEM_DENY_2_MATCH, uids);
440     } else if (!name.compare(LOCAL_OEM_DENY_3)) {
441         res = replaceRulesInMap(OEM_DENY_3_MATCH, uids);
442     } else {
443         ALOGE("unknown chain name: %s", name.c_str());
444         return -EINVAL;
445     }
446     if (!isOk(res)) {
447         ALOGE("Failed to clean up chain: %s: %s", name.c_str(), res.msg().c_str());
448         return -res.code();
449     }
450     return 0;
451 }
452 
toggleUidOwnerMap(ChildChain chain,bool enable)453 int TrafficController::toggleUidOwnerMap(ChildChain chain, bool enable) {
454     std::lock_guard guard(mMutex);
455     uint32_t key = UID_RULES_CONFIGURATION_KEY;
456     auto oldConfigure = mConfigurationMap.readValue(key);
457     if (!oldConfigure.ok()) {
458         ALOGE("Cannot read the old configuration from map: %s",
459               oldConfigure.error().message().c_str());
460         return -oldConfigure.error().code();
461     }
462     uint32_t match;
463     switch (chain) {
464         case DOZABLE:
465             match = DOZABLE_MATCH;
466             break;
467         case STANDBY:
468             match = STANDBY_MATCH;
469             break;
470         case POWERSAVE:
471             match = POWERSAVE_MATCH;
472             break;
473         case RESTRICTED:
474             match = RESTRICTED_MATCH;
475             break;
476         case LOW_POWER_STANDBY:
477             match = LOW_POWER_STANDBY_MATCH;
478             break;
479         case OEM_DENY_1:
480             match = OEM_DENY_1_MATCH;
481             break;
482         case OEM_DENY_2:
483             match = OEM_DENY_2_MATCH;
484             break;
485         case OEM_DENY_3:
486             match = OEM_DENY_3_MATCH;
487             break;
488         default:
489             return -EINVAL;
490     }
491     BpfConfig newConfiguration =
492             enable ? (oldConfigure.value() | match) : (oldConfigure.value() & ~match);
493     Status res = mConfigurationMap.writeValue(key, newConfiguration, BPF_EXIST);
494     if (!isOk(res)) {
495         ALOGE("Failed to toggleUidOwnerMap(%d): %s", chain, res.msg().c_str());
496     }
497     return -res.code();
498 }
499 
swapActiveStatsMap()500 Status TrafficController::swapActiveStatsMap() {
501     std::lock_guard guard(mMutex);
502 
503     uint32_t key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
504     auto oldConfigure = mConfigurationMap.readValue(key);
505     if (!oldConfigure.ok()) {
506         ALOGE("Cannot read the old configuration from map: %s",
507               oldConfigure.error().message().c_str());
508         return Status(oldConfigure.error().code(), oldConfigure.error().message());
509     }
510 
511     // Write to the configuration map to inform the kernel eBPF program to switch
512     // from using one map to the other. Use flag BPF_EXIST here since the map should
513     // be already populated in initMaps.
514     uint32_t newConfigure = (oldConfigure.value() == SELECT_MAP_A) ? SELECT_MAP_B : SELECT_MAP_A;
515     auto res = mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, newConfigure,
516                                             BPF_EXIST);
517     if (!res.ok()) {
518         ALOGE("Failed to toggle the stats map: %s", strerror(res.error().code()));
519         return res;
520     }
521     // After changing the config, we need to make sure all the current running
522     // eBPF programs are finished and all the CPUs are aware of this config change
523     // before we modify the old map. So we do a special hack here to wait for
524     // the kernel to do a synchronize_rcu(). Once the kernel called
525     // synchronize_rcu(), the config we just updated will be available to all cores
526     // and the next eBPF programs triggered inside the kernel will use the new
527     // map configuration. So once this function returns we can safely modify the
528     // old stats map without concerning about race between the kernel and
529     // userspace.
530     int ret = synchronizeKernelRCU();
531     if (ret) {
532         ALOGE("map swap synchronize_rcu() ended with failure: %s", strerror(-ret));
533         return statusFromErrno(-ret, "map swap synchronize_rcu() failed");
534     }
535     return netdutils::status::ok;
536 }
537 
setPermissionForUids(int permission,const std::vector<uid_t> & uids)538 void TrafficController::setPermissionForUids(int permission, const std::vector<uid_t>& uids) {
539     std::lock_guard guard(mMutex);
540     if (permission == INetd::PERMISSION_UNINSTALLED) {
541         for (uid_t uid : uids) {
542             // Clean up all permission information for the related uid if all the
543             // packages related to it are uninstalled.
544             mPrivilegedUser.erase(uid);
545             Status ret = mUidPermissionMap.deleteValue(uid);
546             if (!isOk(ret) && ret.code() != ENOENT) {
547                 ALOGE("Failed to clean up the permission for %u: %s", uid, strerror(ret.code()));
548             }
549         }
550         return;
551     }
552 
553     bool privileged = (permission & INetd::PERMISSION_UPDATE_DEVICE_STATS);
554 
555     for (uid_t uid : uids) {
556         if (privileged) {
557             mPrivilegedUser.insert(uid);
558         } else {
559             mPrivilegedUser.erase(uid);
560         }
561 
562         // The map stores all the permissions that the UID has, except if the only permission
563         // the UID has is the INTERNET permission, then the UID should not appear in the map.
564         if (permission != INetd::PERMISSION_INTERNET) {
565             Status ret = mUidPermissionMap.writeValue(uid, permission, BPF_ANY);
566             if (!isOk(ret)) {
567                 ALOGE("Failed to set permission: %s of uid(%u) to permission map: %s",
568                       UidPermissionTypeToString(permission).c_str(), uid, strerror(ret.code()));
569             }
570         } else {
571             Status ret = mUidPermissionMap.deleteValue(uid);
572             if (!isOk(ret) && ret.code() != ENOENT) {
573                 ALOGE("Failed to remove uid %u from permission map: %s", uid, strerror(ret.code()));
574             }
575         }
576     }
577 }
578 
getMapStatus(const base::unique_fd & map_fd,const char * path)579 std::string getMapStatus(const base::unique_fd& map_fd, const char* path) {
580     if (map_fd.get() < 0) {
581         return StringPrintf("map fd lost");
582     }
583     if (access(path, F_OK) != 0) {
584         return StringPrintf("map not pinned to location: %s", path);
585     }
586     return StringPrintf("OK");
587 }
588 
589 // NOLINTNEXTLINE(google-runtime-references): grandfathered pass by non-const reference
dumpBpfMap(const std::string & mapName,DumpWriter & dw,const std::string & header)590 void dumpBpfMap(const std::string& mapName, DumpWriter& dw, const std::string& header) {
591     dw.blankline();
592     dw.println("%s:", mapName.c_str());
593     if (!header.empty()) {
594         dw.println(header);
595     }
596 }
597 
dump(int fd,bool verbose __unused)598 void TrafficController::dump(int fd, bool verbose __unused) {
599     std::lock_guard guard(mMutex);
600     DumpWriter dw(fd);
601 
602     ScopedIndent indentTop(dw);
603     dw.println("TrafficController");
604 
605     ScopedIndent indentPreBpfModule(dw);
606 
607     dw.blankline();
608     dw.println("mCookieTagMap status: %s",
609                getMapStatus(mCookieTagMap.getMap(), COOKIE_TAG_MAP_PATH).c_str());
610     dw.println("mUidCounterSetMap status: %s",
611                getMapStatus(mUidCounterSetMap.getMap(), UID_COUNTERSET_MAP_PATH).c_str());
612     dw.println("mAppUidStatsMap status: %s",
613                getMapStatus(mAppUidStatsMap.getMap(), APP_UID_STATS_MAP_PATH).c_str());
614     dw.println("mStatsMapA status: %s",
615                getMapStatus(mStatsMapA.getMap(), STATS_MAP_A_PATH).c_str());
616     dw.println("mStatsMapB status: %s",
617                getMapStatus(mStatsMapB.getMap(), STATS_MAP_B_PATH).c_str());
618     dw.println("mIfaceIndexNameMap status: %s",
619                getMapStatus(mIfaceIndexNameMap.getMap(), IFACE_INDEX_NAME_MAP_PATH).c_str());
620     dw.println("mIfaceStatsMap status: %s",
621                getMapStatus(mIfaceStatsMap.getMap(), IFACE_STATS_MAP_PATH).c_str());
622     dw.println("mConfigurationMap status: %s",
623                getMapStatus(mConfigurationMap.getMap(), CONFIGURATION_MAP_PATH).c_str());
624     dw.println("mUidOwnerMap status: %s",
625                getMapStatus(mUidOwnerMap.getMap(), UID_OWNER_MAP_PATH).c_str());
626 }
627 
628 }  // namespace net
629 }  // namespace android
630