blob: 5c74e9abcb85ad99f5e4614dfaa264b291d9313f [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;
mtk13799ae0704e2019-03-28 15:07:14 +080080constexpr mode_t S_NONE = 0;
Chenbo Feng116d0552017-12-04 17:25:19 -080081
Chenbo Fengbf660aa2019-02-26 16:12:27 -080082static_assert(BPF_PERMISSION_INTERNET == INetd::PERMISSION_INTERNET,
83 "Mismatch between BPF and AIDL permissions: PERMISSION_INTERNET");
84static_assert(BPF_PERMISSION_UPDATE_DEVICE_STATS == INetd::PERMISSION_UPDATE_DEVICE_STATS,
85 "Mismatch between BPF and AIDL permissions: PERMISSION_UPDATE_DEVICE_STATS");
Chenbo Fengfd88f9d2019-05-01 12:59:09 -070086static_assert(STATS_MAP_SIZE - TOTAL_UID_STATS_ENTRIES_LIMIT > 100,
87 "The limit for stats map is to high, stats data may be lost due to overflow");
Chenbo Fengbf660aa2019-02-26 16:12:27 -080088
Chenbo Feng48eaed32018-12-26 17:40:21 -080089#define FLAG_MSG_TRANS(result, flag, value) \
90 do { \
91 if (value & flag) { \
92 result.append(StringPrintf(" %s", #flag)); \
93 value &= ~flag; \
94 } \
Chenbo Feng703798e2018-06-15 17:07:59 -070095 } while (0)
96
97const std::string uidMatchTypeToString(uint8_t match) {
98 std::string matchType;
Chenbo Feng48eaed32018-12-26 17:40:21 -080099 FLAG_MSG_TRANS(matchType, HAPPY_BOX_MATCH, match);
100 FLAG_MSG_TRANS(matchType, PENALTY_BOX_MATCH, match);
101 FLAG_MSG_TRANS(matchType, DOZABLE_MATCH, match);
102 FLAG_MSG_TRANS(matchType, STANDBY_MATCH, match);
103 FLAG_MSG_TRANS(matchType, POWERSAVE_MATCH, match);
Rubin Xuec27ff22019-01-08 21:33:03 +0000104 FLAG_MSG_TRANS(matchType, IIF_MATCH, match);
Chenbo Feng703798e2018-06-15 17:07:59 -0700105 if (match) {
106 return StringPrintf("Unknown match: %u", match);
107 }
108 return matchType;
109}
110
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800111bool TrafficController::hasUpdateDeviceStatsPermission(uid_t uid) {
Chenbo Feng3969c262019-03-19 14:53:57 -0700112 // This implementation is the same logic as method ActivityManager#checkComponentPermission.
113 // It implies that the calling uid can never be the same as PER_USER_RANGE.
114 uint32_t appId = uid % PER_USER_RANGE;
115 return ((appId == AID_ROOT) || (appId == AID_SYSTEM) ||
116 mPrivilegedUser.find(appId) != mPrivilegedUser.end());
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800117}
118
Chenbo Feng48eaed32018-12-26 17:40:21 -0800119const std::string UidPermissionTypeToString(uint8_t permission) {
Chenbo Feng84f48cd2019-04-22 15:34:40 -0700120 if (permission == INetd::PERMISSION_NONE) {
121 return "PERMISSION_NONE";
Chenbo Fengbf660aa2019-02-26 16:12:27 -0800122 }
Chenbo Feng527908a2019-04-02 20:14:11 -0700123 if (permission == INetd::PERMISSION_UNINSTALLED) {
124 // This should never appear in the map, complain loudly if it does.
125 return "PERMISSION_UNINSTALLED error!";
126 }
Chenbo Feng48eaed32018-12-26 17:40:21 -0800127 std::string permissionType;
Chenbo Fengbf660aa2019-02-26 16:12:27 -0800128 FLAG_MSG_TRANS(permissionType, BPF_PERMISSION_INTERNET, permission);
129 FLAG_MSG_TRANS(permissionType, BPF_PERMISSION_UPDATE_DEVICE_STATS, permission);
Chenbo Feng48eaed32018-12-26 17:40:21 -0800130 if (permission) {
131 return StringPrintf("Unknown permission: %u", permission);
132 }
133 return permissionType;
134}
135
Chenbo Feng49586642018-08-30 18:01:53 -0700136StatusOr<std::unique_ptr<NetlinkListenerInterface>> TrafficController::makeSkDestroyListener() {
Chenbo Feng116d0552017-12-04 17:25:19 -0800137 const auto& sys = sSyscalls.get();
138 ASSIGN_OR_RETURN(auto event, sys.eventfd(0, EFD_CLOEXEC));
139 const int domain = AF_NETLINK;
140 const int type = SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK;
141 const int protocol = NETLINK_INET_DIAG;
142 ASSIGN_OR_RETURN(auto sock, sys.socket(domain, type, protocol));
143
Lorenzo Colitti436efdb2018-07-26 17:20:57 +0900144 // TODO: if too many sockets are closed too quickly, we can overflow the socket buffer, and
145 // some entries in mCookieTagMap will not be freed. In order to fix this we would need to
146 // periodically dump all sockets and remove the tag entries for sockets that have been closed.
147 // For now, set a large-enough buffer that we can close hundreds of sockets without getting
148 // ENOBUFS and leaking mCookieTagMap entries.
149 int rcvbuf = 512 * 1024;
150 auto ret = sys.setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf));
151 if (!ret.ok()) {
152 ALOGW("Failed to set SkDestroyListener buffer size to %d: %s", rcvbuf, ret.msg().c_str());
153 }
154
Chenbo Feng116d0552017-12-04 17:25:19 -0800155 sockaddr_nl addr = {
156 .nl_family = AF_NETLINK,
157 .nl_groups = 1 << (SKNLGRP_INET_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET_UDP_DESTROY - 1) |
158 1 << (SKNLGRP_INET6_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET6_UDP_DESTROY - 1)};
159 RETURN_IF_NOT_OK(sys.bind(sock, addr));
160
161 const sockaddr_nl kernel = {.nl_family = AF_NETLINK};
162 RETURN_IF_NOT_OK(sys.connect(sock, kernel));
163
164 std::unique_ptr<NetlinkListenerInterface> listener =
Chenbo Feng46296702018-08-23 12:20:22 -0700165 std::make_unique<NetlinkListener>(std::move(event), std::move(sock), "SkDestroyListen");
Chenbo Feng116d0552017-12-04 17:25:19 -0800166
167 return listener;
168}
169
mtk13799ae0704e2019-03-28 15:07:14 +0800170Status changeOwnerAndMode(const char* path, gid_t group, const char* debugName, mode_t groupMode) {
Chenbo Feng89c12f12018-03-21 10:29:18 -0700171 int ret = chown(path, AID_ROOT, group);
172 if (ret != 0) return statusFromErrno(errno, StringPrintf("change %s group failed", debugName));
173
mtk13799ae0704e2019-03-28 15:07:14 +0800174 // Ensure groupMode only contains group bits.
175 groupMode &= S_IRGRP | S_IWGRP;
176
177 // chmod doesn't by itself grant permission to all processes in that group to
178 // read/write the bpf map. They still need correct sepolicy.
179 ret = chmod(path, S_IRUSR | S_IWUSR | groupMode);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700180 if (ret != 0) return statusFromErrno(errno, StringPrintf("change %s mode failed", debugName));
181 return netdutils::status::ok;
182}
183
Chenbo Feng82075e52019-04-12 19:21:47 -0700184TrafficController::TrafficController()
185 : mBpfLevel(getBpfSupportLevel()),
186 mPerUidStatsEntriesLimit(PER_UID_STATS_ENTRIES_LIMIT),
187 mTotalUidStatsEntriesLimit(TOTAL_UID_STATS_ENTRIES_LIMIT) {}
188
189TrafficController::TrafficController(uint32_t perUidLimit, uint32_t totalLimit)
190 : mBpfLevel(getBpfSupportLevel()),
191 mPerUidStatsEntriesLimit(perUidLimit),
192 mTotalUidStatsEntriesLimit(totalLimit) {}
Chenbo Feng89c12f12018-03-21 10:29:18 -0700193
Chenbo Feng89c12f12018-03-21 10:29:18 -0700194Status TrafficController::initMaps() {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700195 std::lock_guard guard(mMutex);
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700196 RETURN_IF_NOT_OK(mCookieTagMap.init(COOKIE_TAG_MAP_PATH));
mtk13799ae0704e2019-03-28 15:07:14 +0800197 RETURN_IF_NOT_OK(
198 changeOwnerAndMode(COOKIE_TAG_MAP_PATH, AID_NET_BW_ACCT, "CookieTagMap", S_IRGRP));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700199
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700200 RETURN_IF_NOT_OK(mUidCounterSetMap.init(UID_COUNTERSET_MAP_PATH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700201 RETURN_IF_NOT_OK(changeOwnerAndMode(UID_COUNTERSET_MAP_PATH, AID_NET_BW_ACCT,
mtk13799ae0704e2019-03-28 15:07:14 +0800202 "UidCounterSetMap", S_IRGRP));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700203
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700204 RETURN_IF_NOT_OK(mAppUidStatsMap.init(APP_UID_STATS_MAP_PATH));
mtk13799ae0704e2019-03-28 15:07:14 +0800205 RETURN_IF_NOT_OK(changeOwnerAndMode(APP_UID_STATS_MAP_PATH, AID_NET_BW_STATS, "AppUidStatsMap",
206 S_IRGRP));
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700207
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700208 RETURN_IF_NOT_OK(mStatsMapA.init(STATS_MAP_A_PATH));
mtk13799ae0704e2019-03-28 15:07:14 +0800209 RETURN_IF_NOT_OK(
210 changeOwnerAndMode(STATS_MAP_A_PATH, AID_NET_BW_STATS, "StatsMapA", S_IRGRP | S_IWGRP));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700211
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700212 RETURN_IF_NOT_OK(mStatsMapB.init(STATS_MAP_B_PATH));
mtk13799ae0704e2019-03-28 15:07:14 +0800213 RETURN_IF_NOT_OK(
214 changeOwnerAndMode(STATS_MAP_B_PATH, AID_NET_BW_STATS, "StatsMapB", S_IRGRP | S_IWGRP));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700215
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700216 RETURN_IF_NOT_OK(mIfaceIndexNameMap.init(IFACE_INDEX_NAME_MAP_PATH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700217 RETURN_IF_NOT_OK(changeOwnerAndMode(IFACE_INDEX_NAME_MAP_PATH, AID_NET_BW_STATS,
mtk13799ae0704e2019-03-28 15:07:14 +0800218 "IfaceIndexNameMap", S_IRGRP));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700219
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700220 RETURN_IF_NOT_OK(mIfaceStatsMap.init(IFACE_STATS_MAP_PATH));
mtk13799ae0704e2019-03-28 15:07:14 +0800221 RETURN_IF_NOT_OK(
222 changeOwnerAndMode(IFACE_STATS_MAP_PATH, AID_NET_BW_STATS, "IfaceStatsMap", S_IRGRP));
Chenbo Feng95892f32018-06-07 14:52:02 -0700223
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700224 RETURN_IF_NOT_OK(mConfigurationMap.init(CONFIGURATION_MAP_PATH));
Chenbo Fengf434e862018-06-27 14:08:39 -0700225 RETURN_IF_NOT_OK(changeOwnerAndMode(CONFIGURATION_MAP_PATH, AID_NET_BW_STATS,
mtk13799ae0704e2019-03-28 15:07:14 +0800226 "ConfigurationMap", S_IRGRP));
Chenbo Feng703798e2018-06-15 17:07:59 -0700227 RETURN_IF_NOT_OK(
Chenbo Fengf434e862018-06-27 14:08:39 -0700228 mConfigurationMap.writeValue(UID_RULES_CONFIGURATION_KEY, DEFAULT_CONFIG, BPF_ANY));
229 RETURN_IF_NOT_OK(mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, SELECT_MAP_A,
230 BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700231
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700232 RETURN_IF_NOT_OK(mUidOwnerMap.init(UID_OWNER_MAP_PATH));
mtk13799ae0704e2019-03-28 15:07:14 +0800233 RETURN_IF_NOT_OK(changeOwnerAndMode(UID_OWNER_MAP_PATH, AID_ROOT, "UidOwnerMap", S_NONE));
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900234 RETURN_IF_NOT_OK(mUidOwnerMap.clear());
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700235 RETURN_IF_NOT_OK(mUidPermissionMap.init(UID_PERMISSION_MAP_PATH));
mtk13799ae0704e2019-03-28 15:07:14 +0800236
237 // The programs must be readable to process that modify iptables rules
238 RETURN_IF_NOT_OK(changeOwnerAndMode(XT_BPF_EGRESS_PROG_PATH, AID_NET_ADMIN,
239 "XtFilterEgressProgram", S_IRGRP));
240 RETURN_IF_NOT_OK(changeOwnerAndMode(XT_BPF_INGRESS_PROG_PATH, AID_NET_ADMIN,
241 "XtFilterIngressProgram", S_IRGRP));
242 RETURN_IF_NOT_OK(changeOwnerAndMode(XT_BPF_WHITELIST_PROG_PATH, AID_NET_ADMIN,
243 "XtWhitelistProgram", S_IRGRP));
244 RETURN_IF_NOT_OK(changeOwnerAndMode(XT_BPF_BLACKLIST_PROG_PATH, AID_NET_ADMIN,
245 "XtBlacklistProgram", S_IRGRP));
246
Chenbo Feng89c12f12018-03-21 10:29:18 -0700247 return netdutils::status::ok;
248}
249
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800250static Status attachProgramToCgroup(const char* programPath, const int cgroupFd,
251 bpf_attach_type type) {
252 unique_fd cgroupProg(bpfFdGet(programPath, 0));
253 if (cgroupProg == -1) {
254 int ret = errno;
255 ALOGE("Failed to get program from %s: %s", programPath, strerror(ret));
256 return statusFromErrno(ret, "cgroup program get failed");
257 }
258 if (android::bpf::attachProgram(type, cgroupProg, cgroupFd)) {
259 int ret = errno;
260 ALOGE("Program from %s attach failed: %s", programPath, strerror(ret));
261 return statusFromErrno(ret, "program attach failed");
262 }
263 return netdutils::status::ok;
264}
265
266static Status initPrograms() {
Suren Baghdasaryane072a3c2019-01-16 14:36:07 -0800267 std::string cg2_path;
268
269 if (!CgroupGetControllerPath(CGROUPV2_CONTROLLER_NAME, &cg2_path)) {
270 int ret = errno;
271 ALOGE("Failed to find cgroup v2 root");
272 return statusFromErrno(ret, "Failed to find cgroup v2 root");
273 }
274
275 unique_fd cg_fd(open(cg2_path.c_str(), O_DIRECTORY | O_RDONLY | O_CLOEXEC));
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800276 if (cg_fd == -1) {
277 int ret = errno;
278 ALOGE("Failed to open the cgroup directory: %s", strerror(ret));
279 return statusFromErrno(ret, "Open the cgroup directory failed");
280 }
281 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_EGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_EGRESS));
282 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_INGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_INGRESS));
Chenbo Fenga51f4fa2019-01-15 15:03:32 -0800283
284 // For the devices that support cgroup socket filter, the socket filter
285 // should be loaded successfully by bpfloader. So we attach the filter to
286 // cgroup if the program is pinned properly.
287 // TODO: delete the if statement once all devices should support cgroup
288 // socket filter (ie. the minimum kernel version required is 4.14).
289 if (!access(CGROUP_SOCKET_PROG_PATH, F_OK)) {
290 RETURN_IF_NOT_OK(
291 attachProgramToCgroup(CGROUP_SOCKET_PROG_PATH, cg_fd, BPF_CGROUP_INET_SOCK_CREATE));
292 }
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800293 return netdutils::status::ok;
294}
295
Chenbo Feng89c12f12018-03-21 10:29:18 -0700296Status TrafficController::start() {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800297 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800298 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700299 }
300
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900301 /* When netd restarts from a crash without total system reboot, the program
Chenbo Fengf2759682017-10-10 17:31:57 -0700302 * is still attached to the cgroup, detach it so the program can be freed
303 * and we can load and attach new program into the target cgroup.
304 *
305 * TODO: Scrape existing socket when run-time restart and clean up the map
306 * if the socket no longer exist
307 */
308
Chenbo Feng89c12f12018-03-21 10:29:18 -0700309 RETURN_IF_NOT_OK(initMaps());
Chenbo Feng7e974052018-02-28 22:57:21 -0800310
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800311 RETURN_IF_NOT_OK(initPrograms());
312
Chenbo Feng7e974052018-02-28 22:57:21 -0800313 // Fetch the list of currently-existing interfaces. At this point NetlinkHandler is
314 // already running, so it will call addInterface() when any new interface appears.
315 std::map<std::string, uint32_t> ifacePairs;
316 ASSIGN_OR_RETURN(ifacePairs, InterfaceController::getIfaceList());
317 for (const auto& ifacePair:ifacePairs) {
318 addInterface(ifacePair.first.c_str(), ifacePair.second);
319 }
320
Chenbo Feng116d0552017-12-04 17:25:19 -0800321 auto result = makeSkDestroyListener();
322 if (!isOk(result)) {
323 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
324 } else {
325 mSkDestroyListener = std::move(result.value());
326 }
327 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
328 const auto rxHandler = [this](const nlmsghdr&, const Slice msg) {
Chenbo Fengf01f5302019-05-07 12:28:13 -0700329 std::lock_guard guard(mMutex);
Chenbo Feng116d0552017-12-04 17:25:19 -0800330 inet_diag_msg diagmsg = {};
331 if (extract(msg, diagmsg) < sizeof(inet_diag_msg)) {
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900332 ALOGE("Unrecognized netlink message: %s", toString(msg).c_str());
Chenbo Feng116d0552017-12-04 17:25:19 -0800333 return;
334 }
335 uint64_t sock_cookie = static_cast<uint64_t>(diagmsg.id.idiag_cookie[0]) |
336 (static_cast<uint64_t>(diagmsg.id.idiag_cookie[1]) << 32);
337
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900338 Status s = mCookieTagMap.deleteValue(sock_cookie);
Chenbo Feng1d4c5db2018-10-18 15:50:46 -0700339 if (!isOk(s) && s.code() != ENOENT) {
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900340 ALOGE("Failed to delete cookie %" PRIx64 ": %s", sock_cookie, toString(s).c_str());
341 return;
342 }
Chenbo Feng116d0552017-12-04 17:25:19 -0800343 };
344 expectOk(mSkDestroyListener->subscribe(kSockDiagMsgType, rxHandler));
345
346 // In case multiple netlink message comes in as a stream, we need to handle the rxDone message
347 // properly.
348 const auto rxDoneHandler = [](const nlmsghdr&, const Slice msg) {
349 // Ignore NLMSG_DONE messages
350 inet_diag_msg diagmsg = {};
351 extract(msg, diagmsg);
352 };
353 expectOk(mSkDestroyListener->subscribe(kSockDiagDoneMsgType, rxDoneHandler));
354
Chenbo Feng05393d82018-01-09 15:18:43 -0800355 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700356}
357
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800358int TrafficController::tagSocket(int sockFd, uint32_t tag, uid_t uid, uid_t callingUid) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700359 std::lock_guard guard(mMutex);
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800360 if (uid != callingUid && !hasUpdateDeviceStatsPermission(callingUid)) {
361 return -EPERM;
362 }
363
Chenbo Feng47dd0732018-12-11 12:23:24 -0800364 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700365 if (legacy_tagSocket(sockFd, tag, uid)) return -errno;
366 return 0;
367 }
Chenbo Feng33cc1032017-10-23 15:16:37 -0700368
Chenbo Fengf2759682017-10-10 17:31:57 -0700369 uint64_t sock_cookie = getSocketCookie(sockFd);
Chenbo Fengef1cab32018-04-13 19:50:49 -0700370 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
Chenbo Fengf2759682017-10-10 17:31:57 -0700371 UidTag newKey = {.uid = (uint32_t)uid, .tag = tag};
372
Chenbo Fengb0495132019-04-10 12:54:41 -0700373 uint32_t totalEntryCount = 0;
Chenbo Feng82075e52019-04-12 19:21:47 -0700374 uint32_t perUidEntryCount = 0;
Chenbo Fengb0495132019-04-10 12:54:41 -0700375 // Now we go through the stats map and count how many entries are associated
376 // with target uid. If the uid entry hit the limit for each uid, we block
377 // the request to prevent the map from overflow. It is safe here to iterate
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700378 // over the map since when mMutex is hold, system server cannot toggle
Chenbo Fengb0495132019-04-10 12:54:41 -0700379 // the live stats map and clean it. So nobody can delete entries from the map.
Chenbo Feng82075e52019-04-12 19:21:47 -0700380 const auto countUidStatsEntries = [uid, &totalEntryCount, &perUidEntryCount](
381 const StatsKey& key, BpfMap<StatsKey, StatsValue>&) {
Chenbo Fengb0495132019-04-10 12:54:41 -0700382 if (key.uid == uid) {
Chenbo Feng82075e52019-04-12 19:21:47 -0700383 perUidEntryCount++;
Chenbo Fengb0495132019-04-10 12:54:41 -0700384 }
Chenbo Feng82075e52019-04-12 19:21:47 -0700385 totalEntryCount++;
Chenbo Fengb0495132019-04-10 12:54:41 -0700386 return netdutils::status::ok;
387 };
388 auto configuration = mConfigurationMap.readValue(CURRENT_STATS_MAP_CONFIGURATION_KEY);
389 if (!isOk(configuration.status())) {
390 ALOGE("Failed to get current configuration: %s, fd: %d",
391 strerror(configuration.status().code()), mConfigurationMap.getMap().get());
392 return -configuration.status().code();
393 }
Chenbo Feng36a40d12019-04-23 16:47:05 -0700394 if (configuration.value() != SELECT_MAP_A && configuration.value() != SELECT_MAP_B) {
Chenbo Fengb0495132019-04-10 12:54:41 -0700395 ALOGE("unknown configuration value: %d", configuration.value());
396 return -EINVAL;
397 }
Chenbo Feng36a40d12019-04-23 16:47:05 -0700398
399 BpfMap<StatsKey, StatsValue>& currentMap =
400 (configuration.value() == SELECT_MAP_A) ? mStatsMapA : mStatsMapB;
401 Status res = currentMap.iterate(countUidStatsEntries);
402 if (!isOk(res)) {
403 ALOGE("Failed to count the stats entry in map %d: %s", currentMap.getMap().get(),
404 strerror(res.code()));
405 return -res.code();
406 }
407
Chenbo Feng82075e52019-04-12 19:21:47 -0700408 if (totalEntryCount > mTotalUidStatsEntriesLimit ||
409 perUidEntryCount > mPerUidStatsEntriesLimit) {
410 ALOGE("Too many stats entries in the map, total count: %u, uid(%u) count: %u, blocking tag"
411 " request to prevent map overflow",
412 totalEntryCount, uid, perUidEntryCount);
Chenbo Fengb0495132019-04-10 12:54:41 -0700413 return -EMFILE;
414 }
Chenbo Fengf2759682017-10-10 17:31:57 -0700415 // Update the tag information of a socket to the cookieUidMap. Use BPF_ANY
416 // flag so it will insert a new entry to the map if that value doesn't exist
417 // yet. And update the tag if there is already a tag stored. Since the eBPF
418 // program in kernel only read this map, and is protected by rcu read lock. It
419 // should be fine to cocurrently update the map while eBPF program is running.
Chenbo Feng36a40d12019-04-23 16:47:05 -0700420 res = mCookieTagMap.writeValue(sock_cookie, newKey, BPF_ANY);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700421 if (!isOk(res)) {
422 ALOGE("Failed to tag the socket: %s, fd: %d", strerror(res.code()),
423 mCookieTagMap.getMap().get());
Chenbo Fengf2759682017-10-10 17:31:57 -0700424 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700425 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700426}
427
428int TrafficController::untagSocket(int sockFd) {
Chenbo Fengf01f5302019-05-07 12:28:13 -0700429 std::lock_guard guard(mMutex);
Chenbo Feng47dd0732018-12-11 12:23:24 -0800430 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700431 if (legacy_untagSocket(sockFd)) return -errno;
432 return 0;
433 }
Chenbo Fengf2759682017-10-10 17:31:57 -0700434 uint64_t sock_cookie = getSocketCookie(sockFd);
435
Chenbo Fengef1cab32018-04-13 19:50:49 -0700436 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700437 Status res = mCookieTagMap.deleteValue(sock_cookie);
438 if (!isOk(res)) {
439 ALOGE("Failed to untag socket: %s\n", strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700440 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700441 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700442}
443
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800444int TrafficController::setCounterSet(int counterSetNum, uid_t uid, uid_t callingUid) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700445 if (counterSetNum < 0 || counterSetNum >= OVERFLOW_COUNTERSET) return -EINVAL;
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800446
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700447 std::lock_guard guard(mMutex);
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800448 if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
449
Chenbo Feng47dd0732018-12-11 12:23:24 -0800450 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700451 if (legacy_setCounterSet(counterSetNum, uid)) return -errno;
452 return 0;
453 }
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800454
455 // The default counter set for all uid is 0, so deleting the current counterset for that uid
456 // will automatically set it to 0.
Chenbo Fengf2759682017-10-10 17:31:57 -0700457 if (counterSetNum == 0) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700458 Status res = mUidCounterSetMap.deleteValue(uid);
459 if (isOk(res) || (!isOk(res) && res.code() == ENOENT)) {
Chenbo Fengf2759682017-10-10 17:31:57 -0700460 return 0;
461 } else {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700462 ALOGE("Failed to delete the counterSet: %s\n", strerror(res.code()));
463 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700464 }
465 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700466 uint8_t tmpCounterSetNum = (uint8_t)counterSetNum;
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800467 Status res = mUidCounterSetMap.writeValue(uid, tmpCounterSetNum, BPF_ANY);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700468 if (!isOk(res)) {
469 ALOGE("Failed to set the counterSet: %s, fd: %d", strerror(res.code()),
470 mUidCounterSetMap.getMap().get());
471 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700472 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700473 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700474}
475
Chenbo Fengf434e862018-06-27 14:08:39 -0700476// This method only get called by system_server when an app get uinstalled, it
477// is called inside removeUidsLocked() while holding mStatsLock. So it is safe
478// to iterate and modify the stats maps.
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800479int TrafficController::deleteTagData(uint32_t tag, uid_t uid, uid_t callingUid) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700480 std::lock_guard guard(mMutex);
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800481 if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
482
Chenbo Feng47dd0732018-12-11 12:23:24 -0800483 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700484 if (legacy_deleteTagData(tag, uid)) return -errno;
485 return 0;
486 }
Chenbo Feng33cc1032017-10-23 15:16:37 -0700487
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800488 // First we go through the cookieTagMap to delete the target uid tag combination. Or delete all
Chenbo Fengef1cab32018-04-13 19:50:49 -0700489 // the tags related to the uid if the tag is 0.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700490 const auto deleteMatchedCookieEntries = [uid, tag](const uint64_t& key, const UidTag& value,
491 BpfMap<uint64_t, UidTag>& map) {
492 if (value.uid == uid && (value.tag == tag || tag == 0)) {
493 Status res = map.deleteValue(key);
494 if (isOk(res) || (res.code() == ENOENT)) {
495 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700496 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700497 ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s\n", key, strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700498 }
Chenbo Fengef1cab32018-04-13 19:50:49 -0700499 // Move forward to next cookie in the map.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700500 return netdutils::status::ok;
Chenbo Fengef1cab32018-04-13 19:50:49 -0700501 };
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900502 mCookieTagMap.iterateWithValue(deleteMatchedCookieEntries).ignoreError();
Chenbo Fengf2759682017-10-10 17:31:57 -0700503 // 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 -0700504 // combination. Or all tag stats under that uid if the target tag is 0.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700505 const auto deleteMatchedUidTagEntries = [uid, tag](const StatsKey& key,
506 BpfMap<StatsKey, StatsValue>& map) {
507 if (key.uid == uid && (key.tag == tag || tag == 0)) {
508 Status res = map.deleteValue(key);
509 if (isOk(res) || (res.code() == ENOENT)) {
Chenbo Fengef1cab32018-04-13 19:50:49 -0700510 //Entry is deleted, use the current key to get a new nextKey;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700511 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700512 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700513 ALOGE("Failed to delete data(uid=%u, tag=%u): %s\n", key.uid, key.tag,
514 strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700515 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700516 return netdutils::status::ok;
Chenbo Fengef1cab32018-04-13 19:50:49 -0700517 };
Chenbo Fengf434e862018-06-27 14:08:39 -0700518 mStatsMapB.iterate(deleteMatchedUidTagEntries).ignoreError();
519 mStatsMapA.iterate(deleteMatchedUidTagEntries).ignoreError();
Chenbo Fengf2759682017-10-10 17:31:57 -0700520 // 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 -0800521 // need to delete the stats stored in uidStatsMap and counterSet map.
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800522 if (tag != 0) return 0;
523
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700524 Status res = mUidCounterSetMap.deleteValue(uid);
525 if (!isOk(res) && res.code() != ENOENT) {
526 ALOGE("Failed to delete counterSet data(uid=%u, tag=%u): %s\n", uid, tag,
527 strerror(res.code()));
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800528 }
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700529
530 auto deleteAppUidStatsEntry = [uid](const uint32_t& key, BpfMap<uint32_t, StatsValue>& map) {
531 if (key == uid) {
532 Status res = map.deleteValue(key);
533 if (isOk(res) || (res.code() == ENOENT)) {
534 return netdutils::status::ok;
535 }
536 ALOGE("Failed to delete data(uid=%u): %s", key, strerror(res.code()));
537 }
538 return netdutils::status::ok;
539 };
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900540 mAppUidStatsMap.iterate(deleteAppUidStatsEntry).ignoreError();
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700541 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700542}
543
Chenbo Feng7e974052018-02-28 22:57:21 -0800544int TrafficController::addInterface(const char* name, uint32_t ifaceIndex) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800545 if (mBpfLevel == BpfLevel::NONE) return 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800546
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700547 IfaceValue iface;
Chenbo Feng7e974052018-02-28 22:57:21 -0800548 if (ifaceIndex == 0) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700549 ALOGE("Unknown interface %s(%d)", name, ifaceIndex);
Chenbo Feng7e974052018-02-28 22:57:21 -0800550 return -1;
551 }
552
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700553 strlcpy(iface.name, name, sizeof(IfaceValue));
554 Status res = mIfaceIndexNameMap.writeValue(ifaceIndex, iface, BPF_ANY);
555 if (!isOk(res)) {
556 ALOGE("Failed to add iface %s(%d): %s", name, ifaceIndex, strerror(res.code()));
557 return -res.code();
Chenbo Feng7e974052018-02-28 22:57:21 -0800558 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700559 return 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800560}
561
Chenbo Feng703798e2018-06-15 17:07:59 -0700562Status TrafficController::updateOwnerMapEntry(UidOwnerMatchType match, uid_t uid, FirewallRule rule,
563 FirewallType type) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700564 std::lock_guard guard(mMutex);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700565 if ((rule == ALLOW && type == WHITELIST) || (rule == DENY && type == BLACKLIST)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100566 RETURN_IF_NOT_OK(addRule(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700567 } else if ((rule == ALLOW && type == BLACKLIST) || (rule == DENY && type == WHITELIST)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100568 RETURN_IF_NOT_OK(removeRule(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700569 } else {
570 //Cannot happen.
Rubin Xuec27ff22019-01-08 21:33:03 +0000571 return statusFromErrno(EINVAL, "");
Chenbo Feng89c12f12018-03-21 10:29:18 -0700572 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700573 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700574}
575
Chenbo Feng703798e2018-06-15 17:07:59 -0700576UidOwnerMatchType TrafficController::jumpOpToMatch(BandwidthController::IptJumpOp jumpHandling) {
Chenbo Feng95892f32018-06-07 14:52:02 -0700577 switch (jumpHandling) {
578 case BandwidthController::IptJumpReject:
Chenbo Feng703798e2018-06-15 17:07:59 -0700579 return PENALTY_BOX_MATCH;
Chenbo Feng95892f32018-06-07 14:52:02 -0700580 case BandwidthController::IptJumpReturn:
Chenbo Feng703798e2018-06-15 17:07:59 -0700581 return HAPPY_BOX_MATCH;
Chenbo Feng95892f32018-06-07 14:52:02 -0700582 case BandwidthController::IptJumpNoAdd:
583 return NO_MATCH;
584 }
585}
586
Rubin Xu5ca8e802019-04-05 11:50:32 +0100587Status TrafficController::removeRule(BpfMap<uint32_t, UidOwnerValue>& map, uint32_t uid,
588 UidOwnerMatchType match) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700589 auto oldMatch = map.readValue(uid);
590 if (isOk(oldMatch)) {
Rubin Xuec27ff22019-01-08 21:33:03 +0000591 UidOwnerValue newMatch = {.rule = static_cast<uint8_t>(oldMatch.value().rule & ~match),
592 .iif = (match == IIF_MATCH) ? 0 : oldMatch.value().iif};
593 if (newMatch.rule == 0) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700594 RETURN_IF_NOT_OK(map.deleteValue(uid));
595 } else {
596 RETURN_IF_NOT_OK(map.writeValue(uid, newMatch, BPF_ANY));
597 }
598 } else {
599 return statusFromErrno(ENOENT, StringPrintf("uid: %u does not exist in map", uid));
600 }
601 return netdutils::status::ok;
602}
603
Rubin Xu5ca8e802019-04-05 11:50:32 +0100604Status TrafficController::addRule(BpfMap<uint32_t, UidOwnerValue>& map, uint32_t uid,
605 UidOwnerMatchType match, uint32_t iif) {
Rubin Xuec27ff22019-01-08 21:33:03 +0000606 // iif should be non-zero if and only if match == MATCH_IIF
607 if (match == IIF_MATCH && iif == 0) {
608 return statusFromErrno(EINVAL, "Interface match must have nonzero interface index");
609 } else if (match != IIF_MATCH && iif != 0) {
610 return statusFromErrno(EINVAL, "Non-interface match must have zero interface index");
611 }
Chenbo Feng703798e2018-06-15 17:07:59 -0700612 auto oldMatch = map.readValue(uid);
613 if (isOk(oldMatch)) {
Rubin Xuec27ff22019-01-08 21:33:03 +0000614 UidOwnerValue newMatch = {.rule = static_cast<uint8_t>(oldMatch.value().rule | match),
615 .iif = iif ? iif : oldMatch.value().iif};
616 RETURN_IF_NOT_OK(map.writeValue(uid, newMatch, BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700617 } else {
Rubin Xuec27ff22019-01-08 21:33:03 +0000618 UidOwnerValue newMatch = {.rule = static_cast<uint8_t>(match), .iif = iif};
619 RETURN_IF_NOT_OK(map.writeValue(uid, newMatch, BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700620 }
621 return netdutils::status::ok;
622}
623
624Status TrafficController::updateUidOwnerMap(const std::vector<std::string>& appStrUids,
625 BandwidthController::IptJumpOp jumpHandling,
626 BandwidthController::IptOp op) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700627 std::lock_guard guard(mMutex);
Chenbo Feng703798e2018-06-15 17:07:59 -0700628 UidOwnerMatchType match = jumpOpToMatch(jumpHandling);
629 if (match == NO_MATCH) {
630 return statusFromErrno(
631 EINVAL, StringPrintf("invalid IptJumpOp: %d, command: %d", jumpHandling, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700632 }
633 for (const auto& appStrUid : appStrUids) {
634 char* endPtr;
635 long uid = strtol(appStrUid.c_str(), &endPtr, 10);
636 if ((errno == ERANGE && (uid == LONG_MAX || uid == LONG_MIN)) ||
637 (endPtr == appStrUid.c_str()) || (*endPtr != '\0')) {
638 return statusFromErrno(errno, "invalid uid string:" + appStrUid);
639 }
640
Chenbo Feng95892f32018-06-07 14:52:02 -0700641 if (op == BandwidthController::IptOpDelete) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100642 RETURN_IF_NOT_OK(removeRule(mUidOwnerMap, uid, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700643 } else if (op == BandwidthController::IptOpInsert) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100644 RETURN_IF_NOT_OK(addRule(mUidOwnerMap, uid, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700645 } else {
646 // Cannot happen.
Chenbo Feng703798e2018-06-15 17:07:59 -0700647 return statusFromErrno(EINVAL, StringPrintf("invalid IptOp: %d, %d", op, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700648 }
649 }
650 return netdutils::status::ok;
651}
652
Chenbo Feng89c12f12018-03-21 10:29:18 -0700653int TrafficController::changeUidOwnerRule(ChildChain chain, uid_t uid, FirewallRule rule,
654 FirewallType type) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800655 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Feng89c12f12018-03-21 10:29:18 -0700656 ALOGE("bpf is not set up, should use iptables rule");
657 return -ENOSYS;
658 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700659 Status res;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700660 switch (chain) {
661 case DOZABLE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700662 res = updateOwnerMapEntry(DOZABLE_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700663 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700664 case STANDBY:
Chenbo Feng703798e2018-06-15 17:07:59 -0700665 res = updateOwnerMapEntry(STANDBY_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700666 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700667 case POWERSAVE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700668 res = updateOwnerMapEntry(POWERSAVE_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700669 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700670 case NONE:
671 default:
672 return -EINVAL;
673 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700674 if (!isOk(res)) {
675 ALOGE("change uid(%u) rule of %d failed: %s, rule: %d, type: %d", uid, chain,
676 res.msg().c_str(), rule, type);
677 return -res.code();
678 }
679 return 0;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700680}
681
Rubin Xu5ca8e802019-04-05 11:50:32 +0100682Status TrafficController::replaceRulesInMap(const UidOwnerMatchType match,
683 const std::vector<int32_t>& uids) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700684 std::lock_guard guard(mMutex);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700685 std::set<int32_t> uidSet(uids.begin(), uids.end());
686 std::vector<uint32_t> uidsToDelete;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700687 auto getUidsToDelete = [&uidsToDelete, &uidSet](const uint32_t& key,
Rubin Xuec27ff22019-01-08 21:33:03 +0000688 const BpfMap<uint32_t, UidOwnerValue>&) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700689 if (uidSet.find((int32_t) key) == uidSet.end()) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700690 uidsToDelete.push_back(key);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700691 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700692 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700693 };
Chenbo Feng703798e2018-06-15 17:07:59 -0700694 RETURN_IF_NOT_OK(mUidOwnerMap.iterate(getUidsToDelete));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700695
696 for(auto uid : uidsToDelete) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100697 RETURN_IF_NOT_OK(removeRule(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700698 }
699
700 for (auto uid : uids) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100701 RETURN_IF_NOT_OK(addRule(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700702 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700703 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700704}
705
Rubin Xuec27ff22019-01-08 21:33:03 +0000706Status TrafficController::addUidInterfaceRules(const int iif,
707 const std::vector<int32_t>& uidsToAdd) {
708 if (mBpfLevel == BpfLevel::NONE) {
709 ALOGW("UID ingress interface filtering not possible without BPF owner match");
710 return statusFromErrno(EOPNOTSUPP, "eBPF not supported");
711 }
712 if (!iif) {
713 return statusFromErrno(EINVAL, "Interface rule must specify interface");
714 }
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700715 std::lock_guard guard(mMutex);
Rubin Xuec27ff22019-01-08 21:33:03 +0000716
717 for (auto uid : uidsToAdd) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100718 netdutils::Status result = addRule(mUidOwnerMap, uid, IIF_MATCH, iif);
Rubin Xuec27ff22019-01-08 21:33:03 +0000719 if (!isOk(result)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100720 ALOGW("addRule failed(%d): uid=%d iif=%d", result.code(), uid, iif);
Rubin Xuec27ff22019-01-08 21:33:03 +0000721 }
722 }
723 return netdutils::status::ok;
724}
725
726Status TrafficController::removeUidInterfaceRules(const std::vector<int32_t>& uidsToDelete) {
727 if (mBpfLevel == BpfLevel::NONE) {
728 ALOGW("UID ingress interface filtering not possible without BPF owner match");
729 return statusFromErrno(EOPNOTSUPP, "eBPF not supported");
730 }
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700731 std::lock_guard guard(mMutex);
Rubin Xuec27ff22019-01-08 21:33:03 +0000732
733 for (auto uid : uidsToDelete) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100734 netdutils::Status result = removeRule(mUidOwnerMap, uid, IIF_MATCH);
Rubin Xuec27ff22019-01-08 21:33:03 +0000735 if (!isOk(result)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100736 ALOGW("removeRule failed(%d): uid=%d", result.code(), uid);
Rubin Xuec27ff22019-01-08 21:33:03 +0000737 }
738 }
739 return netdutils::status::ok;
740}
741
Chenbo Feng89c12f12018-03-21 10:29:18 -0700742int TrafficController::replaceUidOwnerMap(const std::string& name, bool isWhitelist,
743 const std::vector<int32_t>& uids) {
Chenbo Feng89c12f12018-03-21 10:29:18 -0700744 FirewallRule rule;
745 FirewallType type;
746 if (isWhitelist) {
747 type = WHITELIST;
748 rule = ALLOW;
749 } else {
750 type = BLACKLIST;
751 rule = DENY;
752 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700753 Status res;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700754 if (!name.compare(FirewallController::LOCAL_DOZABLE)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100755 res = replaceRulesInMap(DOZABLE_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700756 } else if (!name.compare(FirewallController::LOCAL_STANDBY)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100757 res = replaceRulesInMap(STANDBY_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700758 } else if (!name.compare(FirewallController::LOCAL_POWERSAVE)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100759 res = replaceRulesInMap(POWERSAVE_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700760 } else {
761 ALOGE("unknown chain name: %s", name.c_str());
762 return -EINVAL;
763 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700764 if (!isOk(res)) {
765 ALOGE("Failed to clean up chain: %s: %s", name.c_str(), res.msg().c_str());
766 return -res.code();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700767 }
768 return 0;
769}
770
771int TrafficController::toggleUidOwnerMap(ChildChain chain, bool enable) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700772 std::lock_guard guard(mMutex);
Chenbo Fengf434e862018-06-27 14:08:39 -0700773 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Chenbo Feng703798e2018-06-15 17:07:59 -0700774 auto oldConfiguration = mConfigurationMap.readValue(key);
775 if (!isOk(oldConfiguration)) {
776 ALOGE("Cannot read the old configuration from map: %s",
777 oldConfiguration.status().msg().c_str());
778 return -oldConfiguration.status().code();
779 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700780 Status res;
Chenbo Feng703798e2018-06-15 17:07:59 -0700781 BpfConfig newConfiguration;
782 uint8_t match;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700783 switch (chain) {
784 case DOZABLE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700785 match = DOZABLE_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700786 break;
787 case STANDBY:
Chenbo Feng703798e2018-06-15 17:07:59 -0700788 match = STANDBY_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700789 break;
790 case POWERSAVE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700791 match = POWERSAVE_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700792 break;
793 default:
794 return -EINVAL;
795 }
Chenbo Feng703798e2018-06-15 17:07:59 -0700796 newConfiguration =
797 enable ? (oldConfiguration.value() | match) : (oldConfiguration.value() & (~match));
798 res = mConfigurationMap.writeValue(key, newConfiguration, BPF_EXIST);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700799 if (!isOk(res)) {
800 ALOGE("Failed to toggleUidOwnerMap(%d): %s", chain, res.msg().c_str());
Chenbo Feng89c12f12018-03-21 10:29:18 -0700801 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700802 return -res.code();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700803}
804
Chenbo Feng47dd0732018-12-11 12:23:24 -0800805BpfLevel TrafficController::getBpfLevel() {
806 return mBpfLevel;
Chenbo Feng07d43fe2017-12-21 14:38:51 -0800807}
808
Chenbo Feng873ae142019-04-10 12:26:06 -0700809Status TrafficController::swapActiveStatsMap() {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700810 std::lock_guard guard(mMutex);
Chenbo Feng873ae142019-04-10 12:26:06 -0700811
812 if (mBpfLevel == BpfLevel::NONE) {
813 return statusFromErrno(EOPNOTSUPP, "This device doesn't have eBPF support");
814 }
815
816 uint32_t key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
817 auto oldConfiguration = mConfigurationMap.readValue(key);
818 if (!isOk(oldConfiguration)) {
819 ALOGE("Cannot read the old configuration from map: %s",
820 oldConfiguration.status().msg().c_str());
821 return oldConfiguration.status();
822 }
823
824 // Write to the configuration map to inform the kernel eBPF program to switch
825 // from using one map to the other. Use flag BPF_EXIST here since the map should
826 // be already populated in initMaps.
827 uint8_t newConfigure = (oldConfiguration.value() == SELECT_MAP_A) ? SELECT_MAP_B : SELECT_MAP_A;
828 Status res = mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, newConfigure,
829 BPF_EXIST);
830 if (!isOk(res)) {
831 ALOGE("Failed to toggle the stats map: %s", strerror(res.code()));
832 return res;
833 }
834 // After changing the config, we need to make sure all the current running
835 // eBPF programs are finished and all the CPUs are aware of this config change
836 // before we modify the old map. So we do a special hack here to wait for
837 // the kernel to do a synchronize_rcu(). Once the kernel called
838 // synchronize_rcu(), the config we just updated will be available to all cores
839 // and the next eBPF programs triggered inside the kernel will use the new
840 // map configuration. So once this function returns we can safely modify the
841 // old stats map without concerning about race between the kernel and
842 // userspace.
843 int ret = synchronizeKernelRCU();
844 if (ret) {
845 ALOGE("map swap synchronize_rcu() ended with failure: %s", strerror(-ret));
846 return statusFromErrno(-ret, "map swap synchronize_rcu() failed");
847 }
848 return netdutils::status::ok;
849}
850
Chenbo Feng48eaed32018-12-26 17:40:21 -0800851void TrafficController::setPermissionForUids(int permission, const std::vector<uid_t>& uids) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700852 std::lock_guard guard(mMutex);
Chenbo Fengbf660aa2019-02-26 16:12:27 -0800853 if (permission == INetd::PERMISSION_UNINSTALLED) {
854 for (uid_t uid : uids) {
855 // Clean up all permission information for the related uid if all the
856 // packages related to it are uninstalled.
857 mPrivilegedUser.erase(uid);
Chenbo Feng97c88db2019-04-24 12:19:16 -0700858 if (mBpfLevel > BpfLevel::NONE) {
859 Status ret = mUidPermissionMap.deleteValue(uid);
Maciej Żenczykowski928ea232019-08-20 17:28:05 -0700860 if (!isOk(ret) && ret.code() != ENOENT) {
Chenbo Feng97c88db2019-04-24 12:19:16 -0700861 ALOGE("Failed to clean up the permission for %u: %s", uid,
862 strerror(ret.code()));
863 }
864 }
Chenbo Fengbf660aa2019-02-26 16:12:27 -0800865 }
866 return;
867 }
868
Chenbo Feng48eaed32018-12-26 17:40:21 -0800869 bool privileged = (permission & INetd::PERMISSION_UPDATE_DEVICE_STATS);
870
871 for (uid_t uid : uids) {
Chenbo Feng97c88db2019-04-24 12:19:16 -0700872 if (privileged) {
873 mPrivilegedUser.insert(uid);
874 } else {
875 mPrivilegedUser.erase(uid);
876 }
877
878 // Skip the bpf map operation if not supported.
879 if (mBpfLevel == BpfLevel::NONE) {
880 continue;
881 }
Chenbo Feng527908a2019-04-02 20:14:11 -0700882 // The map stores all the permissions that the UID has, except if the only permission
883 // the UID has is the INTERNET permission, then the UID should not appear in the map.
884 if (permission != INetd::PERMISSION_INTERNET) {
Chenbo Fengbf660aa2019-02-26 16:12:27 -0800885 Status ret = mUidPermissionMap.writeValue(uid, permission, BPF_ANY);
Chenbo Feng48eaed32018-12-26 17:40:21 -0800886 if (!isOk(ret)) {
Chenbo Feng527908a2019-04-02 20:14:11 -0700887 ALOGE("Failed to set permission: %s of uid(%u) to permission map: %s",
888 UidPermissionTypeToString(permission).c_str(), uid, strerror(ret.code()));
Chenbo Feng48eaed32018-12-26 17:40:21 -0800889 }
890 } else {
891 Status ret = mUidPermissionMap.deleteValue(uid);
892 if (!isOk(ret) && ret.code() != ENOENT) {
Chenbo Feng527908a2019-04-02 20:14:11 -0700893 ALOGE("Failed to remove uid %u from permission map: %s", uid, strerror(ret.code()));
Chenbo Feng48eaed32018-12-26 17:40:21 -0800894 }
895 }
Chenbo Feng48eaed32018-12-26 17:40:21 -0800896 }
897}
898
Chenbo Fengef297172018-03-26 10:53:33 -0700899std::string getProgramStatus(const char *path) {
900 int ret = access(path, R_OK);
901 if (ret == 0) {
902 return StringPrintf("OK");
903 }
904 if (ret != 0 && errno == ENOENT) {
905 return StringPrintf("program is missing at: %s", path);
906 }
907 return StringPrintf("check Program %s error: %s", path, strerror(errno));
908}
909
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700910std::string getMapStatus(const base::unique_fd& map_fd, const char* path) {
Chenbo Fengef297172018-03-26 10:53:33 -0700911 if (map_fd.get() < 0) {
912 return StringPrintf("map fd lost");
913 }
914 if (access(path, F_OK) != 0) {
915 return StringPrintf("map not pinned to location: %s", path);
916 }
917 return StringPrintf("OK");
918}
919
Bernie Innocentia5161a02019-01-30 22:40:53 +0900920// NOLINTNEXTLINE(google-runtime-references): grandfathered pass by non-const reference
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900921void dumpBpfMap(const std::string& mapName, DumpWriter& dw, const std::string& header) {
Chenbo Fengef297172018-03-26 10:53:33 -0700922 dw.blankline();
923 dw.println("%s:", mapName.c_str());
Erik Klineb31fd692018-06-06 20:50:11 +0900924 if (!header.empty()) {
925 dw.println(header);
Chenbo Fengef297172018-03-26 10:53:33 -0700926 }
927}
928
929const String16 TrafficController::DUMP_KEYWORD = String16("trafficcontroller");
930
931void TrafficController::dump(DumpWriter& dw, bool verbose) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700932 std::lock_guard guard(mMutex);
Erik Klineb31fd692018-06-06 20:50:11 +0900933 ScopedIndent indentTop(dw);
Chenbo Fengef297172018-03-26 10:53:33 -0700934 dw.println("TrafficController");
935
Erik Klineb31fd692018-06-06 20:50:11 +0900936 ScopedIndent indentPreBpfModule(dw);
Chenbo Feng47dd0732018-12-11 12:23:24 -0800937 dw.println("BPF module status: %s", BpfLevelToString(mBpfLevel).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700938
Chenbo Feng47dd0732018-12-11 12:23:24 -0800939 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengef297172018-03-26 10:53:33 -0700940 return;
Erik Klineb31fd692018-06-06 20:50:11 +0900941 }
Chenbo Fengef297172018-03-26 10:53:33 -0700942
943 dw.blankline();
944 dw.println("mCookieTagMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700945 getMapStatus(mCookieTagMap.getMap(), COOKIE_TAG_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700946 dw.println("mUidCounterSetMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700947 getMapStatus(mUidCounterSetMap.getMap(), UID_COUNTERSET_MAP_PATH).c_str());
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700948 dw.println("mAppUidStatsMap status: %s",
949 getMapStatus(mAppUidStatsMap.getMap(), APP_UID_STATS_MAP_PATH).c_str());
Chenbo Fengf434e862018-06-27 14:08:39 -0700950 dw.println("mStatsMapA status: %s",
951 getMapStatus(mStatsMapA.getMap(), STATS_MAP_A_PATH).c_str());
952 dw.println("mStatsMapB status: %s",
953 getMapStatus(mStatsMapB.getMap(), STATS_MAP_B_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700954 dw.println("mIfaceIndexNameMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700955 getMapStatus(mIfaceIndexNameMap.getMap(), IFACE_INDEX_NAME_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700956 dw.println("mIfaceStatsMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700957 getMapStatus(mIfaceStatsMap.getMap(), IFACE_STATS_MAP_PATH).c_str());
Chenbo Feng703798e2018-06-15 17:07:59 -0700958 dw.println("mConfigurationMap status: %s",
959 getMapStatus(mConfigurationMap.getMap(), CONFIGURATION_MAP_PATH).c_str());
960 dw.println("mUidOwnerMap status: %s",
961 getMapStatus(mUidOwnerMap.getMap(), UID_OWNER_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700962
963 dw.blankline();
964 dw.println("Cgroup ingress program status: %s",
965 getProgramStatus(BPF_INGRESS_PROG_PATH).c_str());
966 dw.println("Cgroup egress program status: %s", getProgramStatus(BPF_EGRESS_PROG_PATH).c_str());
967 dw.println("xt_bpf ingress program status: %s",
968 getProgramStatus(XT_BPF_INGRESS_PROG_PATH).c_str());
969 dw.println("xt_bpf egress program status: %s",
970 getProgramStatus(XT_BPF_EGRESS_PROG_PATH).c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700971 dw.println("xt_bpf bandwidth whitelist program status: %s",
972 getProgramStatus(XT_BPF_WHITELIST_PROG_PATH).c_str());
973 dw.println("xt_bpf bandwidth blacklist program status: %s",
974 getProgramStatus(XT_BPF_BLACKLIST_PROG_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700975
Erik Klineb31fd692018-06-06 20:50:11 +0900976 if (!verbose) {
977 return;
978 }
Chenbo Fengef297172018-03-26 10:53:33 -0700979
980 dw.blankline();
981 dw.println("BPF map content:");
982
Erik Klineb31fd692018-06-06 20:50:11 +0900983 ScopedIndent indentForMapContent(dw);
Chenbo Fengef297172018-03-26 10:53:33 -0700984
985 // Print CookieTagMap content.
986 dumpBpfMap("mCookieTagMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700987 const auto printCookieTagInfo = [&dw](const uint64_t& key, const UidTag& value,
988 const BpfMap<uint64_t, UidTag>&) {
989 dw.println("cookie=%" PRIu64 " tag=0x%x uid=%u", key, value.tag, value.uid);
990 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700991 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700992 Status res = mCookieTagMap.iterateWithValue(printCookieTagInfo);
993 if (!isOk(res)) {
994 dw.println("mCookieTagMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700995 }
996
997 // Print UidCounterSetMap Content
998 dumpBpfMap("mUidCounterSetMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700999 const auto printUidInfo = [&dw](const uint32_t& key, const uint8_t& value,
1000 const BpfMap<uint32_t, uint8_t>&) {
1001 dw.println("%u %u", key, value);
1002 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -07001003 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001004 res = mUidCounterSetMap.iterateWithValue(printUidInfo);
1005 if (!isOk(res)) {
1006 dw.println("mUidCounterSetMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001007 }
1008
Chenbo Fengbc4a15f2018-05-11 19:15:15 -07001009 // Print AppUidStatsMap content
1010 std::string appUidStatsHeader = StringPrintf("uid rxBytes rxPackets txBytes txPackets");
1011 dumpBpfMap("mAppUidStatsMap:", dw, appUidStatsHeader);
1012 auto printAppUidStatsInfo = [&dw](const uint32_t& key, const StatsValue& value,
1013 const BpfMap<uint32_t, StatsValue>&) {
1014 dw.println("%u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, value.rxBytes,
1015 value.rxPackets, value.txBytes, value.txPackets);
1016 return netdutils::status::ok;
1017 };
1018 res = mAppUidStatsMap.iterateWithValue(printAppUidStatsInfo);
1019 if (!res.ok()) {
1020 dw.println("mAppUidStatsMap print end with error: %s", res.msg().c_str());
1021 }
1022
Chenbo Fengef297172018-03-26 10:53:33 -07001023 // Print uidStatsMap content
1024 std::string statsHeader = StringPrintf("ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes"
1025 " rxPackets txBytes txPackets");
Chenbo Fengf434e862018-06-27 14:08:39 -07001026 dumpBpfMap("mStatsMapA", dw, statsHeader);
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001027 const auto printStatsInfo = [&dw, this](const StatsKey& key, const StatsValue& value,
1028 const BpfMap<StatsKey, StatsValue>&) {
1029 uint32_t ifIndex = key.ifaceIndex;
1030 auto ifname = mIfaceIndexNameMap.readValue(ifIndex);
1031 if (!isOk(ifname)) {
1032 strlcpy(ifname.value().name, "unknown", sizeof(IfaceValue));
Chenbo Fengef297172018-03-26 10:53:33 -07001033 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001034 dw.println("%u %s 0x%x %u %u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, ifIndex,
1035 ifname.value().name, key.tag, key.uid, key.counterSet, value.rxBytes,
1036 value.rxPackets, value.txBytes, value.txPackets);
1037 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -07001038 };
Chenbo Fengf434e862018-06-27 14:08:39 -07001039 res = mStatsMapA.iterateWithValue(printStatsInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001040 if (!isOk(res)) {
Chenbo Fengf434e862018-06-27 14:08:39 -07001041 dw.println("mStatsMapA print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001042 }
1043
1044 // Print TagStatsMap content.
Chenbo Fengf434e862018-06-27 14:08:39 -07001045 dumpBpfMap("mStatsMapB", dw, statsHeader);
1046 res = mStatsMapB.iterateWithValue(printStatsInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001047 if (!isOk(res)) {
Chenbo Fengf434e862018-06-27 14:08:39 -07001048 dw.println("mStatsMapB print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001049 }
1050
1051 // Print ifaceIndexToNameMap content.
1052 dumpBpfMap("mIfaceIndexNameMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001053 const auto printIfaceNameInfo = [&dw](const uint32_t& key, const IfaceValue& value,
1054 const BpfMap<uint32_t, IfaceValue>&) {
1055 const char* ifname = value.name;
1056 dw.println("ifaceIndex=%u ifaceName=%s", key, ifname);
1057 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -07001058 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001059 res = mIfaceIndexNameMap.iterateWithValue(printIfaceNameInfo);
1060 if (!isOk(res)) {
1061 dw.println("mIfaceIndexNameMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001062 }
1063
1064 // Print ifaceStatsMap content
1065 std::string ifaceStatsHeader = StringPrintf("ifaceIndex ifaceName rxBytes rxPackets txBytes"
1066 " txPackets");
1067 dumpBpfMap("mIfaceStatsMap:", dw, ifaceStatsHeader);
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001068 const auto printIfaceStatsInfo = [&dw, this](const uint32_t& key, const StatsValue& value,
1069 const BpfMap<uint32_t, StatsValue>&) {
1070 auto ifname = mIfaceIndexNameMap.readValue(key);
1071 if (!isOk(ifname)) {
1072 strlcpy(ifname.value().name, "unknown", sizeof(IfaceValue));
Chenbo Fengef297172018-03-26 10:53:33 -07001073 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001074 dw.println("%u %s %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, ifname.value().name,
1075 value.rxBytes, value.rxPackets, value.txBytes, value.txPackets);
1076 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -07001077 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001078 res = mIfaceStatsMap.iterateWithValue(printIfaceStatsInfo);
1079 if (!isOk(res)) {
1080 dw.println("mIfaceStatsMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001081 }
1082
Chenbo Feng703798e2018-06-15 17:07:59 -07001083 dw.blankline();
Chenbo Fengef297172018-03-26 10:53:33 -07001084
Chenbo Fengf434e862018-06-27 14:08:39 -07001085 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Chenbo Feng703798e2018-06-15 17:07:59 -07001086 auto configuration = mConfigurationMap.readValue(key);
1087 if (isOk(configuration)) {
Lorenzo Colittic2677362019-06-26 20:01:35 +09001088 dw.println("current ownerMatch configuration: %d%s", configuration.value(),
1089 uidMatchTypeToString(configuration.value()).c_str());
Chenbo Feng703798e2018-06-15 17:07:59 -07001090 } else {
Chenbo Fengf434e862018-06-27 14:08:39 -07001091 dw.println("mConfigurationMap read ownerMatch configure failed with error: %s",
1092 configuration.status().msg().c_str());
1093 }
Lorenzo Colittic2677362019-06-26 20:01:35 +09001094
Chenbo Fengf434e862018-06-27 14:08:39 -07001095 key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
1096 configuration = mConfigurationMap.readValue(key);
1097 if (isOk(configuration)) {
Lorenzo Colittic2677362019-06-26 20:01:35 +09001098 const char* statsMapDescription = "???";
1099 switch (configuration.value()) {
1100 case SELECT_MAP_A:
1101 statsMapDescription = "SELECT_MAP_A";
1102 break;
1103 case SELECT_MAP_B:
1104 statsMapDescription = "SELECT_MAP_B";
1105 break;
1106 // No default clause, so if we ever add a third map, this code will fail to build.
1107 }
1108 dw.println("current statsMap configuration: %d %s", configuration.value(),
1109 statsMapDescription);
Chenbo Fengf434e862018-06-27 14:08:39 -07001110 } else {
1111 dw.println("mConfigurationMap read stats map configure failed with error: %s",
1112 configuration.status().msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001113 }
Chenbo Feng703798e2018-06-15 17:07:59 -07001114 dumpBpfMap("mUidOwnerMap", dw, "");
Rubin Xuec27ff22019-01-08 21:33:03 +00001115 const auto printUidMatchInfo = [&dw, this](const uint32_t& key, const UidOwnerValue& value,
1116 const BpfMap<uint32_t, UidOwnerValue>&) {
1117 if (value.rule & IIF_MATCH) {
1118 auto ifname = mIfaceIndexNameMap.readValue(value.iif);
1119 if (isOk(ifname)) {
1120 dw.println("%u %s %s", key, uidMatchTypeToString(value.rule).c_str(),
1121 ifname.value().name);
1122 } else {
1123 dw.println("%u %s %u", key, uidMatchTypeToString(value.rule).c_str(), value.iif);
1124 }
1125 } else {
1126 dw.println("%u %s", key, uidMatchTypeToString(value.rule).c_str());
1127 }
Chenbo Feng703798e2018-06-15 17:07:59 -07001128 return netdutils::status::ok;
1129 };
1130 res = mUidOwnerMap.iterateWithValue(printUidMatchInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001131 if (!isOk(res)) {
Chenbo Feng703798e2018-06-15 17:07:59 -07001132 dw.println("mUidOwnerMap print end with error: %s", res.msg().c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -07001133 }
Chenbo Feng48eaed32018-12-26 17:40:21 -08001134 dumpBpfMap("mUidPermissionMap", dw, "");
1135 const auto printUidPermissionInfo = [&dw](const uint32_t& key, const uint8_t& value,
1136 const BpfMap<uint32_t, uint8_t>&) {
1137 dw.println("%u %s", key, UidPermissionTypeToString(value).c_str());
1138 return netdutils::status::ok;
1139 };
1140 res = mUidPermissionMap.iterateWithValue(printUidPermissionInfo);
1141 if (!isOk(res)) {
1142 dw.println("mUidPermissionMap print end with error: %s", res.msg().c_str());
1143 }
1144
1145 dumpBpfMap("mPrivilegedUser", dw, "");
1146 for (uid_t uid : mPrivilegedUser) {
1147 dw.println("%u ALLOW_UPDATE_DEVICE_STATS", (uint32_t)uid);
1148 }
Chenbo Fengef297172018-03-26 10:53:33 -07001149}
1150
Chenbo Fengf2759682017-10-10 17:31:57 -07001151} // namespace net
1152} // namespace android