blob: d676ac50826aa9eca2699ee909e363fef17a8a08 [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
Yi Kong3d82f382019-10-01 21:52:14 -0700119const std::string UidPermissionTypeToString(int 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()
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800185 : mBpfEnabled(isBpfSupported()),
Chenbo Feng82075e52019-04-12 19:21:47 -0700186 mPerUidStatsEntriesLimit(PER_UID_STATS_ENTRIES_LIMIT),
187 mTotalUidStatsEntriesLimit(TOTAL_UID_STATS_ENTRIES_LIMIT) {}
188
189TrafficController::TrafficController(uint32_t perUidLimit, uint32_t totalLimit)
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800190 : mBpfEnabled(isBpfSupported()),
Chenbo Feng82075e52019-04-12 19:21:47 -0700191 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
Hungming Chenb1ff3f12020-02-05 17:27:16 +0800237 RETURN_IF_NOT_OK(changeOwnerAndMode(TETHER_INGRESS_MAP_PATH, AID_NETWORK_STACK,
238 "TetherIngressMap", S_IRGRP | S_IWGRP));
239
mtk13799ae0704e2019-03-28 15:07:14 +0800240 // The programs must be readable to process that modify iptables rules
241 RETURN_IF_NOT_OK(changeOwnerAndMode(XT_BPF_EGRESS_PROG_PATH, AID_NET_ADMIN,
242 "XtFilterEgressProgram", S_IRGRP));
243 RETURN_IF_NOT_OK(changeOwnerAndMode(XT_BPF_INGRESS_PROG_PATH, AID_NET_ADMIN,
244 "XtFilterIngressProgram", S_IRGRP));
245 RETURN_IF_NOT_OK(changeOwnerAndMode(XT_BPF_WHITELIST_PROG_PATH, AID_NET_ADMIN,
246 "XtWhitelistProgram", S_IRGRP));
247 RETURN_IF_NOT_OK(changeOwnerAndMode(XT_BPF_BLACKLIST_PROG_PATH, AID_NET_ADMIN,
248 "XtBlacklistProgram", S_IRGRP));
249
Chenbo Feng89c12f12018-03-21 10:29:18 -0700250 return netdutils::status::ok;
251}
252
Maciej Żenczykowski87017852020-01-17 19:22:11 -0800253static Status attachProgramToCgroup(const char* programPath, const unique_fd& cgroupFd,
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800254 bpf_attach_type type) {
255 unique_fd cgroupProg(bpfFdGet(programPath, 0));
256 if (cgroupProg == -1) {
257 int ret = errno;
258 ALOGE("Failed to get program from %s: %s", programPath, strerror(ret));
259 return statusFromErrno(ret, "cgroup program get failed");
260 }
261 if (android::bpf::attachProgram(type, cgroupProg, cgroupFd)) {
262 int ret = errno;
263 ALOGE("Program from %s attach failed: %s", programPath, strerror(ret));
264 return statusFromErrno(ret, "program attach failed");
265 }
266 return netdutils::status::ok;
267}
268
269static Status initPrograms() {
Suren Baghdasaryane072a3c2019-01-16 14:36:07 -0800270 std::string cg2_path;
271
272 if (!CgroupGetControllerPath(CGROUPV2_CONTROLLER_NAME, &cg2_path)) {
273 int ret = errno;
274 ALOGE("Failed to find cgroup v2 root");
275 return statusFromErrno(ret, "Failed to find cgroup v2 root");
276 }
277
278 unique_fd cg_fd(open(cg2_path.c_str(), O_DIRECTORY | O_RDONLY | O_CLOEXEC));
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800279 if (cg_fd == -1) {
280 int ret = errno;
281 ALOGE("Failed to open the cgroup directory: %s", strerror(ret));
282 return statusFromErrno(ret, "Open the cgroup directory failed");
283 }
284 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_EGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_EGRESS));
285 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_INGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_INGRESS));
Chenbo Fenga51f4fa2019-01-15 15:03:32 -0800286
287 // For the devices that support cgroup socket filter, the socket filter
288 // should be loaded successfully by bpfloader. So we attach the filter to
289 // cgroup if the program is pinned properly.
290 // TODO: delete the if statement once all devices should support cgroup
291 // socket filter (ie. the minimum kernel version required is 4.14).
292 if (!access(CGROUP_SOCKET_PROG_PATH, F_OK)) {
293 RETURN_IF_NOT_OK(
294 attachProgramToCgroup(CGROUP_SOCKET_PROG_PATH, cg_fd, BPF_CGROUP_INET_SOCK_CREATE));
295 }
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800296 return netdutils::status::ok;
297}
298
Chenbo Feng89c12f12018-03-21 10:29:18 -0700299Status TrafficController::start() {
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800300 if (!mBpfEnabled) {
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800301 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700302 }
303
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900304 /* When netd restarts from a crash without total system reboot, the program
Chenbo Fengf2759682017-10-10 17:31:57 -0700305 * is still attached to the cgroup, detach it so the program can be freed
306 * and we can load and attach new program into the target cgroup.
307 *
308 * TODO: Scrape existing socket when run-time restart and clean up the map
309 * if the socket no longer exist
310 */
311
Chenbo Feng89c12f12018-03-21 10:29:18 -0700312 RETURN_IF_NOT_OK(initMaps());
Chenbo Feng7e974052018-02-28 22:57:21 -0800313
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800314 RETURN_IF_NOT_OK(initPrograms());
315
Chenbo Feng7e974052018-02-28 22:57:21 -0800316 // Fetch the list of currently-existing interfaces. At this point NetlinkHandler is
317 // already running, so it will call addInterface() when any new interface appears.
318 std::map<std::string, uint32_t> ifacePairs;
319 ASSIGN_OR_RETURN(ifacePairs, InterfaceController::getIfaceList());
320 for (const auto& ifacePair:ifacePairs) {
321 addInterface(ifacePair.first.c_str(), ifacePair.second);
322 }
323
Chenbo Feng116d0552017-12-04 17:25:19 -0800324 auto result = makeSkDestroyListener();
325 if (!isOk(result)) {
326 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
327 } else {
328 mSkDestroyListener = std::move(result.value());
329 }
330 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
331 const auto rxHandler = [this](const nlmsghdr&, const Slice msg) {
Chenbo Fengf01f5302019-05-07 12:28:13 -0700332 std::lock_guard guard(mMutex);
Chenbo Feng116d0552017-12-04 17:25:19 -0800333 inet_diag_msg diagmsg = {};
334 if (extract(msg, diagmsg) < sizeof(inet_diag_msg)) {
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900335 ALOGE("Unrecognized netlink message: %s", toString(msg).c_str());
Chenbo Feng116d0552017-12-04 17:25:19 -0800336 return;
337 }
338 uint64_t sock_cookie = static_cast<uint64_t>(diagmsg.id.idiag_cookie[0]) |
339 (static_cast<uint64_t>(diagmsg.id.idiag_cookie[1]) << 32);
340
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900341 Status s = mCookieTagMap.deleteValue(sock_cookie);
Chenbo Feng1d4c5db2018-10-18 15:50:46 -0700342 if (!isOk(s) && s.code() != ENOENT) {
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900343 ALOGE("Failed to delete cookie %" PRIx64 ": %s", sock_cookie, toString(s).c_str());
344 return;
345 }
Chenbo Feng116d0552017-12-04 17:25:19 -0800346 };
347 expectOk(mSkDestroyListener->subscribe(kSockDiagMsgType, rxHandler));
348
349 // In case multiple netlink message comes in as a stream, we need to handle the rxDone message
350 // properly.
351 const auto rxDoneHandler = [](const nlmsghdr&, const Slice msg) {
352 // Ignore NLMSG_DONE messages
353 inet_diag_msg diagmsg = {};
354 extract(msg, diagmsg);
355 };
356 expectOk(mSkDestroyListener->subscribe(kSockDiagDoneMsgType, rxDoneHandler));
357
Chenbo Feng05393d82018-01-09 15:18:43 -0800358 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700359}
360
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800361int TrafficController::tagSocket(int sockFd, uint32_t tag, uid_t uid, uid_t callingUid) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700362 std::lock_guard guard(mMutex);
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800363 if (uid != callingUid && !hasUpdateDeviceStatsPermission(callingUid)) {
364 return -EPERM;
365 }
366
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800367 if (!mBpfEnabled) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700368 if (legacy_tagSocket(sockFd, tag, uid)) return -errno;
369 return 0;
370 }
Chenbo Feng33cc1032017-10-23 15:16:37 -0700371
Chenbo Fengf2759682017-10-10 17:31:57 -0700372 uint64_t sock_cookie = getSocketCookie(sockFd);
Chenbo Fengef1cab32018-04-13 19:50:49 -0700373 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
Maciej Żenczykowski11ec78b2019-12-30 06:39:32 -0800374 UidTagValue newKey = {.uid = (uint32_t)uid, .tag = tag};
Chenbo Fengf2759682017-10-10 17:31:57 -0700375
Chenbo Fengb0495132019-04-10 12:54:41 -0700376 uint32_t totalEntryCount = 0;
Chenbo Feng82075e52019-04-12 19:21:47 -0700377 uint32_t perUidEntryCount = 0;
Chenbo Fengb0495132019-04-10 12:54:41 -0700378 // Now we go through the stats map and count how many entries are associated
379 // with target uid. If the uid entry hit the limit for each uid, we block
380 // the request to prevent the map from overflow. It is safe here to iterate
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700381 // over the map since when mMutex is hold, system server cannot toggle
Chenbo Fengb0495132019-04-10 12:54:41 -0700382 // the live stats map and clean it. So nobody can delete entries from the map.
Chenbo Feng82075e52019-04-12 19:21:47 -0700383 const auto countUidStatsEntries = [uid, &totalEntryCount, &perUidEntryCount](
Steven Morelanda3074542020-01-13 14:13:44 -0800384 const StatsKey& key,
385 const BpfMap<StatsKey, StatsValue>&) {
Chenbo Fengb0495132019-04-10 12:54:41 -0700386 if (key.uid == uid) {
Chenbo Feng82075e52019-04-12 19:21:47 -0700387 perUidEntryCount++;
Chenbo Fengb0495132019-04-10 12:54:41 -0700388 }
Chenbo Feng82075e52019-04-12 19:21:47 -0700389 totalEntryCount++;
Steven Morelanda3074542020-01-13 14:13:44 -0800390 return base::Result<void>();
Chenbo Fengb0495132019-04-10 12:54:41 -0700391 };
392 auto configuration = mConfigurationMap.readValue(CURRENT_STATS_MAP_CONFIGURATION_KEY);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900393 if (!configuration.ok()) {
Chenbo Fengb0495132019-04-10 12:54:41 -0700394 ALOGE("Failed to get current configuration: %s, fd: %d",
Steven Morelanda3074542020-01-13 14:13:44 -0800395 strerror(configuration.error().code()), mConfigurationMap.getMap().get());
396 return -configuration.error().code();
Chenbo Fengb0495132019-04-10 12:54:41 -0700397 }
Chenbo Feng36a40d12019-04-23 16:47:05 -0700398 if (configuration.value() != SELECT_MAP_A && configuration.value() != SELECT_MAP_B) {
Chenbo Fengb0495132019-04-10 12:54:41 -0700399 ALOGE("unknown configuration value: %d", configuration.value());
400 return -EINVAL;
401 }
Chenbo Feng36a40d12019-04-23 16:47:05 -0700402
403 BpfMap<StatsKey, StatsValue>& currentMap =
404 (configuration.value() == SELECT_MAP_A) ? mStatsMapA : mStatsMapB;
Steven Morelanda3074542020-01-13 14:13:44 -0800405 base::Result<void> res = currentMap.iterate(countUidStatsEntries);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900406 if (!res.ok()) {
Chenbo Feng36a40d12019-04-23 16:47:05 -0700407 ALOGE("Failed to count the stats entry in map %d: %s", currentMap.getMap().get(),
Steven Morelanda3074542020-01-13 14:13:44 -0800408 strerror(res.error().code()));
409 return -res.error().code();
Chenbo Feng36a40d12019-04-23 16:47:05 -0700410 }
411
Chenbo Feng82075e52019-04-12 19:21:47 -0700412 if (totalEntryCount > mTotalUidStatsEntriesLimit ||
413 perUidEntryCount > mPerUidStatsEntriesLimit) {
414 ALOGE("Too many stats entries in the map, total count: %u, uid(%u) count: %u, blocking tag"
415 " request to prevent map overflow",
416 totalEntryCount, uid, perUidEntryCount);
Chenbo Fengb0495132019-04-10 12:54:41 -0700417 return -EMFILE;
418 }
Chenbo Fengf2759682017-10-10 17:31:57 -0700419 // Update the tag information of a socket to the cookieUidMap. Use BPF_ANY
420 // flag so it will insert a new entry to the map if that value doesn't exist
421 // yet. And update the tag if there is already a tag stored. Since the eBPF
422 // program in kernel only read this map, and is protected by rcu read lock. It
423 // should be fine to cocurrently update the map while eBPF program is running.
Chenbo Feng36a40d12019-04-23 16:47:05 -0700424 res = mCookieTagMap.writeValue(sock_cookie, newKey, BPF_ANY);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900425 if (!res.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -0800426 ALOGE("Failed to tag the socket: %s, fd: %d", strerror(res.error().code()),
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700427 mCookieTagMap.getMap().get());
Steven Morelanda3074542020-01-13 14:13:44 -0800428 return -res.error().code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700429 }
Steven Morelanda3074542020-01-13 14:13:44 -0800430 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700431}
432
433int TrafficController::untagSocket(int sockFd) {
Chenbo Fengf01f5302019-05-07 12:28:13 -0700434 std::lock_guard guard(mMutex);
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800435 if (!mBpfEnabled) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700436 if (legacy_untagSocket(sockFd)) return -errno;
437 return 0;
438 }
Chenbo Fengf2759682017-10-10 17:31:57 -0700439 uint64_t sock_cookie = getSocketCookie(sockFd);
440
Chenbo Fengef1cab32018-04-13 19:50:49 -0700441 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
Steven Morelanda3074542020-01-13 14:13:44 -0800442 base::Result<void> res = mCookieTagMap.deleteValue(sock_cookie);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900443 if (!res.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -0800444 ALOGE("Failed to untag socket: %s\n", strerror(res.error().code()));
445 return -res.error().code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700446 }
Steven Morelanda3074542020-01-13 14:13:44 -0800447 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700448}
449
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800450int TrafficController::setCounterSet(int counterSetNum, uid_t uid, uid_t callingUid) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700451 if (counterSetNum < 0 || counterSetNum >= OVERFLOW_COUNTERSET) return -EINVAL;
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800452
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700453 std::lock_guard guard(mMutex);
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800454 if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
455
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800456 if (!mBpfEnabled) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700457 if (legacy_setCounterSet(counterSetNum, uid)) return -errno;
458 return 0;
459 }
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800460
461 // The default counter set for all uid is 0, so deleting the current counterset for that uid
462 // will automatically set it to 0.
Chenbo Fengf2759682017-10-10 17:31:57 -0700463 if (counterSetNum == 0) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700464 Status res = mUidCounterSetMap.deleteValue(uid);
465 if (isOk(res) || (!isOk(res) && res.code() == ENOENT)) {
Chenbo Fengf2759682017-10-10 17:31:57 -0700466 return 0;
467 } else {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700468 ALOGE("Failed to delete the counterSet: %s\n", strerror(res.code()));
469 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700470 }
471 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700472 uint8_t tmpCounterSetNum = (uint8_t)counterSetNum;
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800473 Status res = mUidCounterSetMap.writeValue(uid, tmpCounterSetNum, BPF_ANY);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700474 if (!isOk(res)) {
475 ALOGE("Failed to set the counterSet: %s, fd: %d", strerror(res.code()),
476 mUidCounterSetMap.getMap().get());
477 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700478 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700479 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700480}
481
Chenbo Fengf434e862018-06-27 14:08:39 -0700482// This method only get called by system_server when an app get uinstalled, it
483// is called inside removeUidsLocked() while holding mStatsLock. So it is safe
484// to iterate and modify the stats maps.
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800485int TrafficController::deleteTagData(uint32_t tag, uid_t uid, uid_t callingUid) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700486 std::lock_guard guard(mMutex);
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800487 if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
488
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800489 if (!mBpfEnabled) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700490 if (legacy_deleteTagData(tag, uid)) return -errno;
491 return 0;
492 }
Chenbo Feng33cc1032017-10-23 15:16:37 -0700493
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800494 // First we go through the cookieTagMap to delete the target uid tag combination. Or delete all
Chenbo Fengef1cab32018-04-13 19:50:49 -0700495 // the tags related to the uid if the tag is 0.
Maciej Żenczykowski11ec78b2019-12-30 06:39:32 -0800496 const auto deleteMatchedCookieEntries = [uid, tag](const uint64_t& key,
497 const UidTagValue& value,
498 BpfMap<uint64_t, UidTagValue>& map) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700499 if (value.uid == uid && (value.tag == tag || tag == 0)) {
Steven Morelanda3074542020-01-13 14:13:44 -0800500 auto res = map.deleteValue(key);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900501 if (res.ok() || (res.error().code() == ENOENT)) {
Steven Morelanda3074542020-01-13 14:13:44 -0800502 return base::Result<void>();
Chenbo Fengf2759682017-10-10 17:31:57 -0700503 }
Steven Morelanda3074542020-01-13 14:13:44 -0800504 ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s\n", key,
505 strerror(res.error().code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700506 }
Chenbo Fengef1cab32018-04-13 19:50:49 -0700507 // Move forward to next cookie in the map.
Steven Morelanda3074542020-01-13 14:13:44 -0800508 return base::Result<void>();
Chenbo Fengef1cab32018-04-13 19:50:49 -0700509 };
Steven Morelanda3074542020-01-13 14:13:44 -0800510 mCookieTagMap.iterateWithValue(deleteMatchedCookieEntries);
Chenbo Fengf2759682017-10-10 17:31:57 -0700511 // 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 -0700512 // combination. Or all tag stats under that uid if the target tag is 0.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700513 const auto deleteMatchedUidTagEntries = [uid, tag](const StatsKey& key,
514 BpfMap<StatsKey, StatsValue>& map) {
515 if (key.uid == uid && (key.tag == tag || tag == 0)) {
Steven Morelanda3074542020-01-13 14:13:44 -0800516 auto res = map.deleteValue(key);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900517 if (res.ok() || (res.error().code() == ENOENT)) {
Chenbo Fengef1cab32018-04-13 19:50:49 -0700518 //Entry is deleted, use the current key to get a new nextKey;
Steven Morelanda3074542020-01-13 14:13:44 -0800519 return base::Result<void>();
Chenbo Fengf2759682017-10-10 17:31:57 -0700520 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700521 ALOGE("Failed to delete data(uid=%u, tag=%u): %s\n", key.uid, key.tag,
Steven Morelanda3074542020-01-13 14:13:44 -0800522 strerror(res.error().code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700523 }
Steven Morelanda3074542020-01-13 14:13:44 -0800524 return base::Result<void>();
Chenbo Fengef1cab32018-04-13 19:50:49 -0700525 };
Steven Morelanda3074542020-01-13 14:13:44 -0800526 mStatsMapB.iterate(deleteMatchedUidTagEntries);
527 mStatsMapA.iterate(deleteMatchedUidTagEntries);
Chenbo Fengf2759682017-10-10 17:31:57 -0700528 // 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 -0800529 // need to delete the stats stored in uidStatsMap and counterSet map.
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800530 if (tag != 0) return 0;
531
Steven Morelanda3074542020-01-13 14:13:44 -0800532 auto res = mUidCounterSetMap.deleteValue(uid);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900533 if (!res.ok() && res.error().code() != ENOENT) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700534 ALOGE("Failed to delete counterSet data(uid=%u, tag=%u): %s\n", uid, tag,
Steven Morelanda3074542020-01-13 14:13:44 -0800535 strerror(res.error().code()));
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800536 }
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700537
Steven Morelanda3074542020-01-13 14:13:44 -0800538 auto deleteAppUidStatsEntry = [uid](const uint32_t& key,
539 BpfMap<uint32_t, StatsValue>& map) -> base::Result<void> {
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700540 if (key == uid) {
Steven Morelanda3074542020-01-13 14:13:44 -0800541 auto res = map.deleteValue(key);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900542 if (res.ok() || (res.error().code() == ENOENT)) {
Steven Morelanda3074542020-01-13 14:13:44 -0800543 return {};
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700544 }
Steven Morelanda3074542020-01-13 14:13:44 -0800545 ALOGE("Failed to delete data(uid=%u): %s", key, strerror(res.error().code()));
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700546 }
Steven Morelanda3074542020-01-13 14:13:44 -0800547 return {};
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700548 };
Steven Morelanda3074542020-01-13 14:13:44 -0800549 mAppUidStatsMap.iterate(deleteAppUidStatsEntry);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700550 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700551}
552
Chenbo Feng7e974052018-02-28 22:57:21 -0800553int TrafficController::addInterface(const char* name, uint32_t ifaceIndex) {
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800554 if (!mBpfEnabled) return 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800555
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700556 IfaceValue iface;
Chenbo Feng7e974052018-02-28 22:57:21 -0800557 if (ifaceIndex == 0) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700558 ALOGE("Unknown interface %s(%d)", name, ifaceIndex);
Chenbo Feng7e974052018-02-28 22:57:21 -0800559 return -1;
560 }
561
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700562 strlcpy(iface.name, name, sizeof(IfaceValue));
563 Status res = mIfaceIndexNameMap.writeValue(ifaceIndex, iface, BPF_ANY);
564 if (!isOk(res)) {
565 ALOGE("Failed to add iface %s(%d): %s", name, ifaceIndex, strerror(res.code()));
566 return -res.code();
Chenbo Feng7e974052018-02-28 22:57:21 -0800567 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700568 return 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800569}
570
Chenbo Feng703798e2018-06-15 17:07:59 -0700571Status TrafficController::updateOwnerMapEntry(UidOwnerMatchType match, uid_t uid, FirewallRule rule,
572 FirewallType type) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700573 std::lock_guard guard(mMutex);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700574 if ((rule == ALLOW && type == WHITELIST) || (rule == DENY && type == BLACKLIST)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100575 RETURN_IF_NOT_OK(addRule(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700576 } else if ((rule == ALLOW && type == BLACKLIST) || (rule == DENY && type == WHITELIST)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100577 RETURN_IF_NOT_OK(removeRule(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700578 } else {
579 //Cannot happen.
Rubin Xuec27ff22019-01-08 21:33:03 +0000580 return statusFromErrno(EINVAL, "");
Chenbo Feng89c12f12018-03-21 10:29:18 -0700581 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700582 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700583}
584
Chenbo Feng703798e2018-06-15 17:07:59 -0700585UidOwnerMatchType TrafficController::jumpOpToMatch(BandwidthController::IptJumpOp jumpHandling) {
Chenbo Feng95892f32018-06-07 14:52:02 -0700586 switch (jumpHandling) {
587 case BandwidthController::IptJumpReject:
Chenbo Feng703798e2018-06-15 17:07:59 -0700588 return PENALTY_BOX_MATCH;
Chenbo Feng95892f32018-06-07 14:52:02 -0700589 case BandwidthController::IptJumpReturn:
Chenbo Feng703798e2018-06-15 17:07:59 -0700590 return HAPPY_BOX_MATCH;
Chenbo Feng95892f32018-06-07 14:52:02 -0700591 case BandwidthController::IptJumpNoAdd:
592 return NO_MATCH;
593 }
594}
595
Rubin Xu5ca8e802019-04-05 11:50:32 +0100596Status TrafficController::removeRule(BpfMap<uint32_t, UidOwnerValue>& map, uint32_t uid,
597 UidOwnerMatchType match) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700598 auto oldMatch = map.readValue(uid);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900599 if (oldMatch.ok()) {
Nick Desaulniers6b357502019-10-11 09:26:44 -0700600 UidOwnerValue newMatch = {
601 .iif = (match == IIF_MATCH) ? 0 : oldMatch.value().iif,
602 .rule = static_cast<uint8_t>(oldMatch.value().rule & ~match),
603 };
Rubin Xuec27ff22019-01-08 21:33:03 +0000604 if (newMatch.rule == 0) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700605 RETURN_IF_NOT_OK(map.deleteValue(uid));
606 } else {
607 RETURN_IF_NOT_OK(map.writeValue(uid, newMatch, BPF_ANY));
608 }
609 } else {
610 return statusFromErrno(ENOENT, StringPrintf("uid: %u does not exist in map", uid));
611 }
612 return netdutils::status::ok;
613}
614
Rubin Xu5ca8e802019-04-05 11:50:32 +0100615Status TrafficController::addRule(BpfMap<uint32_t, UidOwnerValue>& map, uint32_t uid,
616 UidOwnerMatchType match, uint32_t iif) {
Rubin Xuec27ff22019-01-08 21:33:03 +0000617 // iif should be non-zero if and only if match == MATCH_IIF
618 if (match == IIF_MATCH && iif == 0) {
619 return statusFromErrno(EINVAL, "Interface match must have nonzero interface index");
620 } else if (match != IIF_MATCH && iif != 0) {
621 return statusFromErrno(EINVAL, "Non-interface match must have zero interface index");
622 }
Chenbo Feng703798e2018-06-15 17:07:59 -0700623 auto oldMatch = map.readValue(uid);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900624 if (oldMatch.ok()) {
Nick Desaulniers6b357502019-10-11 09:26:44 -0700625 UidOwnerValue newMatch = {
626 .iif = iif ? iif : oldMatch.value().iif,
627 .rule = static_cast<uint8_t>(oldMatch.value().rule | match),
628 };
Rubin Xuec27ff22019-01-08 21:33:03 +0000629 RETURN_IF_NOT_OK(map.writeValue(uid, newMatch, BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700630 } else {
Nick Desaulniers6b357502019-10-11 09:26:44 -0700631 UidOwnerValue newMatch = {
632 .iif = iif,
633 .rule = static_cast<uint8_t>(match),
634 };
Rubin Xuec27ff22019-01-08 21:33:03 +0000635 RETURN_IF_NOT_OK(map.writeValue(uid, newMatch, BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700636 }
637 return netdutils::status::ok;
638}
639
640Status TrafficController::updateUidOwnerMap(const std::vector<std::string>& appStrUids,
641 BandwidthController::IptJumpOp jumpHandling,
642 BandwidthController::IptOp op) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700643 std::lock_guard guard(mMutex);
Chenbo Feng703798e2018-06-15 17:07:59 -0700644 UidOwnerMatchType match = jumpOpToMatch(jumpHandling);
645 if (match == NO_MATCH) {
646 return statusFromErrno(
647 EINVAL, StringPrintf("invalid IptJumpOp: %d, command: %d", jumpHandling, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700648 }
649 for (const auto& appStrUid : appStrUids) {
650 char* endPtr;
651 long uid = strtol(appStrUid.c_str(), &endPtr, 10);
652 if ((errno == ERANGE && (uid == LONG_MAX || uid == LONG_MIN)) ||
653 (endPtr == appStrUid.c_str()) || (*endPtr != '\0')) {
654 return statusFromErrno(errno, "invalid uid string:" + appStrUid);
655 }
656
Chenbo Feng95892f32018-06-07 14:52:02 -0700657 if (op == BandwidthController::IptOpDelete) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100658 RETURN_IF_NOT_OK(removeRule(mUidOwnerMap, uid, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700659 } else if (op == BandwidthController::IptOpInsert) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100660 RETURN_IF_NOT_OK(addRule(mUidOwnerMap, uid, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700661 } else {
662 // Cannot happen.
Chenbo Feng703798e2018-06-15 17:07:59 -0700663 return statusFromErrno(EINVAL, StringPrintf("invalid IptOp: %d, %d", op, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700664 }
665 }
666 return netdutils::status::ok;
667}
668
Chenbo Feng89c12f12018-03-21 10:29:18 -0700669int TrafficController::changeUidOwnerRule(ChildChain chain, uid_t uid, FirewallRule rule,
670 FirewallType type) {
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800671 if (!mBpfEnabled) {
Chenbo Feng89c12f12018-03-21 10:29:18 -0700672 ALOGE("bpf is not set up, should use iptables rule");
673 return -ENOSYS;
674 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700675 Status res;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700676 switch (chain) {
677 case DOZABLE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700678 res = updateOwnerMapEntry(DOZABLE_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700679 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700680 case STANDBY:
Chenbo Feng703798e2018-06-15 17:07:59 -0700681 res = updateOwnerMapEntry(STANDBY_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700682 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700683 case POWERSAVE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700684 res = updateOwnerMapEntry(POWERSAVE_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700685 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700686 case NONE:
687 default:
688 return -EINVAL;
689 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700690 if (!isOk(res)) {
691 ALOGE("change uid(%u) rule of %d failed: %s, rule: %d, type: %d", uid, chain,
692 res.msg().c_str(), rule, type);
693 return -res.code();
694 }
695 return 0;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700696}
697
Rubin Xu5ca8e802019-04-05 11:50:32 +0100698Status TrafficController::replaceRulesInMap(const UidOwnerMatchType match,
699 const std::vector<int32_t>& uids) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700700 std::lock_guard guard(mMutex);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700701 std::set<int32_t> uidSet(uids.begin(), uids.end());
702 std::vector<uint32_t> uidsToDelete;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700703 auto getUidsToDelete = [&uidsToDelete, &uidSet](const uint32_t& key,
Rubin Xuec27ff22019-01-08 21:33:03 +0000704 const BpfMap<uint32_t, UidOwnerValue>&) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700705 if (uidSet.find((int32_t) key) == uidSet.end()) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700706 uidsToDelete.push_back(key);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700707 }
Steven Morelanda3074542020-01-13 14:13:44 -0800708 return base::Result<void>();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700709 };
Chenbo Feng703798e2018-06-15 17:07:59 -0700710 RETURN_IF_NOT_OK(mUidOwnerMap.iterate(getUidsToDelete));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700711
712 for(auto uid : uidsToDelete) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100713 RETURN_IF_NOT_OK(removeRule(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700714 }
715
716 for (auto uid : uids) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100717 RETURN_IF_NOT_OK(addRule(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700718 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700719 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700720}
721
Rubin Xuec27ff22019-01-08 21:33:03 +0000722Status TrafficController::addUidInterfaceRules(const int iif,
723 const std::vector<int32_t>& uidsToAdd) {
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800724 if (!mBpfEnabled) {
Rubin Xuec27ff22019-01-08 21:33:03 +0000725 ALOGW("UID ingress interface filtering not possible without BPF owner match");
726 return statusFromErrno(EOPNOTSUPP, "eBPF not supported");
727 }
728 if (!iif) {
729 return statusFromErrno(EINVAL, "Interface rule must specify interface");
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 : uidsToAdd) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100734 netdutils::Status result = addRule(mUidOwnerMap, uid, IIF_MATCH, iif);
Rubin Xuec27ff22019-01-08 21:33:03 +0000735 if (!isOk(result)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100736 ALOGW("addRule failed(%d): uid=%d iif=%d", result.code(), uid, iif);
Rubin Xuec27ff22019-01-08 21:33:03 +0000737 }
738 }
739 return netdutils::status::ok;
740}
741
742Status TrafficController::removeUidInterfaceRules(const std::vector<int32_t>& uidsToDelete) {
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800743 if (!mBpfEnabled) {
Rubin Xuec27ff22019-01-08 21:33:03 +0000744 ALOGW("UID ingress interface filtering not possible without BPF owner match");
745 return statusFromErrno(EOPNOTSUPP, "eBPF not supported");
746 }
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700747 std::lock_guard guard(mMutex);
Rubin Xuec27ff22019-01-08 21:33:03 +0000748
749 for (auto uid : uidsToDelete) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100750 netdutils::Status result = removeRule(mUidOwnerMap, uid, IIF_MATCH);
Rubin Xuec27ff22019-01-08 21:33:03 +0000751 if (!isOk(result)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100752 ALOGW("removeRule failed(%d): uid=%d", result.code(), uid);
Rubin Xuec27ff22019-01-08 21:33:03 +0000753 }
754 }
755 return netdutils::status::ok;
756}
757
Chenbo Feng89c12f12018-03-21 10:29:18 -0700758int TrafficController::replaceUidOwnerMap(const std::string& name, bool isWhitelist,
759 const std::vector<int32_t>& uids) {
Chenbo Feng89c12f12018-03-21 10:29:18 -0700760 FirewallRule rule;
761 FirewallType type;
762 if (isWhitelist) {
763 type = WHITELIST;
764 rule = ALLOW;
765 } else {
766 type = BLACKLIST;
767 rule = DENY;
768 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700769 Status res;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700770 if (!name.compare(FirewallController::LOCAL_DOZABLE)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100771 res = replaceRulesInMap(DOZABLE_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700772 } else if (!name.compare(FirewallController::LOCAL_STANDBY)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100773 res = replaceRulesInMap(STANDBY_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700774 } else if (!name.compare(FirewallController::LOCAL_POWERSAVE)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100775 res = replaceRulesInMap(POWERSAVE_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700776 } else {
777 ALOGE("unknown chain name: %s", name.c_str());
778 return -EINVAL;
779 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700780 if (!isOk(res)) {
781 ALOGE("Failed to clean up chain: %s: %s", name.c_str(), res.msg().c_str());
782 return -res.code();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700783 }
784 return 0;
785}
786
787int TrafficController::toggleUidOwnerMap(ChildChain chain, bool enable) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700788 std::lock_guard guard(mMutex);
Chenbo Fengf434e862018-06-27 14:08:39 -0700789 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Chenbo Feng703798e2018-06-15 17:07:59 -0700790 auto oldConfiguration = mConfigurationMap.readValue(key);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900791 if (!oldConfiguration.ok()) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700792 ALOGE("Cannot read the old configuration from map: %s",
Steven Morelanda3074542020-01-13 14:13:44 -0800793 oldConfiguration.error().message().c_str());
794 return -oldConfiguration.error().code();
Chenbo Feng703798e2018-06-15 17:07:59 -0700795 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700796 Status res;
Chenbo Feng703798e2018-06-15 17:07:59 -0700797 BpfConfig newConfiguration;
798 uint8_t match;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700799 switch (chain) {
800 case DOZABLE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700801 match = DOZABLE_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700802 break;
803 case STANDBY:
Chenbo Feng703798e2018-06-15 17:07:59 -0700804 match = STANDBY_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700805 break;
806 case POWERSAVE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700807 match = POWERSAVE_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700808 break;
809 default:
810 return -EINVAL;
811 }
Chenbo Feng703798e2018-06-15 17:07:59 -0700812 newConfiguration =
813 enable ? (oldConfiguration.value() | match) : (oldConfiguration.value() & (~match));
814 res = mConfigurationMap.writeValue(key, newConfiguration, BPF_EXIST);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700815 if (!isOk(res)) {
816 ALOGE("Failed to toggleUidOwnerMap(%d): %s", chain, res.msg().c_str());
Chenbo Feng89c12f12018-03-21 10:29:18 -0700817 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700818 return -res.code();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700819}
820
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800821bool TrafficController::getBpfEnabled() {
822 return mBpfEnabled;
Chenbo Feng07d43fe2017-12-21 14:38:51 -0800823}
824
Chenbo Feng873ae142019-04-10 12:26:06 -0700825Status TrafficController::swapActiveStatsMap() {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700826 std::lock_guard guard(mMutex);
Chenbo Feng873ae142019-04-10 12:26:06 -0700827
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800828 if (!mBpfEnabled) {
Chenbo Feng873ae142019-04-10 12:26:06 -0700829 return statusFromErrno(EOPNOTSUPP, "This device doesn't have eBPF support");
830 }
831
832 uint32_t key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
833 auto oldConfiguration = mConfigurationMap.readValue(key);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900834 if (!oldConfiguration.ok()) {
Chenbo Feng873ae142019-04-10 12:26:06 -0700835 ALOGE("Cannot read the old configuration from map: %s",
Steven Morelanda3074542020-01-13 14:13:44 -0800836 oldConfiguration.error().message().c_str());
837 return Status(oldConfiguration.error().code(), oldConfiguration.error().message());
Chenbo Feng873ae142019-04-10 12:26:06 -0700838 }
839
840 // Write to the configuration map to inform the kernel eBPF program to switch
841 // from using one map to the other. Use flag BPF_EXIST here since the map should
842 // be already populated in initMaps.
843 uint8_t newConfigure = (oldConfiguration.value() == SELECT_MAP_A) ? SELECT_MAP_B : SELECT_MAP_A;
Steven Morelanda3074542020-01-13 14:13:44 -0800844 auto res = mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, newConfigure,
845 BPF_EXIST);
Bernie Innocenti615fd742020-02-06 03:55:09 +0900846 if (!res.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -0800847 ALOGE("Failed to toggle the stats map: %s", strerror(res.error().code()));
Chenbo Feng873ae142019-04-10 12:26:06 -0700848 return res;
849 }
850 // After changing the config, we need to make sure all the current running
851 // eBPF programs are finished and all the CPUs are aware of this config change
852 // before we modify the old map. So we do a special hack here to wait for
853 // the kernel to do a synchronize_rcu(). Once the kernel called
854 // synchronize_rcu(), the config we just updated will be available to all cores
855 // and the next eBPF programs triggered inside the kernel will use the new
856 // map configuration. So once this function returns we can safely modify the
857 // old stats map without concerning about race between the kernel and
858 // userspace.
859 int ret = synchronizeKernelRCU();
860 if (ret) {
861 ALOGE("map swap synchronize_rcu() ended with failure: %s", strerror(-ret));
862 return statusFromErrno(-ret, "map swap synchronize_rcu() failed");
863 }
864 return netdutils::status::ok;
865}
866
Chenbo Feng48eaed32018-12-26 17:40:21 -0800867void TrafficController::setPermissionForUids(int permission, const std::vector<uid_t>& uids) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700868 std::lock_guard guard(mMutex);
Chenbo Fengbf660aa2019-02-26 16:12:27 -0800869 if (permission == INetd::PERMISSION_UNINSTALLED) {
870 for (uid_t uid : uids) {
871 // Clean up all permission information for the related uid if all the
872 // packages related to it are uninstalled.
873 mPrivilegedUser.erase(uid);
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800874 if (mBpfEnabled) {
Chenbo Feng97c88db2019-04-24 12:19:16 -0700875 Status ret = mUidPermissionMap.deleteValue(uid);
Maciej Żenczykowski928ea232019-08-20 17:28:05 -0700876 if (!isOk(ret) && ret.code() != ENOENT) {
Chenbo Feng97c88db2019-04-24 12:19:16 -0700877 ALOGE("Failed to clean up the permission for %u: %s", uid,
878 strerror(ret.code()));
879 }
880 }
Chenbo Fengbf660aa2019-02-26 16:12:27 -0800881 }
882 return;
883 }
884
Chenbo Feng48eaed32018-12-26 17:40:21 -0800885 bool privileged = (permission & INetd::PERMISSION_UPDATE_DEVICE_STATS);
886
887 for (uid_t uid : uids) {
Chenbo Feng97c88db2019-04-24 12:19:16 -0700888 if (privileged) {
889 mPrivilegedUser.insert(uid);
890 } else {
891 mPrivilegedUser.erase(uid);
892 }
893
894 // Skip the bpf map operation if not supported.
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800895 if (!mBpfEnabled) {
Chenbo Feng97c88db2019-04-24 12:19:16 -0700896 continue;
897 }
Chenbo Feng527908a2019-04-02 20:14:11 -0700898 // The map stores all the permissions that the UID has, except if the only permission
899 // the UID has is the INTERNET permission, then the UID should not appear in the map.
900 if (permission != INetd::PERMISSION_INTERNET) {
Chenbo Fengbf660aa2019-02-26 16:12:27 -0800901 Status ret = mUidPermissionMap.writeValue(uid, permission, BPF_ANY);
Chenbo Feng48eaed32018-12-26 17:40:21 -0800902 if (!isOk(ret)) {
Chenbo Feng527908a2019-04-02 20:14:11 -0700903 ALOGE("Failed to set permission: %s of uid(%u) to permission map: %s",
904 UidPermissionTypeToString(permission).c_str(), uid, strerror(ret.code()));
Chenbo Feng48eaed32018-12-26 17:40:21 -0800905 }
906 } else {
907 Status ret = mUidPermissionMap.deleteValue(uid);
908 if (!isOk(ret) && ret.code() != ENOENT) {
Chenbo Feng527908a2019-04-02 20:14:11 -0700909 ALOGE("Failed to remove uid %u from permission map: %s", uid, strerror(ret.code()));
Chenbo Feng48eaed32018-12-26 17:40:21 -0800910 }
911 }
Chenbo Feng48eaed32018-12-26 17:40:21 -0800912 }
913}
914
Chenbo Fengef297172018-03-26 10:53:33 -0700915std::string getProgramStatus(const char *path) {
916 int ret = access(path, R_OK);
917 if (ret == 0) {
918 return StringPrintf("OK");
919 }
920 if (ret != 0 && errno == ENOENT) {
921 return StringPrintf("program is missing at: %s", path);
922 }
923 return StringPrintf("check Program %s error: %s", path, strerror(errno));
924}
925
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700926std::string getMapStatus(const base::unique_fd& map_fd, const char* path) {
Chenbo Fengef297172018-03-26 10:53:33 -0700927 if (map_fd.get() < 0) {
928 return StringPrintf("map fd lost");
929 }
930 if (access(path, F_OK) != 0) {
931 return StringPrintf("map not pinned to location: %s", path);
932 }
933 return StringPrintf("OK");
934}
935
Bernie Innocentia5161a02019-01-30 22:40:53 +0900936// NOLINTNEXTLINE(google-runtime-references): grandfathered pass by non-const reference
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900937void dumpBpfMap(const std::string& mapName, DumpWriter& dw, const std::string& header) {
Chenbo Fengef297172018-03-26 10:53:33 -0700938 dw.blankline();
939 dw.println("%s:", mapName.c_str());
Erik Klineb31fd692018-06-06 20:50:11 +0900940 if (!header.empty()) {
941 dw.println(header);
Chenbo Fengef297172018-03-26 10:53:33 -0700942 }
943}
944
945const String16 TrafficController::DUMP_KEYWORD = String16("trafficcontroller");
946
947void TrafficController::dump(DumpWriter& dw, bool verbose) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700948 std::lock_guard guard(mMutex);
Erik Klineb31fd692018-06-06 20:50:11 +0900949 ScopedIndent indentTop(dw);
Chenbo Fengef297172018-03-26 10:53:33 -0700950 dw.println("TrafficController");
951
Erik Klineb31fd692018-06-06 20:50:11 +0900952 ScopedIndent indentPreBpfModule(dw);
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800953 dw.println("BPF module status: %s", mBpfEnabled ? "enabled" : "disabled");
954 dw.println("BPF support level: %s", BpfLevelToString(getBpfSupportLevel()).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700955
Maciej Żenczykowski3d7c9662020-02-11 17:11:26 -0800956 if (!mBpfEnabled) {
Chenbo Fengef297172018-03-26 10:53:33 -0700957 return;
Erik Klineb31fd692018-06-06 20:50:11 +0900958 }
Chenbo Fengef297172018-03-26 10:53:33 -0700959
960 dw.blankline();
961 dw.println("mCookieTagMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700962 getMapStatus(mCookieTagMap.getMap(), COOKIE_TAG_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700963 dw.println("mUidCounterSetMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700964 getMapStatus(mUidCounterSetMap.getMap(), UID_COUNTERSET_MAP_PATH).c_str());
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700965 dw.println("mAppUidStatsMap status: %s",
966 getMapStatus(mAppUidStatsMap.getMap(), APP_UID_STATS_MAP_PATH).c_str());
Chenbo Fengf434e862018-06-27 14:08:39 -0700967 dw.println("mStatsMapA status: %s",
968 getMapStatus(mStatsMapA.getMap(), STATS_MAP_A_PATH).c_str());
969 dw.println("mStatsMapB status: %s",
970 getMapStatus(mStatsMapB.getMap(), STATS_MAP_B_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700971 dw.println("mIfaceIndexNameMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700972 getMapStatus(mIfaceIndexNameMap.getMap(), IFACE_INDEX_NAME_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700973 dw.println("mIfaceStatsMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700974 getMapStatus(mIfaceStatsMap.getMap(), IFACE_STATS_MAP_PATH).c_str());
Chenbo Feng703798e2018-06-15 17:07:59 -0700975 dw.println("mConfigurationMap status: %s",
976 getMapStatus(mConfigurationMap.getMap(), CONFIGURATION_MAP_PATH).c_str());
977 dw.println("mUidOwnerMap status: %s",
978 getMapStatus(mUidOwnerMap.getMap(), UID_OWNER_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700979
980 dw.blankline();
981 dw.println("Cgroup ingress program status: %s",
982 getProgramStatus(BPF_INGRESS_PROG_PATH).c_str());
983 dw.println("Cgroup egress program status: %s", getProgramStatus(BPF_EGRESS_PROG_PATH).c_str());
984 dw.println("xt_bpf ingress program status: %s",
985 getProgramStatus(XT_BPF_INGRESS_PROG_PATH).c_str());
986 dw.println("xt_bpf egress program status: %s",
987 getProgramStatus(XT_BPF_EGRESS_PROG_PATH).c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700988 dw.println("xt_bpf bandwidth whitelist program status: %s",
989 getProgramStatus(XT_BPF_WHITELIST_PROG_PATH).c_str());
990 dw.println("xt_bpf bandwidth blacklist program status: %s",
991 getProgramStatus(XT_BPF_BLACKLIST_PROG_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700992
Erik Klineb31fd692018-06-06 20:50:11 +0900993 if (!verbose) {
994 return;
995 }
Chenbo Fengef297172018-03-26 10:53:33 -0700996
997 dw.blankline();
998 dw.println("BPF map content:");
999
Erik Klineb31fd692018-06-06 20:50:11 +09001000 ScopedIndent indentForMapContent(dw);
Chenbo Fengef297172018-03-26 10:53:33 -07001001
1002 // Print CookieTagMap content.
1003 dumpBpfMap("mCookieTagMap", dw, "");
Maciej Żenczykowski11ec78b2019-12-30 06:39:32 -08001004 const auto printCookieTagInfo = [&dw](const uint64_t& key, const UidTagValue& value,
1005 const BpfMap<uint64_t, UidTagValue>&) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001006 dw.println("cookie=%" PRIu64 " tag=0x%x uid=%u", key, value.tag, value.uid);
Steven Morelanda3074542020-01-13 14:13:44 -08001007 return base::Result<void>();
Chenbo Fengef297172018-03-26 10:53:33 -07001008 };
Steven Morelanda3074542020-01-13 14:13:44 -08001009 base::Result<void> res = mCookieTagMap.iterateWithValue(printCookieTagInfo);
Bernie Innocenti615fd742020-02-06 03:55:09 +09001010 if (!res.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -08001011 dw.println("mCookieTagMap print end with error: %s", res.error().message().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001012 }
1013
1014 // Print UidCounterSetMap Content
1015 dumpBpfMap("mUidCounterSetMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001016 const auto printUidInfo = [&dw](const uint32_t& key, const uint8_t& value,
1017 const BpfMap<uint32_t, uint8_t>&) {
1018 dw.println("%u %u", key, value);
Steven Morelanda3074542020-01-13 14:13:44 -08001019 return base::Result<void>();
Chenbo Fengef297172018-03-26 10:53:33 -07001020 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001021 res = mUidCounterSetMap.iterateWithValue(printUidInfo);
Bernie Innocenti615fd742020-02-06 03:55:09 +09001022 if (!res.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -08001023 dw.println("mUidCounterSetMap print end with error: %s", res.error().message().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001024 }
1025
Chenbo Fengbc4a15f2018-05-11 19:15:15 -07001026 // Print AppUidStatsMap content
1027 std::string appUidStatsHeader = StringPrintf("uid rxBytes rxPackets txBytes txPackets");
1028 dumpBpfMap("mAppUidStatsMap:", dw, appUidStatsHeader);
1029 auto printAppUidStatsInfo = [&dw](const uint32_t& key, const StatsValue& value,
1030 const BpfMap<uint32_t, StatsValue>&) {
1031 dw.println("%u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, value.rxBytes,
1032 value.rxPackets, value.txBytes, value.txPackets);
Steven Morelanda3074542020-01-13 14:13:44 -08001033 return base::Result<void>();
Chenbo Fengbc4a15f2018-05-11 19:15:15 -07001034 };
1035 res = mAppUidStatsMap.iterateWithValue(printAppUidStatsInfo);
Bernie Innocenti615fd742020-02-06 03:55:09 +09001036 if (!res.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -08001037 dw.println("mAppUidStatsMap print end with error: %s", res.error().message().c_str());
Chenbo Fengbc4a15f2018-05-11 19:15:15 -07001038 }
1039
Chenbo Fengef297172018-03-26 10:53:33 -07001040 // Print uidStatsMap content
1041 std::string statsHeader = StringPrintf("ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes"
1042 " rxPackets txBytes txPackets");
Chenbo Fengf434e862018-06-27 14:08:39 -07001043 dumpBpfMap("mStatsMapA", dw, statsHeader);
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001044 const auto printStatsInfo = [&dw, this](const StatsKey& key, const StatsValue& value,
1045 const BpfMap<StatsKey, StatsValue>&) {
1046 uint32_t ifIndex = key.ifaceIndex;
1047 auto ifname = mIfaceIndexNameMap.readValue(ifIndex);
Bernie Innocenti615fd742020-02-06 03:55:09 +09001048 if (!ifname.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -08001049 ifname = IfaceValue{"unknown"};
Chenbo Fengef297172018-03-26 10:53:33 -07001050 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001051 dw.println("%u %s 0x%x %u %u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, ifIndex,
1052 ifname.value().name, key.tag, key.uid, key.counterSet, value.rxBytes,
1053 value.rxPackets, value.txBytes, value.txPackets);
Steven Morelanda3074542020-01-13 14:13:44 -08001054 return base::Result<void>();
Chenbo Fengef297172018-03-26 10:53:33 -07001055 };
Chenbo Fengf434e862018-06-27 14:08:39 -07001056 res = mStatsMapA.iterateWithValue(printStatsInfo);
Bernie Innocenti615fd742020-02-06 03:55:09 +09001057 if (!res.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -08001058 dw.println("mStatsMapA print end with error: %s", res.error().message().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001059 }
1060
1061 // Print TagStatsMap content.
Chenbo Fengf434e862018-06-27 14:08:39 -07001062 dumpBpfMap("mStatsMapB", dw, statsHeader);
1063 res = mStatsMapB.iterateWithValue(printStatsInfo);
Bernie Innocenti615fd742020-02-06 03:55:09 +09001064 if (!res.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -08001065 dw.println("mStatsMapB print end with error: %s", res.error().message().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001066 }
1067
1068 // Print ifaceIndexToNameMap content.
1069 dumpBpfMap("mIfaceIndexNameMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001070 const auto printIfaceNameInfo = [&dw](const uint32_t& key, const IfaceValue& value,
1071 const BpfMap<uint32_t, IfaceValue>&) {
1072 const char* ifname = value.name;
1073 dw.println("ifaceIndex=%u ifaceName=%s", key, ifname);
Steven Morelanda3074542020-01-13 14:13:44 -08001074 return base::Result<void>();
Chenbo Fengef297172018-03-26 10:53:33 -07001075 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001076 res = mIfaceIndexNameMap.iterateWithValue(printIfaceNameInfo);
Bernie Innocenti615fd742020-02-06 03:55:09 +09001077 if (!res.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -08001078 dw.println("mIfaceIndexNameMap print end with error: %s", res.error().message().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001079 }
1080
1081 // Print ifaceStatsMap content
1082 std::string ifaceStatsHeader = StringPrintf("ifaceIndex ifaceName rxBytes rxPackets txBytes"
1083 " txPackets");
1084 dumpBpfMap("mIfaceStatsMap:", dw, ifaceStatsHeader);
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001085 const auto printIfaceStatsInfo = [&dw, this](const uint32_t& key, const StatsValue& value,
1086 const BpfMap<uint32_t, StatsValue>&) {
1087 auto ifname = mIfaceIndexNameMap.readValue(key);
Bernie Innocenti615fd742020-02-06 03:55:09 +09001088 if (!ifname.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -08001089 ifname = IfaceValue{"unknown"};
Chenbo Fengef297172018-03-26 10:53:33 -07001090 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001091 dw.println("%u %s %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, ifname.value().name,
1092 value.rxBytes, value.rxPackets, value.txBytes, value.txPackets);
Steven Morelanda3074542020-01-13 14:13:44 -08001093 return base::Result<void>();
Chenbo Fengef297172018-03-26 10:53:33 -07001094 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001095 res = mIfaceStatsMap.iterateWithValue(printIfaceStatsInfo);
Bernie Innocenti615fd742020-02-06 03:55:09 +09001096 if (!res.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -08001097 dw.println("mIfaceStatsMap print end with error: %s", res.error().message().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001098 }
1099
Chenbo Feng703798e2018-06-15 17:07:59 -07001100 dw.blankline();
Chenbo Fengef297172018-03-26 10:53:33 -07001101
Chenbo Fengf434e862018-06-27 14:08:39 -07001102 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Chenbo Feng703798e2018-06-15 17:07:59 -07001103 auto configuration = mConfigurationMap.readValue(key);
Bernie Innocenti615fd742020-02-06 03:55:09 +09001104 if (configuration.ok()) {
Lorenzo Colittic2677362019-06-26 20:01:35 +09001105 dw.println("current ownerMatch configuration: %d%s", configuration.value(),
1106 uidMatchTypeToString(configuration.value()).c_str());
Chenbo Feng703798e2018-06-15 17:07:59 -07001107 } else {
Chenbo Fengf434e862018-06-27 14:08:39 -07001108 dw.println("mConfigurationMap read ownerMatch configure failed with error: %s",
Steven Morelanda3074542020-01-13 14:13:44 -08001109 configuration.error().message().c_str());
Chenbo Fengf434e862018-06-27 14:08:39 -07001110 }
Lorenzo Colittic2677362019-06-26 20:01:35 +09001111
Chenbo Fengf434e862018-06-27 14:08:39 -07001112 key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
1113 configuration = mConfigurationMap.readValue(key);
Bernie Innocenti615fd742020-02-06 03:55:09 +09001114 if (configuration.ok()) {
Lorenzo Colittic2677362019-06-26 20:01:35 +09001115 const char* statsMapDescription = "???";
1116 switch (configuration.value()) {
1117 case SELECT_MAP_A:
1118 statsMapDescription = "SELECT_MAP_A";
1119 break;
1120 case SELECT_MAP_B:
1121 statsMapDescription = "SELECT_MAP_B";
1122 break;
1123 // No default clause, so if we ever add a third map, this code will fail to build.
1124 }
1125 dw.println("current statsMap configuration: %d %s", configuration.value(),
1126 statsMapDescription);
Chenbo Fengf434e862018-06-27 14:08:39 -07001127 } else {
1128 dw.println("mConfigurationMap read stats map configure failed with error: %s",
Steven Morelanda3074542020-01-13 14:13:44 -08001129 configuration.error().message().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001130 }
Chenbo Feng703798e2018-06-15 17:07:59 -07001131 dumpBpfMap("mUidOwnerMap", dw, "");
Rubin Xuec27ff22019-01-08 21:33:03 +00001132 const auto printUidMatchInfo = [&dw, this](const uint32_t& key, const UidOwnerValue& value,
1133 const BpfMap<uint32_t, UidOwnerValue>&) {
1134 if (value.rule & IIF_MATCH) {
1135 auto ifname = mIfaceIndexNameMap.readValue(value.iif);
Bernie Innocenti615fd742020-02-06 03:55:09 +09001136 if (ifname.ok()) {
Rubin Xuec27ff22019-01-08 21:33:03 +00001137 dw.println("%u %s %s", key, uidMatchTypeToString(value.rule).c_str(),
1138 ifname.value().name);
1139 } else {
1140 dw.println("%u %s %u", key, uidMatchTypeToString(value.rule).c_str(), value.iif);
1141 }
1142 } else {
1143 dw.println("%u %s", key, uidMatchTypeToString(value.rule).c_str());
1144 }
Steven Morelanda3074542020-01-13 14:13:44 -08001145 return base::Result<void>();
Chenbo Feng703798e2018-06-15 17:07:59 -07001146 };
1147 res = mUidOwnerMap.iterateWithValue(printUidMatchInfo);
Bernie Innocenti615fd742020-02-06 03:55:09 +09001148 if (!res.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -08001149 dw.println("mUidOwnerMap print end with error: %s", res.error().message().c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -07001150 }
Chenbo Feng48eaed32018-12-26 17:40:21 -08001151 dumpBpfMap("mUidPermissionMap", dw, "");
Yi Kong3d82f382019-10-01 21:52:14 -07001152 const auto printUidPermissionInfo = [&dw](const uint32_t& key, const int& value,
Chenbo Feng48eaed32018-12-26 17:40:21 -08001153 const BpfMap<uint32_t, uint8_t>&) {
1154 dw.println("%u %s", key, UidPermissionTypeToString(value).c_str());
Steven Morelanda3074542020-01-13 14:13:44 -08001155 return base::Result<void>();
Chenbo Feng48eaed32018-12-26 17:40:21 -08001156 };
1157 res = mUidPermissionMap.iterateWithValue(printUidPermissionInfo);
Bernie Innocenti615fd742020-02-06 03:55:09 +09001158 if (!res.ok()) {
Steven Morelanda3074542020-01-13 14:13:44 -08001159 dw.println("mUidPermissionMap print end with error: %s", res.error().message().c_str());
Chenbo Feng48eaed32018-12-26 17:40:21 -08001160 }
1161
1162 dumpBpfMap("mPrivilegedUser", dw, "");
1163 for (uid_t uid : mPrivilegedUser) {
1164 dw.println("%u ALLOW_UPDATE_DEVICE_STATS", (uint32_t)uid);
1165 }
Chenbo Fengef297172018-03-26 10:53:33 -07001166}
1167
Chenbo Fengf2759682017-10-10 17:31:57 -07001168} // namespace net
1169} // namespace android