blob: 3839962f5615051e7f0b1d2ab5da5d139f74060a [file] [log] [blame]
Chenbo Fengf2759682017-10-10 17:31:57 -07001/*
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
Chenbo Fengc10a8a42017-12-15 13:56:33 -080017#define LOG_TAG "TrafficController"
Chenbo Feng33cc1032017-10-23 15:16:37 -070018#include <inttypes.h>
Chenbo Fengf2759682017-10-10 17:31:57 -070019#include <linux/bpf.h>
20#include <linux/if_ether.h>
21#include <linux/in.h>
22#include <linux/inet_diag.h>
Chenbo Feng116d0552017-12-04 17:25:19 -080023#include <linux/netlink.h>
24#include <linux/sock_diag.h>
Chenbo Fengf2759682017-10-10 17:31:57 -070025#include <linux/unistd.h>
Chenbo Fengc10a8a42017-12-15 13:56:33 -080026#include <net/if.h>
Chenbo Fengf2759682017-10-10 17:31:57 -070027#include <stdlib.h>
28#include <string.h>
29#include <sys/socket.h>
Chenbo Fengc10a8a42017-12-15 13:56:33 -080030#include <sys/stat.h>
Chenbo Feng05393d82018-01-09 15:18:43 -080031#include <sys/types.h>
Chenbo Feng33cc1032017-10-23 15:16:37 -070032#include <sys/utsname.h>
Chenbo Feng05393d82018-01-09 15:18:43 -080033#include <sys/wait.h>
Chenbo Feng89c12f12018-03-21 10:29:18 -070034#include <mutex>
Chenbo Fengc10a8a42017-12-15 13:56:33 -080035#include <unordered_set>
36#include <vector>
37
38#include <android-base/stringprintf.h>
Chenbo Fengef297172018-03-26 10:53:33 -070039#include <android-base/strings.h>
Chenbo Fengc10a8a42017-12-15 13:56:33 -080040#include <android-base/unique_fd.h>
41#include <netdutils/StatusOr.h>
Chenbo Fengf2759682017-10-10 17:31:57 -070042
Chenbo Feng116d0552017-12-04 17:25:19 -080043#include <netdutils/Misc.h>
44#include <netdutils/Syscalls.h>
Suren Baghdasaryane072a3c2019-01-16 14:36:07 -080045#include <processgroup/processgroup.h>
Chenbo Fengf2759682017-10-10 17:31:57 -070046#include "TrafficController.h"
Chenbo Feng4f6c2372018-04-26 10:37:55 -070047#include "bpf/BpfMap.h"
Chenbo Feng116d0552017-12-04 17:25:19 -080048
Chenbo Feng89c12f12018-03-21 10:29:18 -070049#include "FirewallController.h"
Chenbo Feng7e974052018-02-28 22:57:21 -080050#include "InterfaceController.h"
Chenbo Feng116d0552017-12-04 17:25:19 -080051#include "NetlinkListener.h"
Luke Huangb257d612019-03-14 21:19:13 +080052#include "netdutils/DumpWriter.h"
Chenbo Feng33cc1032017-10-23 15:16:37 -070053#include "qtaguid/qtaguid.h"
Chenbo Fengf2759682017-10-10 17:31:57 -070054
Bernie Innocenti7e25ec02018-07-02 19:32:17 +090055using namespace android::bpf; // NOLINT(google-build-using-namespace): grandfathered
Chenbo Fengf2759682017-10-10 17:31:57 -070056
57namespace android {
58namespace net {
59
Chenbo Fengc10a8a42017-12-15 13:56:33 -080060using base::StringPrintf;
61using base::unique_fd;
Luke Huangb257d612019-03-14 21:19:13 +080062using netdutils::DumpWriter;
Chenbo Feng116d0552017-12-04 17:25:19 -080063using netdutils::extract;
Luke Huangb257d612019-03-14 21:19:13 +080064using netdutils::ScopedIndent;
Chenbo Feng116d0552017-12-04 17:25:19 -080065using netdutils::Slice;
66using netdutils::sSyscalls;
Chenbo Fengc10a8a42017-12-15 13:56:33 -080067using netdutils::Status;
68using netdutils::statusFromErrno;
69using netdutils::StatusOr;
Chenbo Feng116d0552017-12-04 17:25:19 -080070using netdutils::status::ok;
Chenbo Fengc10a8a42017-12-15 13:56:33 -080071
Chenbo Feng116d0552017-12-04 17:25:19 -080072constexpr int kSockDiagMsgType = SOCK_DIAG_BY_FAMILY;
73constexpr int kSockDiagDoneMsgType = NLMSG_DONE;
Chenbo Feng82075e52019-04-12 19:21:47 -070074constexpr int PER_UID_STATS_ENTRIES_LIMIT = 500;
Chenbo Feng05662be2019-05-02 12:47:25 -070075// At most 90% of the stats map may be used by tagged traffic entries. This ensures
76// that 10% of the map is always available to count untagged traffic, one entry per UID.
77// Otherwise, apps would be able to avoid data usage accounting entirely by filling up the
78// map with tagged traffic entries.
Chenbo Fengfd88f9d2019-05-01 12:59:09 -070079constexpr int TOTAL_UID_STATS_ENTRIES_LIMIT = STATS_MAP_SIZE * 0.9;
Chenbo Feng116d0552017-12-04 17:25:19 -080080
Chenbo Fengbf660aa2019-02-26 16:12:27 -080081static_assert(BPF_PERMISSION_INTERNET == INetd::PERMISSION_INTERNET,
82 "Mismatch between BPF and AIDL permissions: PERMISSION_INTERNET");
83static_assert(BPF_PERMISSION_UPDATE_DEVICE_STATS == INetd::PERMISSION_UPDATE_DEVICE_STATS,
84 "Mismatch between BPF and AIDL permissions: PERMISSION_UPDATE_DEVICE_STATS");
Chenbo Fengfd88f9d2019-05-01 12:59:09 -070085static_assert(STATS_MAP_SIZE - TOTAL_UID_STATS_ENTRIES_LIMIT > 100,
86 "The limit for stats map is to high, stats data may be lost due to overflow");
Chenbo Fengbf660aa2019-02-26 16:12:27 -080087
Maciej Żenczykowskic0e739d2020-04-02 09:19:40 +000088#define FLAG_MSG_TRANS(result, flag, value) \
89 do { \
90 if ((value) & (flag)) { \
91 (result).append(" " #flag); \
92 (value) &= ~(flag); \
93 } \
Chenbo Feng703798e2018-06-15 17:07:59 -070094 } while (0)
95
96const std::string uidMatchTypeToString(uint8_t match) {
97 std::string matchType;
Chenbo Feng48eaed32018-12-26 17:40:21 -080098 FLAG_MSG_TRANS(matchType, HAPPY_BOX_MATCH, match);
99 FLAG_MSG_TRANS(matchType, PENALTY_BOX_MATCH, match);
100 FLAG_MSG_TRANS(matchType, DOZABLE_MATCH, match);
101 FLAG_MSG_TRANS(matchType, STANDBY_MATCH, match);
102 FLAG_MSG_TRANS(matchType, POWERSAVE_MATCH, match);
Rubin Xuec27ff22019-01-08 21:33:03 +0000103 FLAG_MSG_TRANS(matchType, IIF_MATCH, match);
Chenbo Feng703798e2018-06-15 17:07:59 -0700104 if (match) {
105 return StringPrintf("Unknown match: %u", match);
106 }
107 return matchType;
108}
109
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800110bool TrafficController::hasUpdateDeviceStatsPermission(uid_t uid) {
Chenbo Feng3969c262019-03-19 14:53:57 -0700111 // This implementation is the same logic as method ActivityManager#checkComponentPermission.
112 // It implies that the calling uid can never be the same as PER_USER_RANGE.
113 uint32_t appId = uid % PER_USER_RANGE;
114 return ((appId == AID_ROOT) || (appId == AID_SYSTEM) ||
115 mPrivilegedUser.find(appId) != mPrivilegedUser.end());
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800116}
117
Yi Kong3d82f382019-10-01 21:52:14 -0700118const std::string UidPermissionTypeToString(int permission) {
Chenbo Feng84f48cd2019-04-22 15:34:40 -0700119 if (permission == INetd::PERMISSION_NONE) {
120 return "PERMISSION_NONE";
Chenbo Fengbf660aa2019-02-26 16:12:27 -0800121 }
Chenbo Feng527908a2019-04-02 20:14:11 -0700122 if (permission == INetd::PERMISSION_UNINSTALLED) {
123 // This should never appear in the map, complain loudly if it does.
124 return "PERMISSION_UNINSTALLED error!";
125 }
Chenbo Feng48eaed32018-12-26 17:40:21 -0800126 std::string permissionType;
Chenbo Fengbf660aa2019-02-26 16:12:27 -0800127 FLAG_MSG_TRANS(permissionType, BPF_PERMISSION_INTERNET, permission);
128 FLAG_MSG_TRANS(permissionType, BPF_PERMISSION_UPDATE_DEVICE_STATS, permission);
Chenbo Feng48eaed32018-12-26 17:40:21 -0800129 if (permission) {
130 return StringPrintf("Unknown permission: %u", permission);
131 }
132 return permissionType;
133}
134
Chenbo Feng49586642018-08-30 18:01:53 -0700135StatusOr<std::unique_ptr<NetlinkListenerInterface>> TrafficController::makeSkDestroyListener() {
Chenbo Feng116d0552017-12-04 17:25:19 -0800136 const auto& sys = sSyscalls.get();
137 ASSIGN_OR_RETURN(auto event, sys.eventfd(0, EFD_CLOEXEC));
138 const int domain = AF_NETLINK;
139 const int type = SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK;
140 const int protocol = NETLINK_INET_DIAG;
141 ASSIGN_OR_RETURN(auto sock, sys.socket(domain, type, protocol));
142
Lorenzo Colitti436efdb2018-07-26 17:20:57 +0900143 // TODO: if too many sockets are closed too quickly, we can overflow the socket buffer, and
144 // some entries in mCookieTagMap will not be freed. In order to fix this we would need to
145 // periodically dump all sockets and remove the tag entries for sockets that have been closed.
146 // For now, set a large-enough buffer that we can close hundreds of sockets without getting
147 // ENOBUFS and leaking mCookieTagMap entries.
148 int rcvbuf = 512 * 1024;
149 auto ret = sys.setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf));
150 if (!ret.ok()) {
151 ALOGW("Failed to set SkDestroyListener buffer size to %d: %s", rcvbuf, ret.msg().c_str());
152 }
153
Chenbo Feng116d0552017-12-04 17:25:19 -0800154 sockaddr_nl addr = {
155 .nl_family = AF_NETLINK,
156 .nl_groups = 1 << (SKNLGRP_INET_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET_UDP_DESTROY - 1) |
157 1 << (SKNLGRP_INET6_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET6_UDP_DESTROY - 1)};
158 RETURN_IF_NOT_OK(sys.bind(sock, addr));
159
160 const sockaddr_nl kernel = {.nl_family = AF_NETLINK};
161 RETURN_IF_NOT_OK(sys.connect(sock, kernel));
162
163 std::unique_ptr<NetlinkListenerInterface> listener =
Chenbo Feng46296702018-08-23 12:20:22 -0700164 std::make_unique<NetlinkListener>(std::move(event), std::move(sock), "SkDestroyListen");
Chenbo Feng116d0552017-12-04 17:25:19 -0800165
166 return listener;
167}
168
Chenbo Feng82075e52019-04-12 19:21:47 -0700169TrafficController::TrafficController()
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800170 : mBpfEnabled(isBpfSupported()),
Chenbo Feng82075e52019-04-12 19:21:47 -0700171 mPerUidStatsEntriesLimit(PER_UID_STATS_ENTRIES_LIMIT),
172 mTotalUidStatsEntriesLimit(TOTAL_UID_STATS_ENTRIES_LIMIT) {}
173
174TrafficController::TrafficController(uint32_t perUidLimit, uint32_t totalLimit)
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800175 : mBpfEnabled(isBpfSupported()),
Chenbo Feng82075e52019-04-12 19:21:47 -0700176 mPerUidStatsEntriesLimit(perUidLimit),
177 mTotalUidStatsEntriesLimit(totalLimit) {}
Chenbo Feng89c12f12018-03-21 10:29:18 -0700178
Chenbo Feng89c12f12018-03-21 10:29:18 -0700179Status TrafficController::initMaps() {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700180 std::lock_guard guard(mMutex);
Maciej Żenczykowski565b6fb2020-01-27 01:58:40 -0800181
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700182 RETURN_IF_NOT_OK(mCookieTagMap.init(COOKIE_TAG_MAP_PATH));
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700183 RETURN_IF_NOT_OK(mUidCounterSetMap.init(UID_COUNTERSET_MAP_PATH));
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700184 RETURN_IF_NOT_OK(mAppUidStatsMap.init(APP_UID_STATS_MAP_PATH));
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700185 RETURN_IF_NOT_OK(mStatsMapA.init(STATS_MAP_A_PATH));
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700186 RETURN_IF_NOT_OK(mStatsMapB.init(STATS_MAP_B_PATH));
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700187 RETURN_IF_NOT_OK(mIfaceIndexNameMap.init(IFACE_INDEX_NAME_MAP_PATH));
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700188 RETURN_IF_NOT_OK(mIfaceStatsMap.init(IFACE_STATS_MAP_PATH));
Chenbo Feng95892f32018-06-07 14:52:02 -0700189
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700190 RETURN_IF_NOT_OK(mConfigurationMap.init(CONFIGURATION_MAP_PATH));
Chenbo Feng703798e2018-06-15 17:07:59 -0700191 RETURN_IF_NOT_OK(
Chenbo Fengf434e862018-06-27 14:08:39 -0700192 mConfigurationMap.writeValue(UID_RULES_CONFIGURATION_KEY, DEFAULT_CONFIG, BPF_ANY));
193 RETURN_IF_NOT_OK(mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, SELECT_MAP_A,
194 BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700195
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700196 RETURN_IF_NOT_OK(mUidOwnerMap.init(UID_OWNER_MAP_PATH));
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900197 RETURN_IF_NOT_OK(mUidOwnerMap.clear());
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700198 RETURN_IF_NOT_OK(mUidPermissionMap.init(UID_PERMISSION_MAP_PATH));
mtk13799ae0704e2019-03-28 15:07:14 +0800199
Chenbo Feng89c12f12018-03-21 10:29:18 -0700200 return netdutils::status::ok;
201}
202
Maciej Żenczykowski87017852020-01-17 19:22:11 -0800203static Status attachProgramToCgroup(const char* programPath, const unique_fd& cgroupFd,
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800204 bpf_attach_type type) {
Maciej Żenczykowski251b3ee2020-06-18 12:30:41 +0000205 unique_fd cgroupProg(retrieveProgram(programPath));
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800206 if (cgroupProg == -1) {
207 int ret = errno;
208 ALOGE("Failed to get program from %s: %s", programPath, strerror(ret));
209 return statusFromErrno(ret, "cgroup program get failed");
210 }
211 if (android::bpf::attachProgram(type, cgroupProg, cgroupFd)) {
212 int ret = errno;
213 ALOGE("Program from %s attach failed: %s", programPath, strerror(ret));
214 return statusFromErrno(ret, "program attach failed");
215 }
216 return netdutils::status::ok;
217}
218
219static Status initPrograms() {
Suren Baghdasaryane072a3c2019-01-16 14:36:07 -0800220 std::string cg2_path;
221
222 if (!CgroupGetControllerPath(CGROUPV2_CONTROLLER_NAME, &cg2_path)) {
223 int ret = errno;
224 ALOGE("Failed to find cgroup v2 root");
225 return statusFromErrno(ret, "Failed to find cgroup v2 root");
226 }
227
228 unique_fd cg_fd(open(cg2_path.c_str(), O_DIRECTORY | O_RDONLY | O_CLOEXEC));
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800229 if (cg_fd == -1) {
230 int ret = errno;
231 ALOGE("Failed to open the cgroup directory: %s", strerror(ret));
232 return statusFromErrno(ret, "Open the cgroup directory failed");
233 }
234 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_EGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_EGRESS));
235 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_INGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_INGRESS));
Chenbo Fenga51f4fa2019-01-15 15:03:32 -0800236
237 // For the devices that support cgroup socket filter, the socket filter
238 // should be loaded successfully by bpfloader. So we attach the filter to
239 // cgroup if the program is pinned properly.
240 // TODO: delete the if statement once all devices should support cgroup
241 // socket filter (ie. the minimum kernel version required is 4.14).
242 if (!access(CGROUP_SOCKET_PROG_PATH, F_OK)) {
243 RETURN_IF_NOT_OK(
244 attachProgramToCgroup(CGROUP_SOCKET_PROG_PATH, cg_fd, BPF_CGROUP_INET_SOCK_CREATE));
245 }
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800246 return netdutils::status::ok;
247}
248
Chenbo Feng89c12f12018-03-21 10:29:18 -0700249Status TrafficController::start() {
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800250 if (!mBpfEnabled) {
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800251 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700252 }
253
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900254 /* When netd restarts from a crash without total system reboot, the program
Chenbo Fengf2759682017-10-10 17:31:57 -0700255 * is still attached to the cgroup, detach it so the program can be freed
256 * and we can load and attach new program into the target cgroup.
257 *
258 * TODO: Scrape existing socket when run-time restart and clean up the map
259 * if the socket no longer exist
260 */
261
Chenbo Feng89c12f12018-03-21 10:29:18 -0700262 RETURN_IF_NOT_OK(initMaps());
Chenbo Feng7e974052018-02-28 22:57:21 -0800263
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800264 RETURN_IF_NOT_OK(initPrograms());
265
Chenbo Feng7e974052018-02-28 22:57:21 -0800266 // Fetch the list of currently-existing interfaces. At this point NetlinkHandler is
267 // already running, so it will call addInterface() when any new interface appears.
268 std::map<std::string, uint32_t> ifacePairs;
269 ASSIGN_OR_RETURN(ifacePairs, InterfaceController::getIfaceList());
270 for (const auto& ifacePair:ifacePairs) {
271 addInterface(ifacePair.first.c_str(), ifacePair.second);
272 }
273
Chenbo Feng116d0552017-12-04 17:25:19 -0800274 auto result = makeSkDestroyListener();
275 if (!isOk(result)) {
276 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
277 } else {
278 mSkDestroyListener = std::move(result.value());
279 }
280 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
281 const auto rxHandler = [this](const nlmsghdr&, const Slice msg) {
Chenbo Fengf01f5302019-05-07 12:28:13 -0700282 std::lock_guard guard(mMutex);
Chenbo Feng116d0552017-12-04 17:25:19 -0800283 inet_diag_msg diagmsg = {};
284 if (extract(msg, diagmsg) < sizeof(inet_diag_msg)) {
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900285 ALOGE("Unrecognized netlink message: %s", toString(msg).c_str());
Chenbo Feng116d0552017-12-04 17:25:19 -0800286 return;
287 }
288 uint64_t sock_cookie = static_cast<uint64_t>(diagmsg.id.idiag_cookie[0]) |
289 (static_cast<uint64_t>(diagmsg.id.idiag_cookie[1]) << 32);
290
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900291 Status s = mCookieTagMap.deleteValue(sock_cookie);
Chenbo Feng1d4c5db2018-10-18 15:50:46 -0700292 if (!isOk(s) && s.code() != ENOENT) {
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900293 ALOGE("Failed to delete cookie %" PRIx64 ": %s", sock_cookie, toString(s).c_str());
294 return;
295 }
Chenbo Feng116d0552017-12-04 17:25:19 -0800296 };
297 expectOk(mSkDestroyListener->subscribe(kSockDiagMsgType, rxHandler));
298
299 // In case multiple netlink message comes in as a stream, we need to handle the rxDone message
300 // properly.
301 const auto rxDoneHandler = [](const nlmsghdr&, const Slice msg) {
302 // Ignore NLMSG_DONE messages
303 inet_diag_msg diagmsg = {};
304 extract(msg, diagmsg);
305 };
306 expectOk(mSkDestroyListener->subscribe(kSockDiagDoneMsgType, rxDoneHandler));
307
Chenbo Feng05393d82018-01-09 15:18:43 -0800308 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700309}
310
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800311int TrafficController::tagSocket(int sockFd, uint32_t tag, uid_t uid, uid_t callingUid) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700312 std::lock_guard guard(mMutex);
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800313 if (uid != callingUid && !hasUpdateDeviceStatsPermission(callingUid)) {
314 return -EPERM;
315 }
316
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800317 if (!mBpfEnabled) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700318 if (legacy_tagSocket(sockFd, tag, uid)) return -errno;
319 return 0;
320 }
Chenbo Feng33cc1032017-10-23 15:16:37 -0700321
Chenbo Fengf2759682017-10-10 17:31:57 -0700322 uint64_t sock_cookie = getSocketCookie(sockFd);
Chenbo Fengef1cab32018-04-13 19:50:49 -0700323 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
Maciej Żenczykowski11ec78b2019-12-30 06:39:32 -0800324 UidTagValue newKey = {.uid = (uint32_t)uid, .tag = tag};
Chenbo Fengf2759682017-10-10 17:31:57 -0700325
Chenbo Fengb0495132019-04-10 12:54:41 -0700326 uint32_t totalEntryCount = 0;
Chenbo Feng82075e52019-04-12 19:21:47 -0700327 uint32_t perUidEntryCount = 0;
Chenbo Fengb0495132019-04-10 12:54:41 -0700328 // Now we go through the stats map and count how many entries are associated
329 // with target uid. If the uid entry hit the limit for each uid, we block
330 // the request to prevent the map from overflow. It is safe here to iterate
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700331 // over the map since when mMutex is hold, system server cannot toggle
Chenbo Fengb0495132019-04-10 12:54:41 -0700332 // the live stats map and clean it. So nobody can delete entries from the map.
Chenbo Feng82075e52019-04-12 19:21:47 -0700333 const auto countUidStatsEntries = [uid, &totalEntryCount, &perUidEntryCount](
Steven Morelanda3074542020-01-13 14:13:44 -0800334 const StatsKey& key,
335 const BpfMap<StatsKey, StatsValue>&) {
Chenbo Fengb0495132019-04-10 12:54:41 -0700336 if (key.uid == uid) {
Chenbo Feng82075e52019-04-12 19:21:47 -0700337 perUidEntryCount++;
Chenbo Fengb0495132019-04-10 12:54:41 -0700338 }
Chenbo Feng82075e52019-04-12 19:21:47 -0700339 totalEntryCount++;
Steven Morelanda3074542020-01-13 14:13:44 -0800340 return base::Result<void>();
Chenbo Fengb0495132019-04-10 12:54:41 -0700341 };
342 auto configuration = mConfigurationMap.readValue(CURRENT_STATS_MAP_CONFIGURATION_KEY);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900343 if (!configuration.ok()) {
Chenbo Fengb0495132019-04-10 12:54:41 -0700344 ALOGE("Failed to get current configuration: %s, fd: %d",
Steven Morelanda3074542020-01-13 14:13:44 -0800345 strerror(configuration.error().code()), mConfigurationMap.getMap().get());
346 return -configuration.error().code();
Chenbo Fengb0495132019-04-10 12:54:41 -0700347 }
Chenbo Feng36a40d12019-04-23 16:47:05 -0700348 if (configuration.value() != SELECT_MAP_A && configuration.value() != SELECT_MAP_B) {
Chenbo Fengb0495132019-04-10 12:54:41 -0700349 ALOGE("unknown configuration value: %d", configuration.value());
350 return -EINVAL;
351 }
Chenbo Feng36a40d12019-04-23 16:47:05 -0700352
353 BpfMap<StatsKey, StatsValue>& currentMap =
354 (configuration.value() == SELECT_MAP_A) ? mStatsMapA : mStatsMapB;
Steven Morelanda3074542020-01-13 14:13:44 -0800355 base::Result<void> res = currentMap.iterate(countUidStatsEntries);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900356 if (!res.ok()) {
Chenbo Feng36a40d12019-04-23 16:47:05 -0700357 ALOGE("Failed to count the stats entry in map %d: %s", currentMap.getMap().get(),
Steven Morelanda3074542020-01-13 14:13:44 -0800358 strerror(res.error().code()));
359 return -res.error().code();
Chenbo Feng36a40d12019-04-23 16:47:05 -0700360 }
361
Chenbo Feng82075e52019-04-12 19:21:47 -0700362 if (totalEntryCount > mTotalUidStatsEntriesLimit ||
363 perUidEntryCount > mPerUidStatsEntriesLimit) {
364 ALOGE("Too many stats entries in the map, total count: %u, uid(%u) count: %u, blocking tag"
365 " request to prevent map overflow",
366 totalEntryCount, uid, perUidEntryCount);
Chenbo Fengb0495132019-04-10 12:54:41 -0700367 return -EMFILE;
368 }
Chenbo Fengf2759682017-10-10 17:31:57 -0700369 // Update the tag information of a socket to the cookieUidMap. Use BPF_ANY
370 // flag so it will insert a new entry to the map if that value doesn't exist
371 // yet. And update the tag if there is already a tag stored. Since the eBPF
372 // program in kernel only read this map, and is protected by rcu read lock. It
373 // should be fine to cocurrently update the map while eBPF program is running.
Chenbo Feng36a40d12019-04-23 16:47:05 -0700374 res = mCookieTagMap.writeValue(sock_cookie, newKey, BPF_ANY);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900375 if (!res.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -0800376 ALOGE("Failed to tag the socket: %s, fd: %d", strerror(res.error().code()),
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700377 mCookieTagMap.getMap().get());
Steven Morelanda3074542020-01-13 14:13:44 -0800378 return -res.error().code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700379 }
Steven Morelanda3074542020-01-13 14:13:44 -0800380 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700381}
382
383int TrafficController::untagSocket(int sockFd) {
Chenbo Fengf01f5302019-05-07 12:28:13 -0700384 std::lock_guard guard(mMutex);
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800385 if (!mBpfEnabled) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700386 if (legacy_untagSocket(sockFd)) return -errno;
387 return 0;
388 }
Chenbo Fengf2759682017-10-10 17:31:57 -0700389 uint64_t sock_cookie = getSocketCookie(sockFd);
390
Chenbo Fengef1cab32018-04-13 19:50:49 -0700391 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
Steven Morelanda3074542020-01-13 14:13:44 -0800392 base::Result<void> res = mCookieTagMap.deleteValue(sock_cookie);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900393 if (!res.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -0800394 ALOGE("Failed to untag socket: %s\n", strerror(res.error().code()));
395 return -res.error().code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700396 }
Steven Morelanda3074542020-01-13 14:13:44 -0800397 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700398}
399
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800400int TrafficController::setCounterSet(int counterSetNum, uid_t uid, uid_t callingUid) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700401 if (counterSetNum < 0 || counterSetNum >= OVERFLOW_COUNTERSET) return -EINVAL;
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800402
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700403 std::lock_guard guard(mMutex);
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800404 if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
405
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800406 if (!mBpfEnabled) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700407 if (legacy_setCounterSet(counterSetNum, uid)) return -errno;
408 return 0;
409 }
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800410
411 // The default counter set for all uid is 0, so deleting the current counterset for that uid
412 // will automatically set it to 0.
Chenbo Fengf2759682017-10-10 17:31:57 -0700413 if (counterSetNum == 0) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700414 Status res = mUidCounterSetMap.deleteValue(uid);
415 if (isOk(res) || (!isOk(res) && res.code() == ENOENT)) {
Chenbo Fengf2759682017-10-10 17:31:57 -0700416 return 0;
417 } else {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700418 ALOGE("Failed to delete the counterSet: %s\n", strerror(res.code()));
419 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700420 }
421 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700422 uint8_t tmpCounterSetNum = (uint8_t)counterSetNum;
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800423 Status res = mUidCounterSetMap.writeValue(uid, tmpCounterSetNum, BPF_ANY);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700424 if (!isOk(res)) {
425 ALOGE("Failed to set the counterSet: %s, fd: %d", strerror(res.code()),
426 mUidCounterSetMap.getMap().get());
427 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700428 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700429 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700430}
431
Chenbo Fengf434e862018-06-27 14:08:39 -0700432// This method only get called by system_server when an app get uinstalled, it
433// is called inside removeUidsLocked() while holding mStatsLock. So it is safe
434// to iterate and modify the stats maps.
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800435int TrafficController::deleteTagData(uint32_t tag, uid_t uid, uid_t callingUid) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700436 std::lock_guard guard(mMutex);
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800437 if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
438
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800439 if (!mBpfEnabled) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700440 if (legacy_deleteTagData(tag, uid)) return -errno;
441 return 0;
442 }
Chenbo Feng33cc1032017-10-23 15:16:37 -0700443
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800444 // First we go through the cookieTagMap to delete the target uid tag combination. Or delete all
Chenbo Fengef1cab32018-04-13 19:50:49 -0700445 // the tags related to the uid if the tag is 0.
Maciej Żenczykowski11ec78b2019-12-30 06:39:32 -0800446 const auto deleteMatchedCookieEntries = [uid, tag](const uint64_t& key,
447 const UidTagValue& value,
448 BpfMap<uint64_t, UidTagValue>& map) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700449 if (value.uid == uid && (value.tag == tag || tag == 0)) {
Steven Morelanda3074542020-01-13 14:13:44 -0800450 auto res = map.deleteValue(key);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900451 if (res.ok() || (res.error().code() == ENOENT)) {
Steven Morelanda3074542020-01-13 14:13:44 -0800452 return base::Result<void>();
Chenbo Fengf2759682017-10-10 17:31:57 -0700453 }
Steven Morelanda3074542020-01-13 14:13:44 -0800454 ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s\n", key,
455 strerror(res.error().code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700456 }
Chenbo Fengef1cab32018-04-13 19:50:49 -0700457 // Move forward to next cookie in the map.
Steven Morelanda3074542020-01-13 14:13:44 -0800458 return base::Result<void>();
Chenbo Fengef1cab32018-04-13 19:50:49 -0700459 };
Steven Morelanda3074542020-01-13 14:13:44 -0800460 mCookieTagMap.iterateWithValue(deleteMatchedCookieEntries);
Chenbo Fengf2759682017-10-10 17:31:57 -0700461 // Now we go through the Tag stats map and delete the data entry with correct uid and tag
Chenbo Fengef1cab32018-04-13 19:50:49 -0700462 // combination. Or all tag stats under that uid if the target tag is 0.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700463 const auto deleteMatchedUidTagEntries = [uid, tag](const StatsKey& key,
464 BpfMap<StatsKey, StatsValue>& map) {
465 if (key.uid == uid && (key.tag == tag || tag == 0)) {
Steven Morelanda3074542020-01-13 14:13:44 -0800466 auto res = map.deleteValue(key);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900467 if (res.ok() || (res.error().code() == ENOENT)) {
Chenbo Fengef1cab32018-04-13 19:50:49 -0700468 //Entry is deleted, use the current key to get a new nextKey;
Steven Morelanda3074542020-01-13 14:13:44 -0800469 return base::Result<void>();
Chenbo Fengf2759682017-10-10 17:31:57 -0700470 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700471 ALOGE("Failed to delete data(uid=%u, tag=%u): %s\n", key.uid, key.tag,
Steven Morelanda3074542020-01-13 14:13:44 -0800472 strerror(res.error().code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700473 }
Steven Morelanda3074542020-01-13 14:13:44 -0800474 return base::Result<void>();
Chenbo Fengef1cab32018-04-13 19:50:49 -0700475 };
Steven Morelanda3074542020-01-13 14:13:44 -0800476 mStatsMapB.iterate(deleteMatchedUidTagEntries);
477 mStatsMapA.iterate(deleteMatchedUidTagEntries);
Chenbo Fengf2759682017-10-10 17:31:57 -0700478 // If the tag is not zero, we already deleted all the data entry required. If tag is 0, we also
Chenbo Fenged37fea2017-12-13 19:35:01 -0800479 // need to delete the stats stored in uidStatsMap and counterSet map.
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800480 if (tag != 0) return 0;
481
Steven Morelanda3074542020-01-13 14:13:44 -0800482 auto res = mUidCounterSetMap.deleteValue(uid);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900483 if (!res.ok() && res.error().code() != ENOENT) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700484 ALOGE("Failed to delete counterSet data(uid=%u, tag=%u): %s\n", uid, tag,
Steven Morelanda3074542020-01-13 14:13:44 -0800485 strerror(res.error().code()));
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800486 }
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700487
Steven Morelanda3074542020-01-13 14:13:44 -0800488 auto deleteAppUidStatsEntry = [uid](const uint32_t& key,
489 BpfMap<uint32_t, StatsValue>& map) -> base::Result<void> {
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700490 if (key == uid) {
Steven Morelanda3074542020-01-13 14:13:44 -0800491 auto res = map.deleteValue(key);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900492 if (res.ok() || (res.error().code() == ENOENT)) {
Steven Morelanda3074542020-01-13 14:13:44 -0800493 return {};
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700494 }
Steven Morelanda3074542020-01-13 14:13:44 -0800495 ALOGE("Failed to delete data(uid=%u): %s", key, strerror(res.error().code()));
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700496 }
Steven Morelanda3074542020-01-13 14:13:44 -0800497 return {};
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700498 };
Steven Morelanda3074542020-01-13 14:13:44 -0800499 mAppUidStatsMap.iterate(deleteAppUidStatsEntry);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700500 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700501}
502
Chenbo Feng7e974052018-02-28 22:57:21 -0800503int TrafficController::addInterface(const char* name, uint32_t ifaceIndex) {
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800504 if (!mBpfEnabled) return 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800505
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700506 IfaceValue iface;
Chenbo Feng7e974052018-02-28 22:57:21 -0800507 if (ifaceIndex == 0) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700508 ALOGE("Unknown interface %s(%d)", name, ifaceIndex);
Chenbo Feng7e974052018-02-28 22:57:21 -0800509 return -1;
510 }
511
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700512 strlcpy(iface.name, name, sizeof(IfaceValue));
513 Status res = mIfaceIndexNameMap.writeValue(ifaceIndex, iface, BPF_ANY);
514 if (!isOk(res)) {
515 ALOGE("Failed to add iface %s(%d): %s", name, ifaceIndex, strerror(res.code()));
516 return -res.code();
Chenbo Feng7e974052018-02-28 22:57:21 -0800517 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700518 return 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800519}
520
Chenbo Feng703798e2018-06-15 17:07:59 -0700521Status TrafficController::updateOwnerMapEntry(UidOwnerMatchType match, uid_t uid, FirewallRule rule,
522 FirewallType type) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700523 std::lock_guard guard(mMutex);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700524 if ((rule == ALLOW && type == WHITELIST) || (rule == DENY && type == BLACKLIST)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100525 RETURN_IF_NOT_OK(addRule(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700526 } else if ((rule == ALLOW && type == BLACKLIST) || (rule == DENY && type == WHITELIST)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100527 RETURN_IF_NOT_OK(removeRule(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700528 } else {
529 //Cannot happen.
Rubin Xuec27ff22019-01-08 21:33:03 +0000530 return statusFromErrno(EINVAL, "");
Chenbo Feng89c12f12018-03-21 10:29:18 -0700531 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700532 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700533}
534
Chenbo Feng703798e2018-06-15 17:07:59 -0700535UidOwnerMatchType TrafficController::jumpOpToMatch(BandwidthController::IptJumpOp jumpHandling) {
Chenbo Feng95892f32018-06-07 14:52:02 -0700536 switch (jumpHandling) {
537 case BandwidthController::IptJumpReject:
Chenbo Feng703798e2018-06-15 17:07:59 -0700538 return PENALTY_BOX_MATCH;
Chenbo Feng95892f32018-06-07 14:52:02 -0700539 case BandwidthController::IptJumpReturn:
Chenbo Feng703798e2018-06-15 17:07:59 -0700540 return HAPPY_BOX_MATCH;
Chenbo Feng95892f32018-06-07 14:52:02 -0700541 case BandwidthController::IptJumpNoAdd:
542 return NO_MATCH;
543 }
544}
545
Rubin Xu5ca8e802019-04-05 11:50:32 +0100546Status TrafficController::removeRule(BpfMap<uint32_t, UidOwnerValue>& map, uint32_t uid,
547 UidOwnerMatchType match) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700548 auto oldMatch = map.readValue(uid);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900549 if (oldMatch.ok()) {
Nick Desaulniers6b357502019-10-11 09:26:44 -0700550 UidOwnerValue newMatch = {
551 .iif = (match == IIF_MATCH) ? 0 : oldMatch.value().iif,
552 .rule = static_cast<uint8_t>(oldMatch.value().rule & ~match),
553 };
Rubin Xuec27ff22019-01-08 21:33:03 +0000554 if (newMatch.rule == 0) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700555 RETURN_IF_NOT_OK(map.deleteValue(uid));
556 } else {
557 RETURN_IF_NOT_OK(map.writeValue(uid, newMatch, BPF_ANY));
558 }
559 } else {
560 return statusFromErrno(ENOENT, StringPrintf("uid: %u does not exist in map", uid));
561 }
562 return netdutils::status::ok;
563}
564
Rubin Xu5ca8e802019-04-05 11:50:32 +0100565Status TrafficController::addRule(BpfMap<uint32_t, UidOwnerValue>& map, uint32_t uid,
566 UidOwnerMatchType match, uint32_t iif) {
Rubin Xuec27ff22019-01-08 21:33:03 +0000567 // iif should be non-zero if and only if match == MATCH_IIF
568 if (match == IIF_MATCH && iif == 0) {
569 return statusFromErrno(EINVAL, "Interface match must have nonzero interface index");
570 } else if (match != IIF_MATCH && iif != 0) {
571 return statusFromErrno(EINVAL, "Non-interface match must have zero interface index");
572 }
Chenbo Feng703798e2018-06-15 17:07:59 -0700573 auto oldMatch = map.readValue(uid);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900574 if (oldMatch.ok()) {
Nick Desaulniers6b357502019-10-11 09:26:44 -0700575 UidOwnerValue newMatch = {
576 .iif = iif ? iif : oldMatch.value().iif,
577 .rule = static_cast<uint8_t>(oldMatch.value().rule | match),
578 };
Rubin Xuec27ff22019-01-08 21:33:03 +0000579 RETURN_IF_NOT_OK(map.writeValue(uid, newMatch, BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700580 } else {
Nick Desaulniers6b357502019-10-11 09:26:44 -0700581 UidOwnerValue newMatch = {
582 .iif = iif,
583 .rule = static_cast<uint8_t>(match),
584 };
Rubin Xuec27ff22019-01-08 21:33:03 +0000585 RETURN_IF_NOT_OK(map.writeValue(uid, newMatch, BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700586 }
587 return netdutils::status::ok;
588}
589
590Status TrafficController::updateUidOwnerMap(const std::vector<std::string>& appStrUids,
591 BandwidthController::IptJumpOp jumpHandling,
592 BandwidthController::IptOp op) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700593 std::lock_guard guard(mMutex);
Chenbo Feng703798e2018-06-15 17:07:59 -0700594 UidOwnerMatchType match = jumpOpToMatch(jumpHandling);
595 if (match == NO_MATCH) {
596 return statusFromErrno(
597 EINVAL, StringPrintf("invalid IptJumpOp: %d, command: %d", jumpHandling, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700598 }
599 for (const auto& appStrUid : appStrUids) {
600 char* endPtr;
601 long uid = strtol(appStrUid.c_str(), &endPtr, 10);
602 if ((errno == ERANGE && (uid == LONG_MAX || uid == LONG_MIN)) ||
603 (endPtr == appStrUid.c_str()) || (*endPtr != '\0')) {
604 return statusFromErrno(errno, "invalid uid string:" + appStrUid);
605 }
606
Chenbo Feng95892f32018-06-07 14:52:02 -0700607 if (op == BandwidthController::IptOpDelete) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100608 RETURN_IF_NOT_OK(removeRule(mUidOwnerMap, uid, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700609 } else if (op == BandwidthController::IptOpInsert) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100610 RETURN_IF_NOT_OK(addRule(mUidOwnerMap, uid, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700611 } else {
612 // Cannot happen.
Chenbo Feng703798e2018-06-15 17:07:59 -0700613 return statusFromErrno(EINVAL, StringPrintf("invalid IptOp: %d, %d", op, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700614 }
615 }
616 return netdutils::status::ok;
617}
618
Chenbo Feng89c12f12018-03-21 10:29:18 -0700619int TrafficController::changeUidOwnerRule(ChildChain chain, uid_t uid, FirewallRule rule,
620 FirewallType type) {
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800621 if (!mBpfEnabled) {
Chenbo Feng89c12f12018-03-21 10:29:18 -0700622 ALOGE("bpf is not set up, should use iptables rule");
623 return -ENOSYS;
624 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700625 Status res;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700626 switch (chain) {
627 case DOZABLE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700628 res = updateOwnerMapEntry(DOZABLE_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700629 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700630 case STANDBY:
Chenbo Feng703798e2018-06-15 17:07:59 -0700631 res = updateOwnerMapEntry(STANDBY_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700632 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700633 case POWERSAVE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700634 res = updateOwnerMapEntry(POWERSAVE_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700635 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700636 case NONE:
637 default:
638 return -EINVAL;
639 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700640 if (!isOk(res)) {
641 ALOGE("change uid(%u) rule of %d failed: %s, rule: %d, type: %d", uid, chain,
642 res.msg().c_str(), rule, type);
643 return -res.code();
644 }
645 return 0;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700646}
647
Rubin Xu5ca8e802019-04-05 11:50:32 +0100648Status TrafficController::replaceRulesInMap(const UidOwnerMatchType match,
649 const std::vector<int32_t>& uids) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700650 std::lock_guard guard(mMutex);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700651 std::set<int32_t> uidSet(uids.begin(), uids.end());
652 std::vector<uint32_t> uidsToDelete;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700653 auto getUidsToDelete = [&uidsToDelete, &uidSet](const uint32_t& key,
Rubin Xuec27ff22019-01-08 21:33:03 +0000654 const BpfMap<uint32_t, UidOwnerValue>&) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700655 if (uidSet.find((int32_t) key) == uidSet.end()) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700656 uidsToDelete.push_back(key);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700657 }
Steven Morelanda3074542020-01-13 14:13:44 -0800658 return base::Result<void>();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700659 };
Chenbo Feng703798e2018-06-15 17:07:59 -0700660 RETURN_IF_NOT_OK(mUidOwnerMap.iterate(getUidsToDelete));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700661
662 for(auto uid : uidsToDelete) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100663 RETURN_IF_NOT_OK(removeRule(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700664 }
665
666 for (auto uid : uids) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100667 RETURN_IF_NOT_OK(addRule(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700668 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700669 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700670}
671
Rubin Xuec27ff22019-01-08 21:33:03 +0000672Status TrafficController::addUidInterfaceRules(const int iif,
673 const std::vector<int32_t>& uidsToAdd) {
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800674 if (!mBpfEnabled) {
Rubin Xuec27ff22019-01-08 21:33:03 +0000675 ALOGW("UID ingress interface filtering not possible without BPF owner match");
676 return statusFromErrno(EOPNOTSUPP, "eBPF not supported");
677 }
678 if (!iif) {
679 return statusFromErrno(EINVAL, "Interface rule must specify interface");
680 }
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700681 std::lock_guard guard(mMutex);
Rubin Xuec27ff22019-01-08 21:33:03 +0000682
683 for (auto uid : uidsToAdd) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100684 netdutils::Status result = addRule(mUidOwnerMap, uid, IIF_MATCH, iif);
Rubin Xuec27ff22019-01-08 21:33:03 +0000685 if (!isOk(result)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100686 ALOGW("addRule failed(%d): uid=%d iif=%d", result.code(), uid, iif);
Rubin Xuec27ff22019-01-08 21:33:03 +0000687 }
688 }
689 return netdutils::status::ok;
690}
691
692Status TrafficController::removeUidInterfaceRules(const std::vector<int32_t>& uidsToDelete) {
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800693 if (!mBpfEnabled) {
Rubin Xuec27ff22019-01-08 21:33:03 +0000694 ALOGW("UID ingress interface filtering not possible without BPF owner match");
695 return statusFromErrno(EOPNOTSUPP, "eBPF not supported");
696 }
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700697 std::lock_guard guard(mMutex);
Rubin Xuec27ff22019-01-08 21:33:03 +0000698
699 for (auto uid : uidsToDelete) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100700 netdutils::Status result = removeRule(mUidOwnerMap, uid, IIF_MATCH);
Rubin Xuec27ff22019-01-08 21:33:03 +0000701 if (!isOk(result)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100702 ALOGW("removeRule failed(%d): uid=%d", result.code(), uid);
Rubin Xuec27ff22019-01-08 21:33:03 +0000703 }
704 }
705 return netdutils::status::ok;
706}
707
Maciej Żenczykowskia8036702020-05-01 01:30:12 +0000708int TrafficController::replaceUidOwnerMap(const std::string& name, bool isWhitelist __unused,
Chenbo Feng89c12f12018-03-21 10:29:18 -0700709 const std::vector<int32_t>& uids) {
Maciej Żenczykowskia8036702020-05-01 01:30:12 +0000710 // FirewallRule rule = isWhitelist ? ALLOW : DENY;
711 // FirewallType type = isWhitelist ? WHITELIST : BLACKLIST;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700712 Status res;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700713 if (!name.compare(FirewallController::LOCAL_DOZABLE)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100714 res = replaceRulesInMap(DOZABLE_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700715 } else if (!name.compare(FirewallController::LOCAL_STANDBY)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100716 res = replaceRulesInMap(STANDBY_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700717 } else if (!name.compare(FirewallController::LOCAL_POWERSAVE)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100718 res = replaceRulesInMap(POWERSAVE_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700719 } else {
720 ALOGE("unknown chain name: %s", name.c_str());
721 return -EINVAL;
722 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700723 if (!isOk(res)) {
724 ALOGE("Failed to clean up chain: %s: %s", name.c_str(), res.msg().c_str());
725 return -res.code();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700726 }
727 return 0;
728}
729
730int TrafficController::toggleUidOwnerMap(ChildChain chain, bool enable) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700731 std::lock_guard guard(mMutex);
Chenbo Fengf434e862018-06-27 14:08:39 -0700732 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Chenbo Feng703798e2018-06-15 17:07:59 -0700733 auto oldConfiguration = mConfigurationMap.readValue(key);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900734 if (!oldConfiguration.ok()) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700735 ALOGE("Cannot read the old configuration from map: %s",
Steven Morelanda3074542020-01-13 14:13:44 -0800736 oldConfiguration.error().message().c_str());
737 return -oldConfiguration.error().code();
Chenbo Feng703798e2018-06-15 17:07:59 -0700738 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700739 Status res;
Chenbo Feng703798e2018-06-15 17:07:59 -0700740 BpfConfig newConfiguration;
741 uint8_t match;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700742 switch (chain) {
743 case DOZABLE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700744 match = DOZABLE_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700745 break;
746 case STANDBY:
Chenbo Feng703798e2018-06-15 17:07:59 -0700747 match = STANDBY_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700748 break;
749 case POWERSAVE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700750 match = POWERSAVE_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700751 break;
752 default:
753 return -EINVAL;
754 }
Chenbo Feng703798e2018-06-15 17:07:59 -0700755 newConfiguration =
756 enable ? (oldConfiguration.value() | match) : (oldConfiguration.value() & (~match));
757 res = mConfigurationMap.writeValue(key, newConfiguration, BPF_EXIST);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700758 if (!isOk(res)) {
759 ALOGE("Failed to toggleUidOwnerMap(%d): %s", chain, res.msg().c_str());
Chenbo Feng89c12f12018-03-21 10:29:18 -0700760 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700761 return -res.code();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700762}
763
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800764bool TrafficController::getBpfEnabled() {
765 return mBpfEnabled;
Chenbo Feng07d43fe2017-12-21 14:38:51 -0800766}
767
Chenbo Feng873ae142019-04-10 12:26:06 -0700768Status TrafficController::swapActiveStatsMap() {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700769 std::lock_guard guard(mMutex);
Chenbo Feng873ae142019-04-10 12:26:06 -0700770
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800771 if (!mBpfEnabled) {
Chenbo Feng873ae142019-04-10 12:26:06 -0700772 return statusFromErrno(EOPNOTSUPP, "This device doesn't have eBPF support");
773 }
774
775 uint32_t key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
776 auto oldConfiguration = mConfigurationMap.readValue(key);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900777 if (!oldConfiguration.ok()) {
Chenbo Feng873ae142019-04-10 12:26:06 -0700778 ALOGE("Cannot read the old configuration from map: %s",
Steven Morelanda3074542020-01-13 14:13:44 -0800779 oldConfiguration.error().message().c_str());
780 return Status(oldConfiguration.error().code(), oldConfiguration.error().message());
Chenbo Feng873ae142019-04-10 12:26:06 -0700781 }
782
783 // Write to the configuration map to inform the kernel eBPF program to switch
784 // from using one map to the other. Use flag BPF_EXIST here since the map should
785 // be already populated in initMaps.
786 uint8_t newConfigure = (oldConfiguration.value() == SELECT_MAP_A) ? SELECT_MAP_B : SELECT_MAP_A;
Steven Morelanda3074542020-01-13 14:13:44 -0800787 auto res = mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, newConfigure,
788 BPF_EXIST);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900789 if (!res.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -0800790 ALOGE("Failed to toggle the stats map: %s", strerror(res.error().code()));
Chenbo Feng873ae142019-04-10 12:26:06 -0700791 return res;
792 }
793 // After changing the config, we need to make sure all the current running
794 // eBPF programs are finished and all the CPUs are aware of this config change
795 // before we modify the old map. So we do a special hack here to wait for
796 // the kernel to do a synchronize_rcu(). Once the kernel called
797 // synchronize_rcu(), the config we just updated will be available to all cores
798 // and the next eBPF programs triggered inside the kernel will use the new
799 // map configuration. So once this function returns we can safely modify the
800 // old stats map without concerning about race between the kernel and
801 // userspace.
802 int ret = synchronizeKernelRCU();
803 if (ret) {
804 ALOGE("map swap synchronize_rcu() ended with failure: %s", strerror(-ret));
805 return statusFromErrno(-ret, "map swap synchronize_rcu() failed");
806 }
807 return netdutils::status::ok;
808}
809
Chenbo Feng48eaed32018-12-26 17:40:21 -0800810void TrafficController::setPermissionForUids(int permission, const std::vector<uid_t>& uids) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700811 std::lock_guard guard(mMutex);
Chenbo Fengbf660aa2019-02-26 16:12:27 -0800812 if (permission == INetd::PERMISSION_UNINSTALLED) {
813 for (uid_t uid : uids) {
814 // Clean up all permission information for the related uid if all the
815 // packages related to it are uninstalled.
816 mPrivilegedUser.erase(uid);
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800817 if (mBpfEnabled) {
Chenbo Feng97c88db2019-04-24 12:19:16 -0700818 Status ret = mUidPermissionMap.deleteValue(uid);
Maciej Żenczykowski928ea232019-08-20 17:28:05 -0700819 if (!isOk(ret) && ret.code() != ENOENT) {
Chenbo Feng97c88db2019-04-24 12:19:16 -0700820 ALOGE("Failed to clean up the permission for %u: %s", uid,
821 strerror(ret.code()));
822 }
823 }
Chenbo Fengbf660aa2019-02-26 16:12:27 -0800824 }
825 return;
826 }
827
Chenbo Feng48eaed32018-12-26 17:40:21 -0800828 bool privileged = (permission & INetd::PERMISSION_UPDATE_DEVICE_STATS);
829
830 for (uid_t uid : uids) {
Chenbo Feng97c88db2019-04-24 12:19:16 -0700831 if (privileged) {
832 mPrivilegedUser.insert(uid);
833 } else {
834 mPrivilegedUser.erase(uid);
835 }
836
837 // Skip the bpf map operation if not supported.
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800838 if (!mBpfEnabled) {
Chenbo Feng97c88db2019-04-24 12:19:16 -0700839 continue;
840 }
Chenbo Feng527908a2019-04-02 20:14:11 -0700841 // The map stores all the permissions that the UID has, except if the only permission
842 // the UID has is the INTERNET permission, then the UID should not appear in the map.
843 if (permission != INetd::PERMISSION_INTERNET) {
Chenbo Fengbf660aa2019-02-26 16:12:27 -0800844 Status ret = mUidPermissionMap.writeValue(uid, permission, BPF_ANY);
Chenbo Feng48eaed32018-12-26 17:40:21 -0800845 if (!isOk(ret)) {
Chenbo Feng527908a2019-04-02 20:14:11 -0700846 ALOGE("Failed to set permission: %s of uid(%u) to permission map: %s",
847 UidPermissionTypeToString(permission).c_str(), uid, strerror(ret.code()));
Chenbo Feng48eaed32018-12-26 17:40:21 -0800848 }
849 } else {
850 Status ret = mUidPermissionMap.deleteValue(uid);
851 if (!isOk(ret) && ret.code() != ENOENT) {
Chenbo Feng527908a2019-04-02 20:14:11 -0700852 ALOGE("Failed to remove uid %u from permission map: %s", uid, strerror(ret.code()));
Chenbo Feng48eaed32018-12-26 17:40:21 -0800853 }
854 }
Chenbo Feng48eaed32018-12-26 17:40:21 -0800855 }
856}
857
Chenbo Fengef297172018-03-26 10:53:33 -0700858std::string getProgramStatus(const char *path) {
859 int ret = access(path, R_OK);
860 if (ret == 0) {
861 return StringPrintf("OK");
862 }
863 if (ret != 0 && errno == ENOENT) {
864 return StringPrintf("program is missing at: %s", path);
865 }
866 return StringPrintf("check Program %s error: %s", path, strerror(errno));
867}
868
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700869std::string getMapStatus(const base::unique_fd& map_fd, const char* path) {
Chenbo Fengef297172018-03-26 10:53:33 -0700870 if (map_fd.get() < 0) {
871 return StringPrintf("map fd lost");
872 }
873 if (access(path, F_OK) != 0) {
874 return StringPrintf("map not pinned to location: %s", path);
875 }
876 return StringPrintf("OK");
877}
878
Bernie Innocentia5161a02019-01-30 22:40:53 +0900879// NOLINTNEXTLINE(google-runtime-references): grandfathered pass by non-const reference
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900880void dumpBpfMap(const std::string& mapName, DumpWriter& dw, const std::string& header) {
Chenbo Fengef297172018-03-26 10:53:33 -0700881 dw.blankline();
882 dw.println("%s:", mapName.c_str());
Erik Klineb31fd692018-06-06 20:50:11 +0900883 if (!header.empty()) {
884 dw.println(header);
Chenbo Fengef297172018-03-26 10:53:33 -0700885 }
886}
887
888const String16 TrafficController::DUMP_KEYWORD = String16("trafficcontroller");
889
890void TrafficController::dump(DumpWriter& dw, bool verbose) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700891 std::lock_guard guard(mMutex);
Erik Klineb31fd692018-06-06 20:50:11 +0900892 ScopedIndent indentTop(dw);
Chenbo Fengef297172018-03-26 10:53:33 -0700893 dw.println("TrafficController");
894
Erik Klineb31fd692018-06-06 20:50:11 +0900895 ScopedIndent indentPreBpfModule(dw);
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800896 dw.println("BPF module status: %s", mBpfEnabled ? "enabled" : "disabled");
897 dw.println("BPF support level: %s", BpfLevelToString(getBpfSupportLevel()).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700898
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800899 if (!mBpfEnabled) {
Chenbo Fengef297172018-03-26 10:53:33 -0700900 return;
Erik Klineb31fd692018-06-06 20:50:11 +0900901 }
Chenbo Fengef297172018-03-26 10:53:33 -0700902
903 dw.blankline();
904 dw.println("mCookieTagMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700905 getMapStatus(mCookieTagMap.getMap(), COOKIE_TAG_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700906 dw.println("mUidCounterSetMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700907 getMapStatus(mUidCounterSetMap.getMap(), UID_COUNTERSET_MAP_PATH).c_str());
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700908 dw.println("mAppUidStatsMap status: %s",
909 getMapStatus(mAppUidStatsMap.getMap(), APP_UID_STATS_MAP_PATH).c_str());
Chenbo Fengf434e862018-06-27 14:08:39 -0700910 dw.println("mStatsMapA status: %s",
911 getMapStatus(mStatsMapA.getMap(), STATS_MAP_A_PATH).c_str());
912 dw.println("mStatsMapB status: %s",
913 getMapStatus(mStatsMapB.getMap(), STATS_MAP_B_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700914 dw.println("mIfaceIndexNameMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700915 getMapStatus(mIfaceIndexNameMap.getMap(), IFACE_INDEX_NAME_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700916 dw.println("mIfaceStatsMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700917 getMapStatus(mIfaceStatsMap.getMap(), IFACE_STATS_MAP_PATH).c_str());
Chenbo Feng703798e2018-06-15 17:07:59 -0700918 dw.println("mConfigurationMap status: %s",
919 getMapStatus(mConfigurationMap.getMap(), CONFIGURATION_MAP_PATH).c_str());
920 dw.println("mUidOwnerMap status: %s",
921 getMapStatus(mUidOwnerMap.getMap(), UID_OWNER_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700922
923 dw.blankline();
924 dw.println("Cgroup ingress program status: %s",
925 getProgramStatus(BPF_INGRESS_PROG_PATH).c_str());
926 dw.println("Cgroup egress program status: %s", getProgramStatus(BPF_EGRESS_PROG_PATH).c_str());
927 dw.println("xt_bpf ingress program status: %s",
928 getProgramStatus(XT_BPF_INGRESS_PROG_PATH).c_str());
929 dw.println("xt_bpf egress program status: %s",
930 getProgramStatus(XT_BPF_EGRESS_PROG_PATH).c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700931 dw.println("xt_bpf bandwidth whitelist program status: %s",
932 getProgramStatus(XT_BPF_WHITELIST_PROG_PATH).c_str());
933 dw.println("xt_bpf bandwidth blacklist program status: %s",
934 getProgramStatus(XT_BPF_BLACKLIST_PROG_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700935
Erik Klineb31fd692018-06-06 20:50:11 +0900936 if (!verbose) {
937 return;
938 }
Chenbo Fengef297172018-03-26 10:53:33 -0700939
940 dw.blankline();
941 dw.println("BPF map content:");
942
Erik Klineb31fd692018-06-06 20:50:11 +0900943 ScopedIndent indentForMapContent(dw);
Chenbo Fengef297172018-03-26 10:53:33 -0700944
945 // Print CookieTagMap content.
946 dumpBpfMap("mCookieTagMap", dw, "");
Maciej Żenczykowski11ec78b2019-12-30 06:39:32 -0800947 const auto printCookieTagInfo = [&dw](const uint64_t& key, const UidTagValue& value,
948 const BpfMap<uint64_t, UidTagValue>&) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700949 dw.println("cookie=%" PRIu64 " tag=0x%x uid=%u", key, value.tag, value.uid);
Steven Morelanda3074542020-01-13 14:13:44 -0800950 return base::Result<void>();
Chenbo Fengef297172018-03-26 10:53:33 -0700951 };
Steven Morelanda3074542020-01-13 14:13:44 -0800952 base::Result<void> res = mCookieTagMap.iterateWithValue(printCookieTagInfo);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900953 if (!res.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -0800954 dw.println("mCookieTagMap print end with error: %s", res.error().message().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700955 }
956
957 // Print UidCounterSetMap Content
958 dumpBpfMap("mUidCounterSetMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700959 const auto printUidInfo = [&dw](const uint32_t& key, const uint8_t& value,
960 const BpfMap<uint32_t, uint8_t>&) {
961 dw.println("%u %u", key, value);
Steven Morelanda3074542020-01-13 14:13:44 -0800962 return base::Result<void>();
Chenbo Fengef297172018-03-26 10:53:33 -0700963 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700964 res = mUidCounterSetMap.iterateWithValue(printUidInfo);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900965 if (!res.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -0800966 dw.println("mUidCounterSetMap print end with error: %s", res.error().message().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700967 }
968
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700969 // Print AppUidStatsMap content
970 std::string appUidStatsHeader = StringPrintf("uid rxBytes rxPackets txBytes txPackets");
971 dumpBpfMap("mAppUidStatsMap:", dw, appUidStatsHeader);
972 auto printAppUidStatsInfo = [&dw](const uint32_t& key, const StatsValue& value,
973 const BpfMap<uint32_t, StatsValue>&) {
974 dw.println("%u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, value.rxBytes,
975 value.rxPackets, value.txBytes, value.txPackets);
Steven Morelanda3074542020-01-13 14:13:44 -0800976 return base::Result<void>();
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700977 };
978 res = mAppUidStatsMap.iterateWithValue(printAppUidStatsInfo);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900979 if (!res.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -0800980 dw.println("mAppUidStatsMap print end with error: %s", res.error().message().c_str());
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700981 }
982
Chenbo Fengef297172018-03-26 10:53:33 -0700983 // Print uidStatsMap content
984 std::string statsHeader = StringPrintf("ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes"
985 " rxPackets txBytes txPackets");
Chenbo Fengf434e862018-06-27 14:08:39 -0700986 dumpBpfMap("mStatsMapA", dw, statsHeader);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700987 const auto printStatsInfo = [&dw, this](const StatsKey& key, const StatsValue& value,
988 const BpfMap<StatsKey, StatsValue>&) {
989 uint32_t ifIndex = key.ifaceIndex;
990 auto ifname = mIfaceIndexNameMap.readValue(ifIndex);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900991 if (!ifname.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -0800992 ifname = IfaceValue{"unknown"};
Chenbo Fengef297172018-03-26 10:53:33 -0700993 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700994 dw.println("%u %s 0x%x %u %u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, ifIndex,
995 ifname.value().name, key.tag, key.uid, key.counterSet, value.rxBytes,
996 value.rxPackets, value.txBytes, value.txPackets);
Steven Morelanda3074542020-01-13 14:13:44 -0800997 return base::Result<void>();
Chenbo Fengef297172018-03-26 10:53:33 -0700998 };
Chenbo Fengf434e862018-06-27 14:08:39 -0700999 res = mStatsMapA.iterateWithValue(printStatsInfo);
Bernie Innocenti615fd742020-02-06 03:55:09 +09001000 if (!res.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -08001001 dw.println("mStatsMapA print end with error: %s", res.error().message().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001002 }
1003
1004 // Print TagStatsMap content.
Chenbo Fengf434e862018-06-27 14:08:39 -07001005 dumpBpfMap("mStatsMapB", dw, statsHeader);
1006 res = mStatsMapB.iterateWithValue(printStatsInfo);
Bernie Innocenti615fd742020-02-06 03:55:09 +09001007 if (!res.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -08001008 dw.println("mStatsMapB print end with error: %s", res.error().message().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001009 }
1010
1011 // Print ifaceIndexToNameMap content.
1012 dumpBpfMap("mIfaceIndexNameMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001013 const auto printIfaceNameInfo = [&dw](const uint32_t& key, const IfaceValue& value,
1014 const BpfMap<uint32_t, IfaceValue>&) {
1015 const char* ifname = value.name;
1016 dw.println("ifaceIndex=%u ifaceName=%s", key, ifname);
Steven Morelanda3074542020-01-13 14:13:44 -08001017 return base::Result<void>();
Chenbo Fengef297172018-03-26 10:53:33 -07001018 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001019 res = mIfaceIndexNameMap.iterateWithValue(printIfaceNameInfo);
Bernie Innocenti615fd742020-02-06 03:55:09 +09001020 if (!res.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -08001021 dw.println("mIfaceIndexNameMap print end with error: %s", res.error().message().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001022 }
1023
1024 // Print ifaceStatsMap content
1025 std::string ifaceStatsHeader = StringPrintf("ifaceIndex ifaceName rxBytes rxPackets txBytes"
1026 " txPackets");
1027 dumpBpfMap("mIfaceStatsMap:", dw, ifaceStatsHeader);
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001028 const auto printIfaceStatsInfo = [&dw, this](const uint32_t& key, const StatsValue& value,
1029 const BpfMap<uint32_t, StatsValue>&) {
1030 auto ifname = mIfaceIndexNameMap.readValue(key);
Bernie Innocenti615fd742020-02-06 03:55:09 +09001031 if (!ifname.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -08001032 ifname = IfaceValue{"unknown"};
Chenbo Fengef297172018-03-26 10:53:33 -07001033 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001034 dw.println("%u %s %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, ifname.value().name,
1035 value.rxBytes, value.rxPackets, value.txBytes, value.txPackets);
Steven Morelanda3074542020-01-13 14:13:44 -08001036 return base::Result<void>();
Chenbo Fengef297172018-03-26 10:53:33 -07001037 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001038 res = mIfaceStatsMap.iterateWithValue(printIfaceStatsInfo);
Bernie Innocenti615fd742020-02-06 03:55:09 +09001039 if (!res.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -08001040 dw.println("mIfaceStatsMap print end with error: %s", res.error().message().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001041 }
1042
Chenbo Feng703798e2018-06-15 17:07:59 -07001043 dw.blankline();
Chenbo Fengef297172018-03-26 10:53:33 -07001044
Chenbo Fengf434e862018-06-27 14:08:39 -07001045 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Chenbo Feng703798e2018-06-15 17:07:59 -07001046 auto configuration = mConfigurationMap.readValue(key);
Bernie Innocenti615fd742020-02-06 03:55:09 +09001047 if (configuration.ok()) {
Lorenzo Colittic2677362019-06-26 20:01:35 +09001048 dw.println("current ownerMatch configuration: %d%s", configuration.value(),
1049 uidMatchTypeToString(configuration.value()).c_str());
Chenbo Feng703798e2018-06-15 17:07:59 -07001050 } else {
Chenbo Fengf434e862018-06-27 14:08:39 -07001051 dw.println("mConfigurationMap read ownerMatch configure failed with error: %s",
Steven Morelanda3074542020-01-13 14:13:44 -08001052 configuration.error().message().c_str());
Chenbo Fengf434e862018-06-27 14:08:39 -07001053 }
Lorenzo Colittic2677362019-06-26 20:01:35 +09001054
Chenbo Fengf434e862018-06-27 14:08:39 -07001055 key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
1056 configuration = mConfigurationMap.readValue(key);
Bernie Innocenti615fd742020-02-06 03:55:09 +09001057 if (configuration.ok()) {
Lorenzo Colittic2677362019-06-26 20:01:35 +09001058 const char* statsMapDescription = "???";
1059 switch (configuration.value()) {
1060 case SELECT_MAP_A:
1061 statsMapDescription = "SELECT_MAP_A";
1062 break;
1063 case SELECT_MAP_B:
1064 statsMapDescription = "SELECT_MAP_B";
1065 break;
1066 // No default clause, so if we ever add a third map, this code will fail to build.
1067 }
1068 dw.println("current statsMap configuration: %d %s", configuration.value(),
1069 statsMapDescription);
Chenbo Fengf434e862018-06-27 14:08:39 -07001070 } else {
1071 dw.println("mConfigurationMap read stats map configure failed with error: %s",
Steven Morelanda3074542020-01-13 14:13:44 -08001072 configuration.error().message().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001073 }
Chenbo Feng703798e2018-06-15 17:07:59 -07001074 dumpBpfMap("mUidOwnerMap", dw, "");
Rubin Xuec27ff22019-01-08 21:33:03 +00001075 const auto printUidMatchInfo = [&dw, this](const uint32_t& key, const UidOwnerValue& value,
1076 const BpfMap<uint32_t, UidOwnerValue>&) {
1077 if (value.rule & IIF_MATCH) {
1078 auto ifname = mIfaceIndexNameMap.readValue(value.iif);
Bernie Innocenti615fd742020-02-06 03:55:09 +09001079 if (ifname.ok()) {
Rubin Xuec27ff22019-01-08 21:33:03 +00001080 dw.println("%u %s %s", key, uidMatchTypeToString(value.rule).c_str(),
1081 ifname.value().name);
1082 } else {
1083 dw.println("%u %s %u", key, uidMatchTypeToString(value.rule).c_str(), value.iif);
1084 }
1085 } else {
1086 dw.println("%u %s", key, uidMatchTypeToString(value.rule).c_str());
1087 }
Steven Morelanda3074542020-01-13 14:13:44 -08001088 return base::Result<void>();
Chenbo Feng703798e2018-06-15 17:07:59 -07001089 };
1090 res = mUidOwnerMap.iterateWithValue(printUidMatchInfo);
Bernie Innocenti615fd742020-02-06 03:55:09 +09001091 if (!res.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -08001092 dw.println("mUidOwnerMap print end with error: %s", res.error().message().c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -07001093 }
Chenbo Feng48eaed32018-12-26 17:40:21 -08001094 dumpBpfMap("mUidPermissionMap", dw, "");
Yi Kong3d82f382019-10-01 21:52:14 -07001095 const auto printUidPermissionInfo = [&dw](const uint32_t& key, const int& value,
Chenbo Feng48eaed32018-12-26 17:40:21 -08001096 const BpfMap<uint32_t, uint8_t>&) {
1097 dw.println("%u %s", key, UidPermissionTypeToString(value).c_str());
Steven Morelanda3074542020-01-13 14:13:44 -08001098 return base::Result<void>();
Chenbo Feng48eaed32018-12-26 17:40:21 -08001099 };
1100 res = mUidPermissionMap.iterateWithValue(printUidPermissionInfo);
Bernie Innocenti615fd742020-02-06 03:55:09 +09001101 if (!res.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -08001102 dw.println("mUidPermissionMap print end with error: %s", res.error().message().c_str());
Chenbo Feng48eaed32018-12-26 17:40:21 -08001103 }
1104
1105 dumpBpfMap("mPrivilegedUser", dw, "");
1106 for (uid_t uid : mPrivilegedUser) {
1107 dw.println("%u ALLOW_UPDATE_DEVICE_STATS", (uint32_t)uid);
1108 }
Chenbo Fengef297172018-03-26 10:53:33 -07001109}
1110
Chenbo Fengf2759682017-10-10 17:31:57 -07001111} // namespace net
1112} // namespace android