blob: 1f3b557f86f3a31bb1a727dd92469f72d6b43b64 [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>
Chenbo Feng05393d82018-01-09 15:18:43 -080041#include <logwrap/logwrap.h>
Chenbo Fengc10a8a42017-12-15 13:56:33 -080042#include <netdutils/StatusOr.h>
Chenbo Fengf2759682017-10-10 17:31:57 -070043
Chenbo Feng116d0552017-12-04 17:25:19 -080044#include <netdutils/Misc.h>
45#include <netdutils/Syscalls.h>
Suren Baghdasaryane072a3c2019-01-16 14:36:07 -080046#include <processgroup/processgroup.h>
Chenbo Fengf2759682017-10-10 17:31:57 -070047#include "TrafficController.h"
Chenbo Feng4f6c2372018-04-26 10:37:55 -070048#include "bpf/BpfMap.h"
Chenbo Feng116d0552017-12-04 17:25:19 -080049
Chenbo Feng89c12f12018-03-21 10:29:18 -070050#include "FirewallController.h"
Chenbo Feng7e974052018-02-28 22:57:21 -080051#include "InterfaceController.h"
Chenbo Feng116d0552017-12-04 17:25:19 -080052#include "NetlinkListener.h"
Luke Huangb257d612019-03-14 21:19:13 +080053#include "netdutils/DumpWriter.h"
Chenbo Feng33cc1032017-10-23 15:16:37 -070054#include "qtaguid/qtaguid.h"
Chenbo Fengf2759682017-10-10 17:31:57 -070055
Bernie Innocenti7e25ec02018-07-02 19:32:17 +090056using namespace android::bpf; // NOLINT(google-build-using-namespace): grandfathered
Chenbo Fengf2759682017-10-10 17:31:57 -070057
58namespace android {
59namespace net {
60
Chenbo Fengc10a8a42017-12-15 13:56:33 -080061using base::StringPrintf;
62using base::unique_fd;
Luke Huangb257d612019-03-14 21:19:13 +080063using netdutils::DumpWriter;
Chenbo Feng116d0552017-12-04 17:25:19 -080064using netdutils::extract;
Luke Huangb257d612019-03-14 21:19:13 +080065using netdutils::ScopedIndent;
Chenbo Feng116d0552017-12-04 17:25:19 -080066using netdutils::Slice;
67using netdutils::sSyscalls;
Chenbo Fengc10a8a42017-12-15 13:56:33 -080068using netdutils::Status;
69using netdutils::statusFromErrno;
70using netdutils::StatusOr;
Chenbo Feng116d0552017-12-04 17:25:19 -080071using netdutils::status::ok;
Chenbo Fengc10a8a42017-12-15 13:56:33 -080072
Chenbo Feng116d0552017-12-04 17:25:19 -080073constexpr int kSockDiagMsgType = SOCK_DIAG_BY_FAMILY;
74constexpr int kSockDiagDoneMsgType = NLMSG_DONE;
Chenbo Fengb0495132019-04-10 12:54:41 -070075constexpr int PER_UID_STATS_ENTRY_LIMIT = 1024;
Chenbo Feng116d0552017-12-04 17:25:19 -080076
Chenbo Fengbf660aa2019-02-26 16:12:27 -080077static_assert(BPF_PERMISSION_INTERNET == INetd::PERMISSION_INTERNET,
78 "Mismatch between BPF and AIDL permissions: PERMISSION_INTERNET");
79static_assert(BPF_PERMISSION_UPDATE_DEVICE_STATS == INetd::PERMISSION_UPDATE_DEVICE_STATS,
80 "Mismatch between BPF and AIDL permissions: PERMISSION_UPDATE_DEVICE_STATS");
81
Chenbo Feng48eaed32018-12-26 17:40:21 -080082#define FLAG_MSG_TRANS(result, flag, value) \
83 do { \
84 if (value & flag) { \
85 result.append(StringPrintf(" %s", #flag)); \
86 value &= ~flag; \
87 } \
Chenbo Feng703798e2018-06-15 17:07:59 -070088 } while (0)
89
90const std::string uidMatchTypeToString(uint8_t match) {
91 std::string matchType;
Chenbo Feng48eaed32018-12-26 17:40:21 -080092 FLAG_MSG_TRANS(matchType, HAPPY_BOX_MATCH, match);
93 FLAG_MSG_TRANS(matchType, PENALTY_BOX_MATCH, match);
94 FLAG_MSG_TRANS(matchType, DOZABLE_MATCH, match);
95 FLAG_MSG_TRANS(matchType, STANDBY_MATCH, match);
96 FLAG_MSG_TRANS(matchType, POWERSAVE_MATCH, match);
Rubin Xuec27ff22019-01-08 21:33:03 +000097 FLAG_MSG_TRANS(matchType, IIF_MATCH, match);
Chenbo Feng703798e2018-06-15 17:07:59 -070098 if (match) {
99 return StringPrintf("Unknown match: %u", match);
100 }
101 return matchType;
102}
103
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800104bool TrafficController::hasUpdateDeviceStatsPermission(uid_t uid) {
Chenbo Feng3969c262019-03-19 14:53:57 -0700105 // This implementation is the same logic as method ActivityManager#checkComponentPermission.
106 // It implies that the calling uid can never be the same as PER_USER_RANGE.
107 uint32_t appId = uid % PER_USER_RANGE;
108 return ((appId == AID_ROOT) || (appId == AID_SYSTEM) ||
109 mPrivilegedUser.find(appId) != mPrivilegedUser.end());
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800110}
111
Chenbo Feng48eaed32018-12-26 17:40:21 -0800112const std::string UidPermissionTypeToString(uint8_t permission) {
Chenbo Fengbf660aa2019-02-26 16:12:27 -0800113 if (permission == INetd::NO_PERMISSIONS) {
114 return "NO_PERMISSIONS";
115 }
Chenbo Feng527908a2019-04-02 20:14:11 -0700116 if (permission == INetd::PERMISSION_UNINSTALLED) {
117 // This should never appear in the map, complain loudly if it does.
118 return "PERMISSION_UNINSTALLED error!";
119 }
Chenbo Feng48eaed32018-12-26 17:40:21 -0800120 std::string permissionType;
Chenbo Fengbf660aa2019-02-26 16:12:27 -0800121 FLAG_MSG_TRANS(permissionType, BPF_PERMISSION_INTERNET, permission);
122 FLAG_MSG_TRANS(permissionType, BPF_PERMISSION_UPDATE_DEVICE_STATS, permission);
Chenbo Feng48eaed32018-12-26 17:40:21 -0800123 if (permission) {
124 return StringPrintf("Unknown permission: %u", permission);
125 }
126 return permissionType;
127}
128
Chenbo Feng49586642018-08-30 18:01:53 -0700129StatusOr<std::unique_ptr<NetlinkListenerInterface>> TrafficController::makeSkDestroyListener() {
Chenbo Feng116d0552017-12-04 17:25:19 -0800130 const auto& sys = sSyscalls.get();
131 ASSIGN_OR_RETURN(auto event, sys.eventfd(0, EFD_CLOEXEC));
132 const int domain = AF_NETLINK;
133 const int type = SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK;
134 const int protocol = NETLINK_INET_DIAG;
135 ASSIGN_OR_RETURN(auto sock, sys.socket(domain, type, protocol));
136
Lorenzo Colitti436efdb2018-07-26 17:20:57 +0900137 // TODO: if too many sockets are closed too quickly, we can overflow the socket buffer, and
138 // some entries in mCookieTagMap will not be freed. In order to fix this we would need to
139 // periodically dump all sockets and remove the tag entries for sockets that have been closed.
140 // For now, set a large-enough buffer that we can close hundreds of sockets without getting
141 // ENOBUFS and leaking mCookieTagMap entries.
142 int rcvbuf = 512 * 1024;
143 auto ret = sys.setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf));
144 if (!ret.ok()) {
145 ALOGW("Failed to set SkDestroyListener buffer size to %d: %s", rcvbuf, ret.msg().c_str());
146 }
147
Chenbo Feng116d0552017-12-04 17:25:19 -0800148 sockaddr_nl addr = {
149 .nl_family = AF_NETLINK,
150 .nl_groups = 1 << (SKNLGRP_INET_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET_UDP_DESTROY - 1) |
151 1 << (SKNLGRP_INET6_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET6_UDP_DESTROY - 1)};
152 RETURN_IF_NOT_OK(sys.bind(sock, addr));
153
154 const sockaddr_nl kernel = {.nl_family = AF_NETLINK};
155 RETURN_IF_NOT_OK(sys.connect(sock, kernel));
156
157 std::unique_ptr<NetlinkListenerInterface> listener =
Chenbo Feng46296702018-08-23 12:20:22 -0700158 std::make_unique<NetlinkListener>(std::move(event), std::move(sock), "SkDestroyListen");
Chenbo Feng116d0552017-12-04 17:25:19 -0800159
160 return listener;
161}
162
Chenbo Feng89c12f12018-03-21 10:29:18 -0700163Status changeOwnerAndMode(const char* path, gid_t group, const char* debugName, bool netdOnly) {
164 int ret = chown(path, AID_ROOT, group);
165 if (ret != 0) return statusFromErrno(errno, StringPrintf("change %s group failed", debugName));
166
167 if (netdOnly) {
168 ret = chmod(path, S_IRWXU);
169 } else {
170 // Allow both netd and system server to obtain map fd from the path.
171 // chmod doesn't grant permission to all processes in that group to
172 // read/write the bpf map. They still need correct sepolicy to
173 // read/write the map.
Chenbo Fengf434e862018-06-27 14:08:39 -0700174 ret = chmod(path, S_IRWXU | S_IRGRP | S_IWGRP);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700175 }
176 if (ret != 0) return statusFromErrno(errno, StringPrintf("change %s mode failed", debugName));
177 return netdutils::status::ok;
178}
179
Chenbo Feng47dd0732018-12-11 12:23:24 -0800180TrafficController::TrafficController() : mBpfLevel(getBpfSupportLevel()) {}
Chenbo Feng89c12f12018-03-21 10:29:18 -0700181
Chenbo Feng89c12f12018-03-21 10:29:18 -0700182Status TrafficController::initMaps() {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900183 std::lock_guard ownerMapGuard(mOwnerMatchMutex);
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700184 RETURN_IF_NOT_OK(mCookieTagMap.init(COOKIE_TAG_MAP_PATH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700185 RETURN_IF_NOT_OK(changeOwnerAndMode(COOKIE_TAG_MAP_PATH, AID_NET_BW_ACCT, "CookieTagMap",
186 false));
187
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700188 RETURN_IF_NOT_OK(mUidCounterSetMap.init(UID_COUNTERSET_MAP_PATH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700189 RETURN_IF_NOT_OK(changeOwnerAndMode(UID_COUNTERSET_MAP_PATH, AID_NET_BW_ACCT,
190 "UidCounterSetMap", false));
191
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700192 RETURN_IF_NOT_OK(mAppUidStatsMap.init(APP_UID_STATS_MAP_PATH));
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700193 RETURN_IF_NOT_OK(
194 changeOwnerAndMode(APP_UID_STATS_MAP_PATH, AID_NET_BW_STATS, "AppUidStatsMap", false));
195
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700196 RETURN_IF_NOT_OK(mStatsMapA.init(STATS_MAP_A_PATH));
Chenbo Fengf434e862018-06-27 14:08:39 -0700197 RETURN_IF_NOT_OK(changeOwnerAndMode(STATS_MAP_A_PATH, AID_NET_BW_STATS, "StatsMapA", false));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700198
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700199 RETURN_IF_NOT_OK(mStatsMapB.init(STATS_MAP_B_PATH));
Chenbo Fengf434e862018-06-27 14:08:39 -0700200 RETURN_IF_NOT_OK(changeOwnerAndMode(STATS_MAP_B_PATH, AID_NET_BW_STATS, "StatsMapB", false));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700201
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700202 RETURN_IF_NOT_OK(mIfaceIndexNameMap.init(IFACE_INDEX_NAME_MAP_PATH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700203 RETURN_IF_NOT_OK(changeOwnerAndMode(IFACE_INDEX_NAME_MAP_PATH, AID_NET_BW_STATS,
204 "IfaceIndexNameMap", false));
205
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700206 RETURN_IF_NOT_OK(mIfaceStatsMap.init(IFACE_STATS_MAP_PATH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700207 RETURN_IF_NOT_OK(changeOwnerAndMode(IFACE_STATS_MAP_PATH, AID_NET_BW_STATS, "IfaceStatsMap",
208 false));
Chenbo Feng95892f32018-06-07 14:52:02 -0700209
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700210 RETURN_IF_NOT_OK(mConfigurationMap.init(CONFIGURATION_MAP_PATH));
Chenbo Fengf434e862018-06-27 14:08:39 -0700211 RETURN_IF_NOT_OK(changeOwnerAndMode(CONFIGURATION_MAP_PATH, AID_NET_BW_STATS,
212 "ConfigurationMap", false));
Chenbo Feng703798e2018-06-15 17:07:59 -0700213 RETURN_IF_NOT_OK(
Chenbo Fengf434e862018-06-27 14:08:39 -0700214 mConfigurationMap.writeValue(UID_RULES_CONFIGURATION_KEY, DEFAULT_CONFIG, BPF_ANY));
215 RETURN_IF_NOT_OK(mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, SELECT_MAP_A,
216 BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700217
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700218 RETURN_IF_NOT_OK(mUidOwnerMap.init(UID_OWNER_MAP_PATH));
Chenbo Feng703798e2018-06-15 17:07:59 -0700219 RETURN_IF_NOT_OK(changeOwnerAndMode(UID_OWNER_MAP_PATH, AID_ROOT, "UidOwnerMap", true));
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900220 RETURN_IF_NOT_OK(mUidOwnerMap.clear());
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700221 RETURN_IF_NOT_OK(mUidPermissionMap.init(UID_PERMISSION_MAP_PATH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700222 return netdutils::status::ok;
223}
224
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800225static Status attachProgramToCgroup(const char* programPath, const int cgroupFd,
226 bpf_attach_type type) {
227 unique_fd cgroupProg(bpfFdGet(programPath, 0));
228 if (cgroupProg == -1) {
229 int ret = errno;
230 ALOGE("Failed to get program from %s: %s", programPath, strerror(ret));
231 return statusFromErrno(ret, "cgroup program get failed");
232 }
233 if (android::bpf::attachProgram(type, cgroupProg, cgroupFd)) {
234 int ret = errno;
235 ALOGE("Program from %s attach failed: %s", programPath, strerror(ret));
236 return statusFromErrno(ret, "program attach failed");
237 }
238 return netdutils::status::ok;
239}
240
241static Status initPrograms() {
Suren Baghdasaryane072a3c2019-01-16 14:36:07 -0800242 std::string cg2_path;
243
244 if (!CgroupGetControllerPath(CGROUPV2_CONTROLLER_NAME, &cg2_path)) {
245 int ret = errno;
246 ALOGE("Failed to find cgroup v2 root");
247 return statusFromErrno(ret, "Failed to find cgroup v2 root");
248 }
249
250 unique_fd cg_fd(open(cg2_path.c_str(), O_DIRECTORY | O_RDONLY | O_CLOEXEC));
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800251 if (cg_fd == -1) {
252 int ret = errno;
253 ALOGE("Failed to open the cgroup directory: %s", strerror(ret));
254 return statusFromErrno(ret, "Open the cgroup directory failed");
255 }
256 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_EGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_EGRESS));
257 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_INGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_INGRESS));
Chenbo Fenga51f4fa2019-01-15 15:03:32 -0800258
259 // For the devices that support cgroup socket filter, the socket filter
260 // should be loaded successfully by bpfloader. So we attach the filter to
261 // cgroup if the program is pinned properly.
262 // TODO: delete the if statement once all devices should support cgroup
263 // socket filter (ie. the minimum kernel version required is 4.14).
264 if (!access(CGROUP_SOCKET_PROG_PATH, F_OK)) {
265 RETURN_IF_NOT_OK(
266 attachProgramToCgroup(CGROUP_SOCKET_PROG_PATH, cg_fd, BPF_CGROUP_INET_SOCK_CREATE));
267 }
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800268 return netdutils::status::ok;
269}
270
Chenbo Feng89c12f12018-03-21 10:29:18 -0700271Status TrafficController::start() {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800272 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800273 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700274 }
275
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900276 /* When netd restarts from a crash without total system reboot, the program
Chenbo Fengf2759682017-10-10 17:31:57 -0700277 * is still attached to the cgroup, detach it so the program can be freed
278 * and we can load and attach new program into the target cgroup.
279 *
280 * TODO: Scrape existing socket when run-time restart and clean up the map
281 * if the socket no longer exist
282 */
283
Chenbo Feng89c12f12018-03-21 10:29:18 -0700284 RETURN_IF_NOT_OK(initMaps());
Chenbo Feng7e974052018-02-28 22:57:21 -0800285
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800286 RETURN_IF_NOT_OK(initPrograms());
287
Chenbo Feng7e974052018-02-28 22:57:21 -0800288 // Fetch the list of currently-existing interfaces. At this point NetlinkHandler is
289 // already running, so it will call addInterface() when any new interface appears.
290 std::map<std::string, uint32_t> ifacePairs;
291 ASSIGN_OR_RETURN(ifacePairs, InterfaceController::getIfaceList());
292 for (const auto& ifacePair:ifacePairs) {
293 addInterface(ifacePair.first.c_str(), ifacePair.second);
294 }
295
Chenbo Feng116d0552017-12-04 17:25:19 -0800296 auto result = makeSkDestroyListener();
297 if (!isOk(result)) {
298 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
299 } else {
300 mSkDestroyListener = std::move(result.value());
301 }
302 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
303 const auto rxHandler = [this](const nlmsghdr&, const Slice msg) {
304 inet_diag_msg diagmsg = {};
305 if (extract(msg, diagmsg) < sizeof(inet_diag_msg)) {
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900306 ALOGE("Unrecognized netlink message: %s", toString(msg).c_str());
Chenbo Feng116d0552017-12-04 17:25:19 -0800307 return;
308 }
309 uint64_t sock_cookie = static_cast<uint64_t>(diagmsg.id.idiag_cookie[0]) |
310 (static_cast<uint64_t>(diagmsg.id.idiag_cookie[1]) << 32);
311
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900312 Status s = mCookieTagMap.deleteValue(sock_cookie);
Chenbo Feng1d4c5db2018-10-18 15:50:46 -0700313 if (!isOk(s) && s.code() != ENOENT) {
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900314 ALOGE("Failed to delete cookie %" PRIx64 ": %s", sock_cookie, toString(s).c_str());
315 return;
316 }
Chenbo Feng116d0552017-12-04 17:25:19 -0800317 };
318 expectOk(mSkDestroyListener->subscribe(kSockDiagMsgType, rxHandler));
319
320 // In case multiple netlink message comes in as a stream, we need to handle the rxDone message
321 // properly.
322 const auto rxDoneHandler = [](const nlmsghdr&, const Slice msg) {
323 // Ignore NLMSG_DONE messages
324 inet_diag_msg diagmsg = {};
325 extract(msg, diagmsg);
326 };
327 expectOk(mSkDestroyListener->subscribe(kSockDiagDoneMsgType, rxDoneHandler));
328
Chenbo Feng05393d82018-01-09 15:18:43 -0800329 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700330}
331
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800332int TrafficController::tagSocket(int sockFd, uint32_t tag, uid_t uid, uid_t callingUid) {
Chenbo Fengb0495132019-04-10 12:54:41 -0700333 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800334 if (uid != callingUid && !hasUpdateDeviceStatsPermission(callingUid)) {
335 return -EPERM;
336 }
337
Chenbo Feng47dd0732018-12-11 12:23:24 -0800338 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700339 if (legacy_tagSocket(sockFd, tag, uid)) return -errno;
340 return 0;
341 }
Chenbo Feng33cc1032017-10-23 15:16:37 -0700342
Chenbo Fengf2759682017-10-10 17:31:57 -0700343 uint64_t sock_cookie = getSocketCookie(sockFd);
Chenbo Fengef1cab32018-04-13 19:50:49 -0700344 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
Chenbo Fengf2759682017-10-10 17:31:57 -0700345 UidTag newKey = {.uid = (uint32_t)uid, .tag = tag};
346
Chenbo Fengb0495132019-04-10 12:54:41 -0700347 uint32_t totalEntryCount = 0;
348 // Now we go through the stats map and count how many entries are associated
349 // with target uid. If the uid entry hit the limit for each uid, we block
350 // the request to prevent the map from overflow. It is safe here to iterate
351 // over the map since when mOwnerMatchMutex is hold, system server cannot toggle
352 // the live stats map and clean it. So nobody can delete entries from the map.
353 const auto countUidStatsEntries = [uid, &totalEntryCount](const StatsKey& key,
354 BpfMap<StatsKey, StatsValue>&) {
355 if (key.uid == uid) {
356 totalEntryCount++;
357 }
358 return netdutils::status::ok;
359 };
360 auto configuration = mConfigurationMap.readValue(CURRENT_STATS_MAP_CONFIGURATION_KEY);
361 if (!isOk(configuration.status())) {
362 ALOGE("Failed to get current configuration: %s, fd: %d",
363 strerror(configuration.status().code()), mConfigurationMap.getMap().get());
364 return -configuration.status().code();
365 }
366 if (configuration.value() == SELECT_MAP_A) {
367 mStatsMapA.iterate(countUidStatsEntries).ignoreError();
368 } else if (configuration.value() == SELECT_MAP_B) {
369 mStatsMapB.iterate(countUidStatsEntries).ignoreError();
370 } else {
371 ALOGE("unknown configuration value: %d", configuration.value());
372 return -EINVAL;
373 }
374 if (totalEntryCount > PER_UID_STATS_ENTRY_LIMIT) {
375 ALOGE("Too many stats entry for this uid: %u, block tag request to prevent map overflow",
376 uid);
377 return -EMFILE;
378 }
Chenbo Fengf2759682017-10-10 17:31:57 -0700379 // Update the tag information of a socket to the cookieUidMap. Use BPF_ANY
380 // flag so it will insert a new entry to the map if that value doesn't exist
381 // yet. And update the tag if there is already a tag stored. Since the eBPF
382 // program in kernel only read this map, and is protected by rcu read lock. It
383 // should be fine to cocurrently update the map while eBPF program is running.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700384 Status res = mCookieTagMap.writeValue(sock_cookie, newKey, BPF_ANY);
385 if (!isOk(res)) {
386 ALOGE("Failed to tag the socket: %s, fd: %d", strerror(res.code()),
387 mCookieTagMap.getMap().get());
Chenbo Fengf2759682017-10-10 17:31:57 -0700388 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700389 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700390}
391
392int TrafficController::untagSocket(int sockFd) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800393 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700394 if (legacy_untagSocket(sockFd)) return -errno;
395 return 0;
396 }
Chenbo Fengf2759682017-10-10 17:31:57 -0700397 uint64_t sock_cookie = getSocketCookie(sockFd);
398
Chenbo Fengef1cab32018-04-13 19:50:49 -0700399 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700400 Status res = mCookieTagMap.deleteValue(sock_cookie);
401 if (!isOk(res)) {
402 ALOGE("Failed to untag socket: %s\n", strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700403 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700404 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700405}
406
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800407int TrafficController::setCounterSet(int counterSetNum, uid_t uid, uid_t callingUid) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700408 if (counterSetNum < 0 || counterSetNum >= OVERFLOW_COUNTERSET) return -EINVAL;
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800409
410 if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
411
Chenbo Feng47dd0732018-12-11 12:23:24 -0800412 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700413 if (legacy_setCounterSet(counterSetNum, uid)) return -errno;
414 return 0;
415 }
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800416
417 // The default counter set for all uid is 0, so deleting the current counterset for that uid
418 // will automatically set it to 0.
Chenbo Fengf2759682017-10-10 17:31:57 -0700419 if (counterSetNum == 0) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700420 Status res = mUidCounterSetMap.deleteValue(uid);
421 if (isOk(res) || (!isOk(res) && res.code() == ENOENT)) {
Chenbo Fengf2759682017-10-10 17:31:57 -0700422 return 0;
423 } else {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700424 ALOGE("Failed to delete the counterSet: %s\n", strerror(res.code()));
425 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700426 }
427 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700428 uint8_t tmpCounterSetNum = (uint8_t)counterSetNum;
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800429 Status res = mUidCounterSetMap.writeValue(uid, tmpCounterSetNum, BPF_ANY);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700430 if (!isOk(res)) {
431 ALOGE("Failed to set the counterSet: %s, fd: %d", strerror(res.code()),
432 mUidCounterSetMap.getMap().get());
433 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700434 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700435 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700436}
437
Chenbo Fengf434e862018-06-27 14:08:39 -0700438// This method only get called by system_server when an app get uinstalled, it
439// is called inside removeUidsLocked() while holding mStatsLock. So it is safe
440// to iterate and modify the stats maps.
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800441int TrafficController::deleteTagData(uint32_t tag, uid_t uid, uid_t callingUid) {
442 if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
443
Chenbo Feng47dd0732018-12-11 12:23:24 -0800444 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700445 if (legacy_deleteTagData(tag, uid)) return -errno;
446 return 0;
447 }
Chenbo Feng33cc1032017-10-23 15:16:37 -0700448
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800449 // First we go through the cookieTagMap to delete the target uid tag combination. Or delete all
Chenbo Fengef1cab32018-04-13 19:50:49 -0700450 // the tags related to the uid if the tag is 0.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700451 const auto deleteMatchedCookieEntries = [uid, tag](const uint64_t& key, const UidTag& value,
452 BpfMap<uint64_t, UidTag>& map) {
453 if (value.uid == uid && (value.tag == tag || tag == 0)) {
454 Status res = map.deleteValue(key);
455 if (isOk(res) || (res.code() == ENOENT)) {
456 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700457 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700458 ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s\n", key, strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700459 }
Chenbo Fengef1cab32018-04-13 19:50:49 -0700460 // Move forward to next cookie in the map.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700461 return netdutils::status::ok;
Chenbo Fengef1cab32018-04-13 19:50:49 -0700462 };
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900463 mCookieTagMap.iterateWithValue(deleteMatchedCookieEntries).ignoreError();
Chenbo Fengf2759682017-10-10 17:31:57 -0700464 // 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 -0700465 // combination. Or all tag stats under that uid if the target tag is 0.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700466 const auto deleteMatchedUidTagEntries = [uid, tag](const StatsKey& key,
467 BpfMap<StatsKey, StatsValue>& map) {
468 if (key.uid == uid && (key.tag == tag || tag == 0)) {
469 Status res = map.deleteValue(key);
470 if (isOk(res) || (res.code() == ENOENT)) {
Chenbo Fengef1cab32018-04-13 19:50:49 -0700471 //Entry is deleted, use the current key to get a new nextKey;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700472 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700473 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700474 ALOGE("Failed to delete data(uid=%u, tag=%u): %s\n", key.uid, key.tag,
475 strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700476 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700477 return netdutils::status::ok;
Chenbo Fengef1cab32018-04-13 19:50:49 -0700478 };
Chenbo Fengf434e862018-06-27 14:08:39 -0700479 mStatsMapB.iterate(deleteMatchedUidTagEntries).ignoreError();
480 mStatsMapA.iterate(deleteMatchedUidTagEntries).ignoreError();
Chenbo Fengf2759682017-10-10 17:31:57 -0700481 // 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 -0800482 // need to delete the stats stored in uidStatsMap and counterSet map.
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800483 if (tag != 0) return 0;
484
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700485 Status res = mUidCounterSetMap.deleteValue(uid);
486 if (!isOk(res) && res.code() != ENOENT) {
487 ALOGE("Failed to delete counterSet data(uid=%u, tag=%u): %s\n", uid, tag,
488 strerror(res.code()));
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800489 }
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700490
491 auto deleteAppUidStatsEntry = [uid](const uint32_t& key, BpfMap<uint32_t, StatsValue>& map) {
492 if (key == uid) {
493 Status res = map.deleteValue(key);
494 if (isOk(res) || (res.code() == ENOENT)) {
495 return netdutils::status::ok;
496 }
497 ALOGE("Failed to delete data(uid=%u): %s", key, strerror(res.code()));
498 }
499 return netdutils::status::ok;
500 };
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900501 mAppUidStatsMap.iterate(deleteAppUidStatsEntry).ignoreError();
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700502 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700503}
504
Chenbo Feng7e974052018-02-28 22:57:21 -0800505int TrafficController::addInterface(const char* name, uint32_t ifaceIndex) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800506 if (mBpfLevel == BpfLevel::NONE) return 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800507
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700508 IfaceValue iface;
Chenbo Feng7e974052018-02-28 22:57:21 -0800509 if (ifaceIndex == 0) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700510 ALOGE("Unknown interface %s(%d)", name, ifaceIndex);
Chenbo Feng7e974052018-02-28 22:57:21 -0800511 return -1;
512 }
513
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700514 strlcpy(iface.name, name, sizeof(IfaceValue));
515 Status res = mIfaceIndexNameMap.writeValue(ifaceIndex, iface, BPF_ANY);
516 if (!isOk(res)) {
517 ALOGE("Failed to add iface %s(%d): %s", name, ifaceIndex, strerror(res.code()));
518 return -res.code();
Chenbo Feng7e974052018-02-28 22:57:21 -0800519 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700520 return 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800521}
522
Chenbo Feng703798e2018-06-15 17:07:59 -0700523Status TrafficController::updateOwnerMapEntry(UidOwnerMatchType match, uid_t uid, FirewallRule rule,
524 FirewallType type) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900525 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700526 if ((rule == ALLOW && type == WHITELIST) || (rule == DENY && type == BLACKLIST)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100527 RETURN_IF_NOT_OK(addRule(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700528 } else if ((rule == ALLOW && type == BLACKLIST) || (rule == DENY && type == WHITELIST)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100529 RETURN_IF_NOT_OK(removeRule(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700530 } else {
531 //Cannot happen.
Rubin Xuec27ff22019-01-08 21:33:03 +0000532 return statusFromErrno(EINVAL, "");
Chenbo Feng89c12f12018-03-21 10:29:18 -0700533 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700534 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700535}
536
Chenbo Feng703798e2018-06-15 17:07:59 -0700537UidOwnerMatchType TrafficController::jumpOpToMatch(BandwidthController::IptJumpOp jumpHandling) {
Chenbo Feng95892f32018-06-07 14:52:02 -0700538 switch (jumpHandling) {
539 case BandwidthController::IptJumpReject:
Chenbo Feng703798e2018-06-15 17:07:59 -0700540 return PENALTY_BOX_MATCH;
Chenbo Feng95892f32018-06-07 14:52:02 -0700541 case BandwidthController::IptJumpReturn:
Chenbo Feng703798e2018-06-15 17:07:59 -0700542 return HAPPY_BOX_MATCH;
Chenbo Feng95892f32018-06-07 14:52:02 -0700543 case BandwidthController::IptJumpNoAdd:
544 return NO_MATCH;
545 }
546}
547
Rubin Xu5ca8e802019-04-05 11:50:32 +0100548Status TrafficController::removeRule(BpfMap<uint32_t, UidOwnerValue>& map, uint32_t uid,
549 UidOwnerMatchType match) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700550 auto oldMatch = map.readValue(uid);
551 if (isOk(oldMatch)) {
Rubin Xuec27ff22019-01-08 21:33:03 +0000552 UidOwnerValue newMatch = {.rule = static_cast<uint8_t>(oldMatch.value().rule & ~match),
553 .iif = (match == IIF_MATCH) ? 0 : oldMatch.value().iif};
554 if (newMatch.rule == 0) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700555 RETURN_IF_NOT_OK(map.deleteValue(uid));
556 } else {
557 RETURN_IF_NOT_OK(map.writeValue(uid, newMatch, BPF_ANY));
558 }
559 } else {
560 return statusFromErrno(ENOENT, StringPrintf("uid: %u does not exist in map", uid));
561 }
562 return netdutils::status::ok;
563}
564
Rubin Xu5ca8e802019-04-05 11:50:32 +0100565Status TrafficController::addRule(BpfMap<uint32_t, UidOwnerValue>& map, uint32_t uid,
566 UidOwnerMatchType match, uint32_t iif) {
Rubin Xuec27ff22019-01-08 21:33:03 +0000567 // iif should be non-zero if and only if match == MATCH_IIF
568 if (match == IIF_MATCH && iif == 0) {
569 return statusFromErrno(EINVAL, "Interface match must have nonzero interface index");
570 } else if (match != IIF_MATCH && iif != 0) {
571 return statusFromErrno(EINVAL, "Non-interface match must have zero interface index");
572 }
Chenbo Feng703798e2018-06-15 17:07:59 -0700573 auto oldMatch = map.readValue(uid);
574 if (isOk(oldMatch)) {
Rubin Xuec27ff22019-01-08 21:33:03 +0000575 UidOwnerValue newMatch = {.rule = static_cast<uint8_t>(oldMatch.value().rule | match),
576 .iif = iif ? iif : oldMatch.value().iif};
577 RETURN_IF_NOT_OK(map.writeValue(uid, newMatch, BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700578 } else {
Rubin Xuec27ff22019-01-08 21:33:03 +0000579 UidOwnerValue newMatch = {.rule = static_cast<uint8_t>(match), .iif = iif};
580 RETURN_IF_NOT_OK(map.writeValue(uid, newMatch, BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700581 }
582 return netdutils::status::ok;
583}
584
585Status TrafficController::updateUidOwnerMap(const std::vector<std::string>& appStrUids,
586 BandwidthController::IptJumpOp jumpHandling,
587 BandwidthController::IptOp op) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900588 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Feng703798e2018-06-15 17:07:59 -0700589 UidOwnerMatchType match = jumpOpToMatch(jumpHandling);
590 if (match == NO_MATCH) {
591 return statusFromErrno(
592 EINVAL, StringPrintf("invalid IptJumpOp: %d, command: %d", jumpHandling, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700593 }
594 for (const auto& appStrUid : appStrUids) {
595 char* endPtr;
596 long uid = strtol(appStrUid.c_str(), &endPtr, 10);
597 if ((errno == ERANGE && (uid == LONG_MAX || uid == LONG_MIN)) ||
598 (endPtr == appStrUid.c_str()) || (*endPtr != '\0')) {
599 return statusFromErrno(errno, "invalid uid string:" + appStrUid);
600 }
601
Chenbo Feng95892f32018-06-07 14:52:02 -0700602 if (op == BandwidthController::IptOpDelete) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100603 RETURN_IF_NOT_OK(removeRule(mUidOwnerMap, uid, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700604 } else if (op == BandwidthController::IptOpInsert) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100605 RETURN_IF_NOT_OK(addRule(mUidOwnerMap, uid, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700606 } else {
607 // Cannot happen.
Chenbo Feng703798e2018-06-15 17:07:59 -0700608 return statusFromErrno(EINVAL, StringPrintf("invalid IptOp: %d, %d", op, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700609 }
610 }
611 return netdutils::status::ok;
612}
613
Chenbo Feng89c12f12018-03-21 10:29:18 -0700614int TrafficController::changeUidOwnerRule(ChildChain chain, uid_t uid, FirewallRule rule,
615 FirewallType type) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800616 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Feng89c12f12018-03-21 10:29:18 -0700617 ALOGE("bpf is not set up, should use iptables rule");
618 return -ENOSYS;
619 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700620 Status res;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700621 switch (chain) {
622 case DOZABLE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700623 res = updateOwnerMapEntry(DOZABLE_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700624 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700625 case STANDBY:
Chenbo Feng703798e2018-06-15 17:07:59 -0700626 res = updateOwnerMapEntry(STANDBY_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700627 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700628 case POWERSAVE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700629 res = updateOwnerMapEntry(POWERSAVE_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700630 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700631 case NONE:
632 default:
633 return -EINVAL;
634 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700635 if (!isOk(res)) {
636 ALOGE("change uid(%u) rule of %d failed: %s, rule: %d, type: %d", uid, chain,
637 res.msg().c_str(), rule, type);
638 return -res.code();
639 }
640 return 0;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700641}
642
Rubin Xu5ca8e802019-04-05 11:50:32 +0100643Status TrafficController::replaceRulesInMap(const UidOwnerMatchType match,
644 const std::vector<int32_t>& uids) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900645 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700646 std::set<int32_t> uidSet(uids.begin(), uids.end());
647 std::vector<uint32_t> uidsToDelete;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700648 auto getUidsToDelete = [&uidsToDelete, &uidSet](const uint32_t& key,
Rubin Xuec27ff22019-01-08 21:33:03 +0000649 const BpfMap<uint32_t, UidOwnerValue>&) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700650 if (uidSet.find((int32_t) key) == uidSet.end()) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700651 uidsToDelete.push_back(key);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700652 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700653 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700654 };
Chenbo Feng703798e2018-06-15 17:07:59 -0700655 RETURN_IF_NOT_OK(mUidOwnerMap.iterate(getUidsToDelete));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700656
657 for(auto uid : uidsToDelete) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100658 RETURN_IF_NOT_OK(removeRule(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700659 }
660
661 for (auto uid : uids) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100662 RETURN_IF_NOT_OK(addRule(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700663 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700664 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700665}
666
Rubin Xuec27ff22019-01-08 21:33:03 +0000667Status TrafficController::addUidInterfaceRules(const int iif,
668 const std::vector<int32_t>& uidsToAdd) {
669 if (mBpfLevel == BpfLevel::NONE) {
670 ALOGW("UID ingress interface filtering not possible without BPF owner match");
671 return statusFromErrno(EOPNOTSUPP, "eBPF not supported");
672 }
673 if (!iif) {
674 return statusFromErrno(EINVAL, "Interface rule must specify interface");
675 }
676 std::lock_guard guard(mOwnerMatchMutex);
677
678 for (auto uid : uidsToAdd) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100679 netdutils::Status result = addRule(mUidOwnerMap, uid, IIF_MATCH, iif);
Rubin Xuec27ff22019-01-08 21:33:03 +0000680 if (!isOk(result)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100681 ALOGW("addRule failed(%d): uid=%d iif=%d", result.code(), uid, iif);
Rubin Xuec27ff22019-01-08 21:33:03 +0000682 }
683 }
684 return netdutils::status::ok;
685}
686
687Status TrafficController::removeUidInterfaceRules(const std::vector<int32_t>& uidsToDelete) {
688 if (mBpfLevel == BpfLevel::NONE) {
689 ALOGW("UID ingress interface filtering not possible without BPF owner match");
690 return statusFromErrno(EOPNOTSUPP, "eBPF not supported");
691 }
692 std::lock_guard guard(mOwnerMatchMutex);
693
694 for (auto uid : uidsToDelete) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100695 netdutils::Status result = removeRule(mUidOwnerMap, uid, IIF_MATCH);
Rubin Xuec27ff22019-01-08 21:33:03 +0000696 if (!isOk(result)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100697 ALOGW("removeRule failed(%d): uid=%d", result.code(), uid);
Rubin Xuec27ff22019-01-08 21:33:03 +0000698 }
699 }
700 return netdutils::status::ok;
701}
702
Chenbo Feng89c12f12018-03-21 10:29:18 -0700703int TrafficController::replaceUidOwnerMap(const std::string& name, bool isWhitelist,
704 const std::vector<int32_t>& uids) {
Chenbo Feng89c12f12018-03-21 10:29:18 -0700705 FirewallRule rule;
706 FirewallType type;
707 if (isWhitelist) {
708 type = WHITELIST;
709 rule = ALLOW;
710 } else {
711 type = BLACKLIST;
712 rule = DENY;
713 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700714 Status res;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700715 if (!name.compare(FirewallController::LOCAL_DOZABLE)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100716 res = replaceRulesInMap(DOZABLE_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700717 } else if (!name.compare(FirewallController::LOCAL_STANDBY)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100718 res = replaceRulesInMap(STANDBY_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700719 } else if (!name.compare(FirewallController::LOCAL_POWERSAVE)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100720 res = replaceRulesInMap(POWERSAVE_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700721 } else {
722 ALOGE("unknown chain name: %s", name.c_str());
723 return -EINVAL;
724 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700725 if (!isOk(res)) {
726 ALOGE("Failed to clean up chain: %s: %s", name.c_str(), res.msg().c_str());
727 return -res.code();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700728 }
729 return 0;
730}
731
732int TrafficController::toggleUidOwnerMap(ChildChain chain, bool enable) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900733 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Fengf434e862018-06-27 14:08:39 -0700734 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Chenbo Feng703798e2018-06-15 17:07:59 -0700735 auto oldConfiguration = mConfigurationMap.readValue(key);
736 if (!isOk(oldConfiguration)) {
737 ALOGE("Cannot read the old configuration from map: %s",
738 oldConfiguration.status().msg().c_str());
739 return -oldConfiguration.status().code();
740 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700741 Status res;
Chenbo Feng703798e2018-06-15 17:07:59 -0700742 BpfConfig newConfiguration;
743 uint8_t match;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700744 switch (chain) {
745 case DOZABLE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700746 match = DOZABLE_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700747 break;
748 case STANDBY:
Chenbo Feng703798e2018-06-15 17:07:59 -0700749 match = STANDBY_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700750 break;
751 case POWERSAVE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700752 match = POWERSAVE_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700753 break;
754 default:
755 return -EINVAL;
756 }
Chenbo Feng703798e2018-06-15 17:07:59 -0700757 newConfiguration =
758 enable ? (oldConfiguration.value() | match) : (oldConfiguration.value() & (~match));
759 res = mConfigurationMap.writeValue(key, newConfiguration, BPF_EXIST);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700760 if (!isOk(res)) {
761 ALOGE("Failed to toggleUidOwnerMap(%d): %s", chain, res.msg().c_str());
Chenbo Feng89c12f12018-03-21 10:29:18 -0700762 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700763 return -res.code();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700764}
765
Chenbo Feng47dd0732018-12-11 12:23:24 -0800766BpfLevel TrafficController::getBpfLevel() {
767 return mBpfLevel;
Chenbo Feng07d43fe2017-12-21 14:38:51 -0800768}
769
Chenbo Feng873ae142019-04-10 12:26:06 -0700770Status TrafficController::swapActiveStatsMap() {
771 std::lock_guard guard(mOwnerMatchMutex);
772
773 if (mBpfLevel == BpfLevel::NONE) {
774 return statusFromErrno(EOPNOTSUPP, "This device doesn't have eBPF support");
775 }
776
777 uint32_t key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
778 auto oldConfiguration = mConfigurationMap.readValue(key);
779 if (!isOk(oldConfiguration)) {
780 ALOGE("Cannot read the old configuration from map: %s",
781 oldConfiguration.status().msg().c_str());
782 return oldConfiguration.status();
783 }
784
785 // Write to the configuration map to inform the kernel eBPF program to switch
786 // from using one map to the other. Use flag BPF_EXIST here since the map should
787 // be already populated in initMaps.
788 uint8_t newConfigure = (oldConfiguration.value() == SELECT_MAP_A) ? SELECT_MAP_B : SELECT_MAP_A;
789 Status res = mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, newConfigure,
790 BPF_EXIST);
791 if (!isOk(res)) {
792 ALOGE("Failed to toggle the stats map: %s", strerror(res.code()));
793 return res;
794 }
795 // After changing the config, we need to make sure all the current running
796 // eBPF programs are finished and all the CPUs are aware of this config change
797 // before we modify the old map. So we do a special hack here to wait for
798 // the kernel to do a synchronize_rcu(). Once the kernel called
799 // synchronize_rcu(), the config we just updated will be available to all cores
800 // and the next eBPF programs triggered inside the kernel will use the new
801 // map configuration. So once this function returns we can safely modify the
802 // old stats map without concerning about race between the kernel and
803 // userspace.
804 int ret = synchronizeKernelRCU();
805 if (ret) {
806 ALOGE("map swap synchronize_rcu() ended with failure: %s", strerror(-ret));
807 return statusFromErrno(-ret, "map swap synchronize_rcu() failed");
808 }
809 return netdutils::status::ok;
810}
811
Chenbo Feng48eaed32018-12-26 17:40:21 -0800812void TrafficController::setPermissionForUids(int permission, const std::vector<uid_t>& uids) {
Chenbo Fengbf660aa2019-02-26 16:12:27 -0800813 if (permission == INetd::PERMISSION_UNINSTALLED) {
814 for (uid_t uid : uids) {
815 // Clean up all permission information for the related uid if all the
816 // packages related to it are uninstalled.
817 mPrivilegedUser.erase(uid);
818 Status ret = mUidPermissionMap.deleteValue(uid);
819 }
820 return;
821 }
822
Chenbo Feng48eaed32018-12-26 17:40:21 -0800823 bool privileged = (permission & INetd::PERMISSION_UPDATE_DEVICE_STATS);
824
825 for (uid_t uid : uids) {
Chenbo Feng527908a2019-04-02 20:14:11 -0700826 // The map stores all the permissions that the UID has, except if the only permission
827 // the UID has is the INTERNET permission, then the UID should not appear in the map.
828 if (permission != INetd::PERMISSION_INTERNET) {
Chenbo Fengbf660aa2019-02-26 16:12:27 -0800829 Status ret = mUidPermissionMap.writeValue(uid, permission, BPF_ANY);
Chenbo Feng48eaed32018-12-26 17:40:21 -0800830 if (!isOk(ret)) {
Chenbo Feng527908a2019-04-02 20:14:11 -0700831 ALOGE("Failed to set permission: %s of uid(%u) to permission map: %s",
832 UidPermissionTypeToString(permission).c_str(), uid, strerror(ret.code()));
Chenbo Feng48eaed32018-12-26 17:40:21 -0800833 }
834 } else {
835 Status ret = mUidPermissionMap.deleteValue(uid);
836 if (!isOk(ret) && ret.code() != ENOENT) {
Chenbo Feng527908a2019-04-02 20:14:11 -0700837 ALOGE("Failed to remove uid %u from permission map: %s", uid, strerror(ret.code()));
Chenbo Feng48eaed32018-12-26 17:40:21 -0800838 }
839 }
840
841 if (privileged) {
842 mPrivilegedUser.insert(uid);
843 } else {
844 mPrivilegedUser.erase(uid);
845 }
846 }
847}
848
Chenbo Fengef297172018-03-26 10:53:33 -0700849std::string getProgramStatus(const char *path) {
850 int ret = access(path, R_OK);
851 if (ret == 0) {
852 return StringPrintf("OK");
853 }
854 if (ret != 0 && errno == ENOENT) {
855 return StringPrintf("program is missing at: %s", path);
856 }
857 return StringPrintf("check Program %s error: %s", path, strerror(errno));
858}
859
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700860std::string getMapStatus(const base::unique_fd& map_fd, const char* path) {
Chenbo Fengef297172018-03-26 10:53:33 -0700861 if (map_fd.get() < 0) {
862 return StringPrintf("map fd lost");
863 }
864 if (access(path, F_OK) != 0) {
865 return StringPrintf("map not pinned to location: %s", path);
866 }
867 return StringPrintf("OK");
868}
869
Bernie Innocentia5161a02019-01-30 22:40:53 +0900870// NOLINTNEXTLINE(google-runtime-references): grandfathered pass by non-const reference
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900871void dumpBpfMap(const std::string& mapName, DumpWriter& dw, const std::string& header) {
Chenbo Fengef297172018-03-26 10:53:33 -0700872 dw.blankline();
873 dw.println("%s:", mapName.c_str());
Erik Klineb31fd692018-06-06 20:50:11 +0900874 if (!header.empty()) {
875 dw.println(header);
Chenbo Fengef297172018-03-26 10:53:33 -0700876 }
877}
878
879const String16 TrafficController::DUMP_KEYWORD = String16("trafficcontroller");
880
881void TrafficController::dump(DumpWriter& dw, bool verbose) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900882 std::lock_guard ownerMapGuard(mOwnerMatchMutex);
Erik Klineb31fd692018-06-06 20:50:11 +0900883 ScopedIndent indentTop(dw);
Chenbo Fengef297172018-03-26 10:53:33 -0700884 dw.println("TrafficController");
885
Erik Klineb31fd692018-06-06 20:50:11 +0900886 ScopedIndent indentPreBpfModule(dw);
Chenbo Feng47dd0732018-12-11 12:23:24 -0800887 dw.println("BPF module status: %s", BpfLevelToString(mBpfLevel).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700888
Chenbo Feng47dd0732018-12-11 12:23:24 -0800889 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengef297172018-03-26 10:53:33 -0700890 return;
Erik Klineb31fd692018-06-06 20:50:11 +0900891 }
Chenbo Fengef297172018-03-26 10:53:33 -0700892
893 dw.blankline();
894 dw.println("mCookieTagMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700895 getMapStatus(mCookieTagMap.getMap(), COOKIE_TAG_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700896 dw.println("mUidCounterSetMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700897 getMapStatus(mUidCounterSetMap.getMap(), UID_COUNTERSET_MAP_PATH).c_str());
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700898 dw.println("mAppUidStatsMap status: %s",
899 getMapStatus(mAppUidStatsMap.getMap(), APP_UID_STATS_MAP_PATH).c_str());
Chenbo Fengf434e862018-06-27 14:08:39 -0700900 dw.println("mStatsMapA status: %s",
901 getMapStatus(mStatsMapA.getMap(), STATS_MAP_A_PATH).c_str());
902 dw.println("mStatsMapB status: %s",
903 getMapStatus(mStatsMapB.getMap(), STATS_MAP_B_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700904 dw.println("mIfaceIndexNameMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700905 getMapStatus(mIfaceIndexNameMap.getMap(), IFACE_INDEX_NAME_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700906 dw.println("mIfaceStatsMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700907 getMapStatus(mIfaceStatsMap.getMap(), IFACE_STATS_MAP_PATH).c_str());
Chenbo Feng703798e2018-06-15 17:07:59 -0700908 dw.println("mConfigurationMap status: %s",
909 getMapStatus(mConfigurationMap.getMap(), CONFIGURATION_MAP_PATH).c_str());
910 dw.println("mUidOwnerMap status: %s",
911 getMapStatus(mUidOwnerMap.getMap(), UID_OWNER_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700912
913 dw.blankline();
914 dw.println("Cgroup ingress program status: %s",
915 getProgramStatus(BPF_INGRESS_PROG_PATH).c_str());
916 dw.println("Cgroup egress program status: %s", getProgramStatus(BPF_EGRESS_PROG_PATH).c_str());
917 dw.println("xt_bpf ingress program status: %s",
918 getProgramStatus(XT_BPF_INGRESS_PROG_PATH).c_str());
919 dw.println("xt_bpf egress program status: %s",
920 getProgramStatus(XT_BPF_EGRESS_PROG_PATH).c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700921 dw.println("xt_bpf bandwidth whitelist program status: %s",
922 getProgramStatus(XT_BPF_WHITELIST_PROG_PATH).c_str());
923 dw.println("xt_bpf bandwidth blacklist program status: %s",
924 getProgramStatus(XT_BPF_BLACKLIST_PROG_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700925
Erik Klineb31fd692018-06-06 20:50:11 +0900926 if (!verbose) {
927 return;
928 }
Chenbo Fengef297172018-03-26 10:53:33 -0700929
930 dw.blankline();
931 dw.println("BPF map content:");
932
Erik Klineb31fd692018-06-06 20:50:11 +0900933 ScopedIndent indentForMapContent(dw);
Chenbo Fengef297172018-03-26 10:53:33 -0700934
935 // Print CookieTagMap content.
936 dumpBpfMap("mCookieTagMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700937 const auto printCookieTagInfo = [&dw](const uint64_t& key, const UidTag& value,
938 const BpfMap<uint64_t, UidTag>&) {
939 dw.println("cookie=%" PRIu64 " tag=0x%x uid=%u", key, value.tag, value.uid);
940 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700941 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700942 Status res = mCookieTagMap.iterateWithValue(printCookieTagInfo);
943 if (!isOk(res)) {
944 dw.println("mCookieTagMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700945 }
946
947 // Print UidCounterSetMap Content
948 dumpBpfMap("mUidCounterSetMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700949 const auto printUidInfo = [&dw](const uint32_t& key, const uint8_t& value,
950 const BpfMap<uint32_t, uint8_t>&) {
951 dw.println("%u %u", key, value);
952 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700953 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700954 res = mUidCounterSetMap.iterateWithValue(printUidInfo);
955 if (!isOk(res)) {
956 dw.println("mUidCounterSetMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700957 }
958
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700959 // Print AppUidStatsMap content
960 std::string appUidStatsHeader = StringPrintf("uid rxBytes rxPackets txBytes txPackets");
961 dumpBpfMap("mAppUidStatsMap:", dw, appUidStatsHeader);
962 auto printAppUidStatsInfo = [&dw](const uint32_t& key, const StatsValue& value,
963 const BpfMap<uint32_t, StatsValue>&) {
964 dw.println("%u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, value.rxBytes,
965 value.rxPackets, value.txBytes, value.txPackets);
966 return netdutils::status::ok;
967 };
968 res = mAppUidStatsMap.iterateWithValue(printAppUidStatsInfo);
969 if (!res.ok()) {
970 dw.println("mAppUidStatsMap print end with error: %s", res.msg().c_str());
971 }
972
Chenbo Fengef297172018-03-26 10:53:33 -0700973 // Print uidStatsMap content
974 std::string statsHeader = StringPrintf("ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes"
975 " rxPackets txBytes txPackets");
Chenbo Fengf434e862018-06-27 14:08:39 -0700976 dumpBpfMap("mStatsMapA", dw, statsHeader);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700977 const auto printStatsInfo = [&dw, this](const StatsKey& key, const StatsValue& value,
978 const BpfMap<StatsKey, StatsValue>&) {
979 uint32_t ifIndex = key.ifaceIndex;
980 auto ifname = mIfaceIndexNameMap.readValue(ifIndex);
981 if (!isOk(ifname)) {
982 strlcpy(ifname.value().name, "unknown", sizeof(IfaceValue));
Chenbo Fengef297172018-03-26 10:53:33 -0700983 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700984 dw.println("%u %s 0x%x %u %u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, ifIndex,
985 ifname.value().name, key.tag, key.uid, key.counterSet, value.rxBytes,
986 value.rxPackets, value.txBytes, value.txPackets);
987 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700988 };
Chenbo Fengf434e862018-06-27 14:08:39 -0700989 res = mStatsMapA.iterateWithValue(printStatsInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700990 if (!isOk(res)) {
Chenbo Fengf434e862018-06-27 14:08:39 -0700991 dw.println("mStatsMapA print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700992 }
993
994 // Print TagStatsMap content.
Chenbo Fengf434e862018-06-27 14:08:39 -0700995 dumpBpfMap("mStatsMapB", dw, statsHeader);
996 res = mStatsMapB.iterateWithValue(printStatsInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700997 if (!isOk(res)) {
Chenbo Fengf434e862018-06-27 14:08:39 -0700998 dw.println("mStatsMapB print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700999 }
1000
1001 // Print ifaceIndexToNameMap content.
1002 dumpBpfMap("mIfaceIndexNameMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001003 const auto printIfaceNameInfo = [&dw](const uint32_t& key, const IfaceValue& value,
1004 const BpfMap<uint32_t, IfaceValue>&) {
1005 const char* ifname = value.name;
1006 dw.println("ifaceIndex=%u ifaceName=%s", key, ifname);
1007 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -07001008 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001009 res = mIfaceIndexNameMap.iterateWithValue(printIfaceNameInfo);
1010 if (!isOk(res)) {
1011 dw.println("mIfaceIndexNameMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001012 }
1013
1014 // Print ifaceStatsMap content
1015 std::string ifaceStatsHeader = StringPrintf("ifaceIndex ifaceName rxBytes rxPackets txBytes"
1016 " txPackets");
1017 dumpBpfMap("mIfaceStatsMap:", dw, ifaceStatsHeader);
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001018 const auto printIfaceStatsInfo = [&dw, this](const uint32_t& key, const StatsValue& value,
1019 const BpfMap<uint32_t, StatsValue>&) {
1020 auto ifname = mIfaceIndexNameMap.readValue(key);
1021 if (!isOk(ifname)) {
1022 strlcpy(ifname.value().name, "unknown", sizeof(IfaceValue));
Chenbo Fengef297172018-03-26 10:53:33 -07001023 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001024 dw.println("%u %s %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, ifname.value().name,
1025 value.rxBytes, value.rxPackets, value.txBytes, value.txPackets);
1026 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -07001027 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001028 res = mIfaceStatsMap.iterateWithValue(printIfaceStatsInfo);
1029 if (!isOk(res)) {
1030 dw.println("mIfaceStatsMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001031 }
1032
Chenbo Feng703798e2018-06-15 17:07:59 -07001033 dw.blankline();
Chenbo Fengef297172018-03-26 10:53:33 -07001034
Chenbo Fengf434e862018-06-27 14:08:39 -07001035 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Chenbo Feng703798e2018-06-15 17:07:59 -07001036 auto configuration = mConfigurationMap.readValue(key);
1037 if (isOk(configuration)) {
Chenbo Fengf434e862018-06-27 14:08:39 -07001038 dw.println("current ownerMatch configuration: %d", configuration.value());
Chenbo Feng703798e2018-06-15 17:07:59 -07001039 } else {
Chenbo Fengf434e862018-06-27 14:08:39 -07001040 dw.println("mConfigurationMap read ownerMatch configure failed with error: %s",
1041 configuration.status().msg().c_str());
1042 }
1043 key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
1044 configuration = mConfigurationMap.readValue(key);
1045 if (isOk(configuration)) {
1046 dw.println("current statsMap configuration: %d", configuration.value());
1047 } else {
1048 dw.println("mConfigurationMap read stats map configure failed with error: %s",
1049 configuration.status().msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001050 }
Chenbo Feng703798e2018-06-15 17:07:59 -07001051 dumpBpfMap("mUidOwnerMap", dw, "");
Rubin Xuec27ff22019-01-08 21:33:03 +00001052 const auto printUidMatchInfo = [&dw, this](const uint32_t& key, const UidOwnerValue& value,
1053 const BpfMap<uint32_t, UidOwnerValue>&) {
1054 if (value.rule & IIF_MATCH) {
1055 auto ifname = mIfaceIndexNameMap.readValue(value.iif);
1056 if (isOk(ifname)) {
1057 dw.println("%u %s %s", key, uidMatchTypeToString(value.rule).c_str(),
1058 ifname.value().name);
1059 } else {
1060 dw.println("%u %s %u", key, uidMatchTypeToString(value.rule).c_str(), value.iif);
1061 }
1062 } else {
1063 dw.println("%u %s", key, uidMatchTypeToString(value.rule).c_str());
1064 }
Chenbo Feng703798e2018-06-15 17:07:59 -07001065 return netdutils::status::ok;
1066 };
1067 res = mUidOwnerMap.iterateWithValue(printUidMatchInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001068 if (!isOk(res)) {
Chenbo Feng703798e2018-06-15 17:07:59 -07001069 dw.println("mUidOwnerMap print end with error: %s", res.msg().c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -07001070 }
Chenbo Feng48eaed32018-12-26 17:40:21 -08001071 dumpBpfMap("mUidPermissionMap", dw, "");
1072 const auto printUidPermissionInfo = [&dw](const uint32_t& key, const uint8_t& value,
1073 const BpfMap<uint32_t, uint8_t>&) {
1074 dw.println("%u %s", key, UidPermissionTypeToString(value).c_str());
1075 return netdutils::status::ok;
1076 };
1077 res = mUidPermissionMap.iterateWithValue(printUidPermissionInfo);
1078 if (!isOk(res)) {
1079 dw.println("mUidPermissionMap print end with error: %s", res.msg().c_str());
1080 }
1081
1082 dumpBpfMap("mPrivilegedUser", dw, "");
1083 for (uid_t uid : mPrivilegedUser) {
1084 dw.println("%u ALLOW_UPDATE_DEVICE_STATS", (uint32_t)uid);
1085 }
Chenbo Fengef297172018-03-26 10:53:33 -07001086}
1087
Chenbo Fengf2759682017-10-10 17:31:57 -07001088} // namespace net
1089} // namespace android