blob: f065e5e1ce4fe4a253085a6c0ec9fa6bc7de0afd [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 Feng82075e52019-04-12 19:21:47 -070075constexpr int PER_UID_STATS_ENTRIES_LIMIT = 500;
76constexpr int TOTAL_UID_STATS_ENTRIES_LIMIT = STATS_MAP_SIZE - 500;
Chenbo Feng116d0552017-12-04 17:25:19 -080077
Chenbo Fengbf660aa2019-02-26 16:12:27 -080078static_assert(BPF_PERMISSION_INTERNET == INetd::PERMISSION_INTERNET,
79 "Mismatch between BPF and AIDL permissions: PERMISSION_INTERNET");
80static_assert(BPF_PERMISSION_UPDATE_DEVICE_STATS == INetd::PERMISSION_UPDATE_DEVICE_STATS,
81 "Mismatch between BPF and AIDL permissions: PERMISSION_UPDATE_DEVICE_STATS");
82
Chenbo Feng48eaed32018-12-26 17:40:21 -080083#define FLAG_MSG_TRANS(result, flag, value) \
84 do { \
85 if (value & flag) { \
86 result.append(StringPrintf(" %s", #flag)); \
87 value &= ~flag; \
88 } \
Chenbo Feng703798e2018-06-15 17:07:59 -070089 } while (0)
90
91const std::string uidMatchTypeToString(uint8_t match) {
92 std::string matchType;
Chenbo Feng48eaed32018-12-26 17:40:21 -080093 FLAG_MSG_TRANS(matchType, HAPPY_BOX_MATCH, match);
94 FLAG_MSG_TRANS(matchType, PENALTY_BOX_MATCH, match);
95 FLAG_MSG_TRANS(matchType, DOZABLE_MATCH, match);
96 FLAG_MSG_TRANS(matchType, STANDBY_MATCH, match);
97 FLAG_MSG_TRANS(matchType, POWERSAVE_MATCH, match);
Rubin Xuec27ff22019-01-08 21:33:03 +000098 FLAG_MSG_TRANS(matchType, IIF_MATCH, match);
Chenbo Feng703798e2018-06-15 17:07:59 -070099 if (match) {
100 return StringPrintf("Unknown match: %u", match);
101 }
102 return matchType;
103}
104
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800105bool TrafficController::hasUpdateDeviceStatsPermission(uid_t uid) {
Chenbo Feng3969c262019-03-19 14:53:57 -0700106 // This implementation is the same logic as method ActivityManager#checkComponentPermission.
107 // It implies that the calling uid can never be the same as PER_USER_RANGE.
108 uint32_t appId = uid % PER_USER_RANGE;
109 return ((appId == AID_ROOT) || (appId == AID_SYSTEM) ||
110 mPrivilegedUser.find(appId) != mPrivilegedUser.end());
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800111}
112
Chenbo Feng48eaed32018-12-26 17:40:21 -0800113const std::string UidPermissionTypeToString(uint8_t permission) {
Chenbo Fengbf660aa2019-02-26 16:12:27 -0800114 if (permission == INetd::NO_PERMISSIONS) {
115 return "NO_PERMISSIONS";
116 }
Chenbo Feng527908a2019-04-02 20:14:11 -0700117 if (permission == INetd::PERMISSION_UNINSTALLED) {
118 // This should never appear in the map, complain loudly if it does.
119 return "PERMISSION_UNINSTALLED error!";
120 }
Chenbo Feng48eaed32018-12-26 17:40:21 -0800121 std::string permissionType;
Chenbo Fengbf660aa2019-02-26 16:12:27 -0800122 FLAG_MSG_TRANS(permissionType, BPF_PERMISSION_INTERNET, permission);
123 FLAG_MSG_TRANS(permissionType, BPF_PERMISSION_UPDATE_DEVICE_STATS, permission);
Chenbo Feng48eaed32018-12-26 17:40:21 -0800124 if (permission) {
125 return StringPrintf("Unknown permission: %u", permission);
126 }
127 return permissionType;
128}
129
Chenbo Feng49586642018-08-30 18:01:53 -0700130StatusOr<std::unique_ptr<NetlinkListenerInterface>> TrafficController::makeSkDestroyListener() {
Chenbo Feng116d0552017-12-04 17:25:19 -0800131 const auto& sys = sSyscalls.get();
132 ASSIGN_OR_RETURN(auto event, sys.eventfd(0, EFD_CLOEXEC));
133 const int domain = AF_NETLINK;
134 const int type = SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK;
135 const int protocol = NETLINK_INET_DIAG;
136 ASSIGN_OR_RETURN(auto sock, sys.socket(domain, type, protocol));
137
Lorenzo Colitti436efdb2018-07-26 17:20:57 +0900138 // TODO: if too many sockets are closed too quickly, we can overflow the socket buffer, and
139 // some entries in mCookieTagMap will not be freed. In order to fix this we would need to
140 // periodically dump all sockets and remove the tag entries for sockets that have been closed.
141 // For now, set a large-enough buffer that we can close hundreds of sockets without getting
142 // ENOBUFS and leaking mCookieTagMap entries.
143 int rcvbuf = 512 * 1024;
144 auto ret = sys.setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf));
145 if (!ret.ok()) {
146 ALOGW("Failed to set SkDestroyListener buffer size to %d: %s", rcvbuf, ret.msg().c_str());
147 }
148
Chenbo Feng116d0552017-12-04 17:25:19 -0800149 sockaddr_nl addr = {
150 .nl_family = AF_NETLINK,
151 .nl_groups = 1 << (SKNLGRP_INET_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET_UDP_DESTROY - 1) |
152 1 << (SKNLGRP_INET6_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET6_UDP_DESTROY - 1)};
153 RETURN_IF_NOT_OK(sys.bind(sock, addr));
154
155 const sockaddr_nl kernel = {.nl_family = AF_NETLINK};
156 RETURN_IF_NOT_OK(sys.connect(sock, kernel));
157
158 std::unique_ptr<NetlinkListenerInterface> listener =
Chenbo Feng46296702018-08-23 12:20:22 -0700159 std::make_unique<NetlinkListener>(std::move(event), std::move(sock), "SkDestroyListen");
Chenbo Feng116d0552017-12-04 17:25:19 -0800160
161 return listener;
162}
163
Chenbo Feng89c12f12018-03-21 10:29:18 -0700164Status changeOwnerAndMode(const char* path, gid_t group, const char* debugName, bool netdOnly) {
165 int ret = chown(path, AID_ROOT, group);
166 if (ret != 0) return statusFromErrno(errno, StringPrintf("change %s group failed", debugName));
167
168 if (netdOnly) {
169 ret = chmod(path, S_IRWXU);
170 } else {
171 // Allow both netd and system server to obtain map fd from the path.
172 // chmod doesn't grant permission to all processes in that group to
173 // read/write the bpf map. They still need correct sepolicy to
174 // read/write the map.
Chenbo Fengf434e862018-06-27 14:08:39 -0700175 ret = chmod(path, S_IRWXU | S_IRGRP | S_IWGRP);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700176 }
177 if (ret != 0) return statusFromErrno(errno, StringPrintf("change %s mode failed", debugName));
178 return netdutils::status::ok;
179}
180
Chenbo Feng82075e52019-04-12 19:21:47 -0700181TrafficController::TrafficController()
182 : mBpfLevel(getBpfSupportLevel()),
183 mPerUidStatsEntriesLimit(PER_UID_STATS_ENTRIES_LIMIT),
184 mTotalUidStatsEntriesLimit(TOTAL_UID_STATS_ENTRIES_LIMIT) {}
185
186TrafficController::TrafficController(uint32_t perUidLimit, uint32_t totalLimit)
187 : mBpfLevel(getBpfSupportLevel()),
188 mPerUidStatsEntriesLimit(perUidLimit),
189 mTotalUidStatsEntriesLimit(totalLimit) {}
Chenbo Feng89c12f12018-03-21 10:29:18 -0700190
Chenbo Feng89c12f12018-03-21 10:29:18 -0700191Status TrafficController::initMaps() {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700192 std::lock_guard guard(mMutex);
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700193 RETURN_IF_NOT_OK(mCookieTagMap.init(COOKIE_TAG_MAP_PATH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700194 RETURN_IF_NOT_OK(changeOwnerAndMode(COOKIE_TAG_MAP_PATH, AID_NET_BW_ACCT, "CookieTagMap",
195 false));
196
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700197 RETURN_IF_NOT_OK(mUidCounterSetMap.init(UID_COUNTERSET_MAP_PATH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700198 RETURN_IF_NOT_OK(changeOwnerAndMode(UID_COUNTERSET_MAP_PATH, AID_NET_BW_ACCT,
199 "UidCounterSetMap", false));
200
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700201 RETURN_IF_NOT_OK(mAppUidStatsMap.init(APP_UID_STATS_MAP_PATH));
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700202 RETURN_IF_NOT_OK(
203 changeOwnerAndMode(APP_UID_STATS_MAP_PATH, AID_NET_BW_STATS, "AppUidStatsMap", false));
204
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700205 RETURN_IF_NOT_OK(mStatsMapA.init(STATS_MAP_A_PATH));
Chenbo Fengf434e862018-06-27 14:08:39 -0700206 RETURN_IF_NOT_OK(changeOwnerAndMode(STATS_MAP_A_PATH, AID_NET_BW_STATS, "StatsMapA", false));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700207
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700208 RETURN_IF_NOT_OK(mStatsMapB.init(STATS_MAP_B_PATH));
Chenbo Fengf434e862018-06-27 14:08:39 -0700209 RETURN_IF_NOT_OK(changeOwnerAndMode(STATS_MAP_B_PATH, AID_NET_BW_STATS, "StatsMapB", false));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700210
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700211 RETURN_IF_NOT_OK(mIfaceIndexNameMap.init(IFACE_INDEX_NAME_MAP_PATH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700212 RETURN_IF_NOT_OK(changeOwnerAndMode(IFACE_INDEX_NAME_MAP_PATH, AID_NET_BW_STATS,
213 "IfaceIndexNameMap", false));
214
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700215 RETURN_IF_NOT_OK(mIfaceStatsMap.init(IFACE_STATS_MAP_PATH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700216 RETURN_IF_NOT_OK(changeOwnerAndMode(IFACE_STATS_MAP_PATH, AID_NET_BW_STATS, "IfaceStatsMap",
217 false));
Chenbo Feng95892f32018-06-07 14:52:02 -0700218
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700219 RETURN_IF_NOT_OK(mConfigurationMap.init(CONFIGURATION_MAP_PATH));
Chenbo Fengf434e862018-06-27 14:08:39 -0700220 RETURN_IF_NOT_OK(changeOwnerAndMode(CONFIGURATION_MAP_PATH, AID_NET_BW_STATS,
221 "ConfigurationMap", false));
Chenbo Feng703798e2018-06-15 17:07:59 -0700222 RETURN_IF_NOT_OK(
Chenbo Fengf434e862018-06-27 14:08:39 -0700223 mConfigurationMap.writeValue(UID_RULES_CONFIGURATION_KEY, DEFAULT_CONFIG, BPF_ANY));
224 RETURN_IF_NOT_OK(mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, SELECT_MAP_A,
225 BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700226
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700227 RETURN_IF_NOT_OK(mUidOwnerMap.init(UID_OWNER_MAP_PATH));
Chenbo Feng703798e2018-06-15 17:07:59 -0700228 RETURN_IF_NOT_OK(changeOwnerAndMode(UID_OWNER_MAP_PATH, AID_ROOT, "UidOwnerMap", true));
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900229 RETURN_IF_NOT_OK(mUidOwnerMap.clear());
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700230 RETURN_IF_NOT_OK(mUidPermissionMap.init(UID_PERMISSION_MAP_PATH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700231 return netdutils::status::ok;
232}
233
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800234static Status attachProgramToCgroup(const char* programPath, const int cgroupFd,
235 bpf_attach_type type) {
236 unique_fd cgroupProg(bpfFdGet(programPath, 0));
237 if (cgroupProg == -1) {
238 int ret = errno;
239 ALOGE("Failed to get program from %s: %s", programPath, strerror(ret));
240 return statusFromErrno(ret, "cgroup program get failed");
241 }
242 if (android::bpf::attachProgram(type, cgroupProg, cgroupFd)) {
243 int ret = errno;
244 ALOGE("Program from %s attach failed: %s", programPath, strerror(ret));
245 return statusFromErrno(ret, "program attach failed");
246 }
247 return netdutils::status::ok;
248}
249
250static Status initPrograms() {
Suren Baghdasaryane072a3c2019-01-16 14:36:07 -0800251 std::string cg2_path;
252
253 if (!CgroupGetControllerPath(CGROUPV2_CONTROLLER_NAME, &cg2_path)) {
254 int ret = errno;
255 ALOGE("Failed to find cgroup v2 root");
256 return statusFromErrno(ret, "Failed to find cgroup v2 root");
257 }
258
259 unique_fd cg_fd(open(cg2_path.c_str(), O_DIRECTORY | O_RDONLY | O_CLOEXEC));
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800260 if (cg_fd == -1) {
261 int ret = errno;
262 ALOGE("Failed to open the cgroup directory: %s", strerror(ret));
263 return statusFromErrno(ret, "Open the cgroup directory failed");
264 }
265 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_EGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_EGRESS));
266 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_INGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_INGRESS));
Chenbo Fenga51f4fa2019-01-15 15:03:32 -0800267
268 // For the devices that support cgroup socket filter, the socket filter
269 // should be loaded successfully by bpfloader. So we attach the filter to
270 // cgroup if the program is pinned properly.
271 // TODO: delete the if statement once all devices should support cgroup
272 // socket filter (ie. the minimum kernel version required is 4.14).
273 if (!access(CGROUP_SOCKET_PROG_PATH, F_OK)) {
274 RETURN_IF_NOT_OK(
275 attachProgramToCgroup(CGROUP_SOCKET_PROG_PATH, cg_fd, BPF_CGROUP_INET_SOCK_CREATE));
276 }
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800277 return netdutils::status::ok;
278}
279
Chenbo Feng89c12f12018-03-21 10:29:18 -0700280Status TrafficController::start() {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800281 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800282 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700283 }
284
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900285 /* When netd restarts from a crash without total system reboot, the program
Chenbo Fengf2759682017-10-10 17:31:57 -0700286 * is still attached to the cgroup, detach it so the program can be freed
287 * and we can load and attach new program into the target cgroup.
288 *
289 * TODO: Scrape existing socket when run-time restart and clean up the map
290 * if the socket no longer exist
291 */
292
Chenbo Feng89c12f12018-03-21 10:29:18 -0700293 RETURN_IF_NOT_OK(initMaps());
Chenbo Feng7e974052018-02-28 22:57:21 -0800294
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800295 RETURN_IF_NOT_OK(initPrograms());
296
Chenbo Feng7e974052018-02-28 22:57:21 -0800297 // Fetch the list of currently-existing interfaces. At this point NetlinkHandler is
298 // already running, so it will call addInterface() when any new interface appears.
299 std::map<std::string, uint32_t> ifacePairs;
300 ASSIGN_OR_RETURN(ifacePairs, InterfaceController::getIfaceList());
301 for (const auto& ifacePair:ifacePairs) {
302 addInterface(ifacePair.first.c_str(), ifacePair.second);
303 }
304
Chenbo Feng116d0552017-12-04 17:25:19 -0800305 auto result = makeSkDestroyListener();
306 if (!isOk(result)) {
307 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
308 } else {
309 mSkDestroyListener = std::move(result.value());
310 }
311 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
312 const auto rxHandler = [this](const nlmsghdr&, const Slice msg) {
313 inet_diag_msg diagmsg = {};
314 if (extract(msg, diagmsg) < sizeof(inet_diag_msg)) {
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900315 ALOGE("Unrecognized netlink message: %s", toString(msg).c_str());
Chenbo Feng116d0552017-12-04 17:25:19 -0800316 return;
317 }
318 uint64_t sock_cookie = static_cast<uint64_t>(diagmsg.id.idiag_cookie[0]) |
319 (static_cast<uint64_t>(diagmsg.id.idiag_cookie[1]) << 32);
320
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900321 Status s = mCookieTagMap.deleteValue(sock_cookie);
Chenbo Feng1d4c5db2018-10-18 15:50:46 -0700322 if (!isOk(s) && s.code() != ENOENT) {
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900323 ALOGE("Failed to delete cookie %" PRIx64 ": %s", sock_cookie, toString(s).c_str());
324 return;
325 }
Chenbo Feng116d0552017-12-04 17:25:19 -0800326 };
327 expectOk(mSkDestroyListener->subscribe(kSockDiagMsgType, rxHandler));
328
329 // In case multiple netlink message comes in as a stream, we need to handle the rxDone message
330 // properly.
331 const auto rxDoneHandler = [](const nlmsghdr&, const Slice msg) {
332 // Ignore NLMSG_DONE messages
333 inet_diag_msg diagmsg = {};
334 extract(msg, diagmsg);
335 };
336 expectOk(mSkDestroyListener->subscribe(kSockDiagDoneMsgType, rxDoneHandler));
337
Chenbo Feng05393d82018-01-09 15:18:43 -0800338 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700339}
340
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800341int TrafficController::tagSocket(int sockFd, uint32_t tag, uid_t uid, uid_t callingUid) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700342 std::lock_guard guard(mMutex);
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800343 if (uid != callingUid && !hasUpdateDeviceStatsPermission(callingUid)) {
344 return -EPERM;
345 }
346
Chenbo Feng47dd0732018-12-11 12:23:24 -0800347 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700348 if (legacy_tagSocket(sockFd, tag, uid)) return -errno;
349 return 0;
350 }
Chenbo Feng33cc1032017-10-23 15:16:37 -0700351
Chenbo Fengf2759682017-10-10 17:31:57 -0700352 uint64_t sock_cookie = getSocketCookie(sockFd);
Chenbo Fengef1cab32018-04-13 19:50:49 -0700353 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
Chenbo Fengf2759682017-10-10 17:31:57 -0700354 UidTag newKey = {.uid = (uint32_t)uid, .tag = tag};
355
Chenbo Fengb0495132019-04-10 12:54:41 -0700356 uint32_t totalEntryCount = 0;
Chenbo Feng82075e52019-04-12 19:21:47 -0700357 uint32_t perUidEntryCount = 0;
Chenbo Fengb0495132019-04-10 12:54:41 -0700358 // Now we go through the stats map and count how many entries are associated
359 // with target uid. If the uid entry hit the limit for each uid, we block
360 // the request to prevent the map from overflow. It is safe here to iterate
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700361 // over the map since when mMutex is hold, system server cannot toggle
Chenbo Fengb0495132019-04-10 12:54:41 -0700362 // the live stats map and clean it. So nobody can delete entries from the map.
Chenbo Feng82075e52019-04-12 19:21:47 -0700363 const auto countUidStatsEntries = [uid, &totalEntryCount, &perUidEntryCount](
364 const StatsKey& key, BpfMap<StatsKey, StatsValue>&) {
Chenbo Fengb0495132019-04-10 12:54:41 -0700365 if (key.uid == uid) {
Chenbo Feng82075e52019-04-12 19:21:47 -0700366 perUidEntryCount++;
Chenbo Fengb0495132019-04-10 12:54:41 -0700367 }
Chenbo Feng82075e52019-04-12 19:21:47 -0700368 totalEntryCount++;
Chenbo Fengb0495132019-04-10 12:54:41 -0700369 return netdutils::status::ok;
370 };
371 auto configuration = mConfigurationMap.readValue(CURRENT_STATS_MAP_CONFIGURATION_KEY);
372 if (!isOk(configuration.status())) {
373 ALOGE("Failed to get current configuration: %s, fd: %d",
374 strerror(configuration.status().code()), mConfigurationMap.getMap().get());
375 return -configuration.status().code();
376 }
Chenbo Feng36a40d12019-04-23 16:47:05 -0700377 if (configuration.value() != SELECT_MAP_A && configuration.value() != SELECT_MAP_B) {
Chenbo Fengb0495132019-04-10 12:54:41 -0700378 ALOGE("unknown configuration value: %d", configuration.value());
379 return -EINVAL;
380 }
Chenbo Feng36a40d12019-04-23 16:47:05 -0700381
382 BpfMap<StatsKey, StatsValue>& currentMap =
383 (configuration.value() == SELECT_MAP_A) ? mStatsMapA : mStatsMapB;
384 Status res = currentMap.iterate(countUidStatsEntries);
385 if (!isOk(res)) {
386 ALOGE("Failed to count the stats entry in map %d: %s", currentMap.getMap().get(),
387 strerror(res.code()));
388 return -res.code();
389 }
390
Chenbo Feng82075e52019-04-12 19:21:47 -0700391 if (totalEntryCount > mTotalUidStatsEntriesLimit ||
392 perUidEntryCount > mPerUidStatsEntriesLimit) {
393 ALOGE("Too many stats entries in the map, total count: %u, uid(%u) count: %u, blocking tag"
394 " request to prevent map overflow",
395 totalEntryCount, uid, perUidEntryCount);
Chenbo Fengb0495132019-04-10 12:54:41 -0700396 return -EMFILE;
397 }
Chenbo Fengf2759682017-10-10 17:31:57 -0700398 // Update the tag information of a socket to the cookieUidMap. Use BPF_ANY
399 // flag so it will insert a new entry to the map if that value doesn't exist
400 // yet. And update the tag if there is already a tag stored. Since the eBPF
401 // program in kernel only read this map, and is protected by rcu read lock. It
402 // should be fine to cocurrently update the map while eBPF program is running.
Chenbo Feng36a40d12019-04-23 16:47:05 -0700403 res = mCookieTagMap.writeValue(sock_cookie, newKey, BPF_ANY);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700404 if (!isOk(res)) {
405 ALOGE("Failed to tag the socket: %s, fd: %d", strerror(res.code()),
406 mCookieTagMap.getMap().get());
Chenbo Fengf2759682017-10-10 17:31:57 -0700407 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700408 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700409}
410
411int TrafficController::untagSocket(int sockFd) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800412 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700413 if (legacy_untagSocket(sockFd)) return -errno;
414 return 0;
415 }
Chenbo Fengf2759682017-10-10 17:31:57 -0700416 uint64_t sock_cookie = getSocketCookie(sockFd);
417
Chenbo Fengef1cab32018-04-13 19:50:49 -0700418 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700419 Status res = mCookieTagMap.deleteValue(sock_cookie);
420 if (!isOk(res)) {
421 ALOGE("Failed to untag socket: %s\n", strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700422 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700423 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700424}
425
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800426int TrafficController::setCounterSet(int counterSetNum, uid_t uid, uid_t callingUid) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700427 if (counterSetNum < 0 || counterSetNum >= OVERFLOW_COUNTERSET) return -EINVAL;
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800428
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700429 std::lock_guard guard(mMutex);
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800430 if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
431
Chenbo Feng47dd0732018-12-11 12:23:24 -0800432 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700433 if (legacy_setCounterSet(counterSetNum, uid)) return -errno;
434 return 0;
435 }
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800436
437 // The default counter set for all uid is 0, so deleting the current counterset for that uid
438 // will automatically set it to 0.
Chenbo Fengf2759682017-10-10 17:31:57 -0700439 if (counterSetNum == 0) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700440 Status res = mUidCounterSetMap.deleteValue(uid);
441 if (isOk(res) || (!isOk(res) && res.code() == ENOENT)) {
Chenbo Fengf2759682017-10-10 17:31:57 -0700442 return 0;
443 } else {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700444 ALOGE("Failed to delete the counterSet: %s\n", strerror(res.code()));
445 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700446 }
447 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700448 uint8_t tmpCounterSetNum = (uint8_t)counterSetNum;
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800449 Status res = mUidCounterSetMap.writeValue(uid, tmpCounterSetNum, BPF_ANY);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700450 if (!isOk(res)) {
451 ALOGE("Failed to set the counterSet: %s, fd: %d", strerror(res.code()),
452 mUidCounterSetMap.getMap().get());
453 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700454 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700455 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700456}
457
Chenbo Fengf434e862018-06-27 14:08:39 -0700458// This method only get called by system_server when an app get uinstalled, it
459// is called inside removeUidsLocked() while holding mStatsLock. So it is safe
460// to iterate and modify the stats maps.
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800461int TrafficController::deleteTagData(uint32_t tag, uid_t uid, uid_t callingUid) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700462 std::lock_guard guard(mMutex);
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800463 if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
464
Chenbo Feng47dd0732018-12-11 12:23:24 -0800465 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700466 if (legacy_deleteTagData(tag, uid)) return -errno;
467 return 0;
468 }
Chenbo Feng33cc1032017-10-23 15:16:37 -0700469
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800470 // First we go through the cookieTagMap to delete the target uid tag combination. Or delete all
Chenbo Fengef1cab32018-04-13 19:50:49 -0700471 // the tags related to the uid if the tag is 0.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700472 const auto deleteMatchedCookieEntries = [uid, tag](const uint64_t& key, const UidTag& value,
473 BpfMap<uint64_t, UidTag>& map) {
474 if (value.uid == uid && (value.tag == tag || tag == 0)) {
475 Status res = map.deleteValue(key);
476 if (isOk(res) || (res.code() == ENOENT)) {
477 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700478 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700479 ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s\n", key, strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700480 }
Chenbo Fengef1cab32018-04-13 19:50:49 -0700481 // Move forward to next cookie in the map.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700482 return netdutils::status::ok;
Chenbo Fengef1cab32018-04-13 19:50:49 -0700483 };
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900484 mCookieTagMap.iterateWithValue(deleteMatchedCookieEntries).ignoreError();
Chenbo Fengf2759682017-10-10 17:31:57 -0700485 // 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 -0700486 // combination. Or all tag stats under that uid if the target tag is 0.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700487 const auto deleteMatchedUidTagEntries = [uid, tag](const StatsKey& key,
488 BpfMap<StatsKey, StatsValue>& map) {
489 if (key.uid == uid && (key.tag == tag || tag == 0)) {
490 Status res = map.deleteValue(key);
491 if (isOk(res) || (res.code() == ENOENT)) {
Chenbo Fengef1cab32018-04-13 19:50:49 -0700492 //Entry is deleted, use the current key to get a new nextKey;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700493 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700494 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700495 ALOGE("Failed to delete data(uid=%u, tag=%u): %s\n", key.uid, key.tag,
496 strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700497 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700498 return netdutils::status::ok;
Chenbo Fengef1cab32018-04-13 19:50:49 -0700499 };
Chenbo Fengf434e862018-06-27 14:08:39 -0700500 mStatsMapB.iterate(deleteMatchedUidTagEntries).ignoreError();
501 mStatsMapA.iterate(deleteMatchedUidTagEntries).ignoreError();
Chenbo Fengf2759682017-10-10 17:31:57 -0700502 // 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 -0800503 // need to delete the stats stored in uidStatsMap and counterSet map.
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800504 if (tag != 0) return 0;
505
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700506 Status res = mUidCounterSetMap.deleteValue(uid);
507 if (!isOk(res) && res.code() != ENOENT) {
508 ALOGE("Failed to delete counterSet data(uid=%u, tag=%u): %s\n", uid, tag,
509 strerror(res.code()));
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800510 }
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700511
512 auto deleteAppUidStatsEntry = [uid](const uint32_t& key, BpfMap<uint32_t, StatsValue>& map) {
513 if (key == uid) {
514 Status res = map.deleteValue(key);
515 if (isOk(res) || (res.code() == ENOENT)) {
516 return netdutils::status::ok;
517 }
518 ALOGE("Failed to delete data(uid=%u): %s", key, strerror(res.code()));
519 }
520 return netdutils::status::ok;
521 };
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900522 mAppUidStatsMap.iterate(deleteAppUidStatsEntry).ignoreError();
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700523 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700524}
525
Chenbo Feng7e974052018-02-28 22:57:21 -0800526int TrafficController::addInterface(const char* name, uint32_t ifaceIndex) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800527 if (mBpfLevel == BpfLevel::NONE) return 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800528
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700529 IfaceValue iface;
Chenbo Feng7e974052018-02-28 22:57:21 -0800530 if (ifaceIndex == 0) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700531 ALOGE("Unknown interface %s(%d)", name, ifaceIndex);
Chenbo Feng7e974052018-02-28 22:57:21 -0800532 return -1;
533 }
534
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700535 strlcpy(iface.name, name, sizeof(IfaceValue));
536 Status res = mIfaceIndexNameMap.writeValue(ifaceIndex, iface, BPF_ANY);
537 if (!isOk(res)) {
538 ALOGE("Failed to add iface %s(%d): %s", name, ifaceIndex, strerror(res.code()));
539 return -res.code();
Chenbo Feng7e974052018-02-28 22:57:21 -0800540 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700541 return 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800542}
543
Chenbo Feng703798e2018-06-15 17:07:59 -0700544Status TrafficController::updateOwnerMapEntry(UidOwnerMatchType match, uid_t uid, FirewallRule rule,
545 FirewallType type) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700546 std::lock_guard guard(mMutex);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700547 if ((rule == ALLOW && type == WHITELIST) || (rule == DENY && type == BLACKLIST)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100548 RETURN_IF_NOT_OK(addRule(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700549 } else if ((rule == ALLOW && type == BLACKLIST) || (rule == DENY && type == WHITELIST)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100550 RETURN_IF_NOT_OK(removeRule(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700551 } else {
552 //Cannot happen.
Rubin Xuec27ff22019-01-08 21:33:03 +0000553 return statusFromErrno(EINVAL, "");
Chenbo Feng89c12f12018-03-21 10:29:18 -0700554 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700555 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700556}
557
Chenbo Feng703798e2018-06-15 17:07:59 -0700558UidOwnerMatchType TrafficController::jumpOpToMatch(BandwidthController::IptJumpOp jumpHandling) {
Chenbo Feng95892f32018-06-07 14:52:02 -0700559 switch (jumpHandling) {
560 case BandwidthController::IptJumpReject:
Chenbo Feng703798e2018-06-15 17:07:59 -0700561 return PENALTY_BOX_MATCH;
Chenbo Feng95892f32018-06-07 14:52:02 -0700562 case BandwidthController::IptJumpReturn:
Chenbo Feng703798e2018-06-15 17:07:59 -0700563 return HAPPY_BOX_MATCH;
Chenbo Feng95892f32018-06-07 14:52:02 -0700564 case BandwidthController::IptJumpNoAdd:
565 return NO_MATCH;
566 }
567}
568
Rubin Xu5ca8e802019-04-05 11:50:32 +0100569Status TrafficController::removeRule(BpfMap<uint32_t, UidOwnerValue>& map, uint32_t uid,
570 UidOwnerMatchType match) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700571 auto oldMatch = map.readValue(uid);
572 if (isOk(oldMatch)) {
Rubin Xuec27ff22019-01-08 21:33:03 +0000573 UidOwnerValue newMatch = {.rule = static_cast<uint8_t>(oldMatch.value().rule & ~match),
574 .iif = (match == IIF_MATCH) ? 0 : oldMatch.value().iif};
575 if (newMatch.rule == 0) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700576 RETURN_IF_NOT_OK(map.deleteValue(uid));
577 } else {
578 RETURN_IF_NOT_OK(map.writeValue(uid, newMatch, BPF_ANY));
579 }
580 } else {
581 return statusFromErrno(ENOENT, StringPrintf("uid: %u does not exist in map", uid));
582 }
583 return netdutils::status::ok;
584}
585
Rubin Xu5ca8e802019-04-05 11:50:32 +0100586Status TrafficController::addRule(BpfMap<uint32_t, UidOwnerValue>& map, uint32_t uid,
587 UidOwnerMatchType match, uint32_t iif) {
Rubin Xuec27ff22019-01-08 21:33:03 +0000588 // iif should be non-zero if and only if match == MATCH_IIF
589 if (match == IIF_MATCH && iif == 0) {
590 return statusFromErrno(EINVAL, "Interface match must have nonzero interface index");
591 } else if (match != IIF_MATCH && iif != 0) {
592 return statusFromErrno(EINVAL, "Non-interface match must have zero interface index");
593 }
Chenbo Feng703798e2018-06-15 17:07:59 -0700594 auto oldMatch = map.readValue(uid);
595 if (isOk(oldMatch)) {
Rubin Xuec27ff22019-01-08 21:33:03 +0000596 UidOwnerValue newMatch = {.rule = static_cast<uint8_t>(oldMatch.value().rule | match),
597 .iif = iif ? iif : oldMatch.value().iif};
598 RETURN_IF_NOT_OK(map.writeValue(uid, newMatch, BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700599 } else {
Rubin Xuec27ff22019-01-08 21:33:03 +0000600 UidOwnerValue newMatch = {.rule = static_cast<uint8_t>(match), .iif = iif};
601 RETURN_IF_NOT_OK(map.writeValue(uid, newMatch, BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700602 }
603 return netdutils::status::ok;
604}
605
606Status TrafficController::updateUidOwnerMap(const std::vector<std::string>& appStrUids,
607 BandwidthController::IptJumpOp jumpHandling,
608 BandwidthController::IptOp op) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700609 std::lock_guard guard(mMutex);
Chenbo Feng703798e2018-06-15 17:07:59 -0700610 UidOwnerMatchType match = jumpOpToMatch(jumpHandling);
611 if (match == NO_MATCH) {
612 return statusFromErrno(
613 EINVAL, StringPrintf("invalid IptJumpOp: %d, command: %d", jumpHandling, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700614 }
615 for (const auto& appStrUid : appStrUids) {
616 char* endPtr;
617 long uid = strtol(appStrUid.c_str(), &endPtr, 10);
618 if ((errno == ERANGE && (uid == LONG_MAX || uid == LONG_MIN)) ||
619 (endPtr == appStrUid.c_str()) || (*endPtr != '\0')) {
620 return statusFromErrno(errno, "invalid uid string:" + appStrUid);
621 }
622
Chenbo Feng95892f32018-06-07 14:52:02 -0700623 if (op == BandwidthController::IptOpDelete) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100624 RETURN_IF_NOT_OK(removeRule(mUidOwnerMap, uid, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700625 } else if (op == BandwidthController::IptOpInsert) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100626 RETURN_IF_NOT_OK(addRule(mUidOwnerMap, uid, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700627 } else {
628 // Cannot happen.
Chenbo Feng703798e2018-06-15 17:07:59 -0700629 return statusFromErrno(EINVAL, StringPrintf("invalid IptOp: %d, %d", op, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700630 }
631 }
632 return netdutils::status::ok;
633}
634
Chenbo Feng89c12f12018-03-21 10:29:18 -0700635int TrafficController::changeUidOwnerRule(ChildChain chain, uid_t uid, FirewallRule rule,
636 FirewallType type) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800637 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Feng89c12f12018-03-21 10:29:18 -0700638 ALOGE("bpf is not set up, should use iptables rule");
639 return -ENOSYS;
640 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700641 Status res;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700642 switch (chain) {
643 case DOZABLE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700644 res = updateOwnerMapEntry(DOZABLE_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700645 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700646 case STANDBY:
Chenbo Feng703798e2018-06-15 17:07:59 -0700647 res = updateOwnerMapEntry(STANDBY_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700648 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700649 case POWERSAVE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700650 res = updateOwnerMapEntry(POWERSAVE_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700651 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700652 case NONE:
653 default:
654 return -EINVAL;
655 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700656 if (!isOk(res)) {
657 ALOGE("change uid(%u) rule of %d failed: %s, rule: %d, type: %d", uid, chain,
658 res.msg().c_str(), rule, type);
659 return -res.code();
660 }
661 return 0;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700662}
663
Rubin Xu5ca8e802019-04-05 11:50:32 +0100664Status TrafficController::replaceRulesInMap(const UidOwnerMatchType match,
665 const std::vector<int32_t>& uids) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700666 std::lock_guard guard(mMutex);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700667 std::set<int32_t> uidSet(uids.begin(), uids.end());
668 std::vector<uint32_t> uidsToDelete;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700669 auto getUidsToDelete = [&uidsToDelete, &uidSet](const uint32_t& key,
Rubin Xuec27ff22019-01-08 21:33:03 +0000670 const BpfMap<uint32_t, UidOwnerValue>&) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700671 if (uidSet.find((int32_t) key) == uidSet.end()) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700672 uidsToDelete.push_back(key);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700673 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700674 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700675 };
Chenbo Feng703798e2018-06-15 17:07:59 -0700676 RETURN_IF_NOT_OK(mUidOwnerMap.iterate(getUidsToDelete));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700677
678 for(auto uid : uidsToDelete) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100679 RETURN_IF_NOT_OK(removeRule(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700680 }
681
682 for (auto uid : uids) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100683 RETURN_IF_NOT_OK(addRule(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700684 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700685 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700686}
687
Rubin Xuec27ff22019-01-08 21:33:03 +0000688Status TrafficController::addUidInterfaceRules(const int iif,
689 const std::vector<int32_t>& uidsToAdd) {
690 if (mBpfLevel == BpfLevel::NONE) {
691 ALOGW("UID ingress interface filtering not possible without BPF owner match");
692 return statusFromErrno(EOPNOTSUPP, "eBPF not supported");
693 }
694 if (!iif) {
695 return statusFromErrno(EINVAL, "Interface rule must specify interface");
696 }
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700697 std::lock_guard guard(mMutex);
Rubin Xuec27ff22019-01-08 21:33:03 +0000698
699 for (auto uid : uidsToAdd) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100700 netdutils::Status result = addRule(mUidOwnerMap, uid, IIF_MATCH, iif);
Rubin Xuec27ff22019-01-08 21:33:03 +0000701 if (!isOk(result)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100702 ALOGW("addRule failed(%d): uid=%d iif=%d", result.code(), uid, iif);
Rubin Xuec27ff22019-01-08 21:33:03 +0000703 }
704 }
705 return netdutils::status::ok;
706}
707
708Status TrafficController::removeUidInterfaceRules(const std::vector<int32_t>& uidsToDelete) {
709 if (mBpfLevel == BpfLevel::NONE) {
710 ALOGW("UID ingress interface filtering not possible without BPF owner match");
711 return statusFromErrno(EOPNOTSUPP, "eBPF not supported");
712 }
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700713 std::lock_guard guard(mMutex);
Rubin Xuec27ff22019-01-08 21:33:03 +0000714
715 for (auto uid : uidsToDelete) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100716 netdutils::Status result = removeRule(mUidOwnerMap, uid, IIF_MATCH);
Rubin Xuec27ff22019-01-08 21:33:03 +0000717 if (!isOk(result)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100718 ALOGW("removeRule failed(%d): uid=%d", result.code(), uid);
Rubin Xuec27ff22019-01-08 21:33:03 +0000719 }
720 }
721 return netdutils::status::ok;
722}
723
Chenbo Feng89c12f12018-03-21 10:29:18 -0700724int TrafficController::replaceUidOwnerMap(const std::string& name, bool isWhitelist,
725 const std::vector<int32_t>& uids) {
Chenbo Feng89c12f12018-03-21 10:29:18 -0700726 FirewallRule rule;
727 FirewallType type;
728 if (isWhitelist) {
729 type = WHITELIST;
730 rule = ALLOW;
731 } else {
732 type = BLACKLIST;
733 rule = DENY;
734 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700735 Status res;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700736 if (!name.compare(FirewallController::LOCAL_DOZABLE)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100737 res = replaceRulesInMap(DOZABLE_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700738 } else if (!name.compare(FirewallController::LOCAL_STANDBY)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100739 res = replaceRulesInMap(STANDBY_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700740 } else if (!name.compare(FirewallController::LOCAL_POWERSAVE)) {
Rubin Xu5ca8e802019-04-05 11:50:32 +0100741 res = replaceRulesInMap(POWERSAVE_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700742 } else {
743 ALOGE("unknown chain name: %s", name.c_str());
744 return -EINVAL;
745 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700746 if (!isOk(res)) {
747 ALOGE("Failed to clean up chain: %s: %s", name.c_str(), res.msg().c_str());
748 return -res.code();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700749 }
750 return 0;
751}
752
753int TrafficController::toggleUidOwnerMap(ChildChain chain, bool enable) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700754 std::lock_guard guard(mMutex);
Chenbo Fengf434e862018-06-27 14:08:39 -0700755 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Chenbo Feng703798e2018-06-15 17:07:59 -0700756 auto oldConfiguration = mConfigurationMap.readValue(key);
757 if (!isOk(oldConfiguration)) {
758 ALOGE("Cannot read the old configuration from map: %s",
759 oldConfiguration.status().msg().c_str());
760 return -oldConfiguration.status().code();
761 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700762 Status res;
Chenbo Feng703798e2018-06-15 17:07:59 -0700763 BpfConfig newConfiguration;
764 uint8_t match;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700765 switch (chain) {
766 case DOZABLE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700767 match = DOZABLE_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700768 break;
769 case STANDBY:
Chenbo Feng703798e2018-06-15 17:07:59 -0700770 match = STANDBY_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700771 break;
772 case POWERSAVE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700773 match = POWERSAVE_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700774 break;
775 default:
776 return -EINVAL;
777 }
Chenbo Feng703798e2018-06-15 17:07:59 -0700778 newConfiguration =
779 enable ? (oldConfiguration.value() | match) : (oldConfiguration.value() & (~match));
780 res = mConfigurationMap.writeValue(key, newConfiguration, BPF_EXIST);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700781 if (!isOk(res)) {
782 ALOGE("Failed to toggleUidOwnerMap(%d): %s", chain, res.msg().c_str());
Chenbo Feng89c12f12018-03-21 10:29:18 -0700783 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700784 return -res.code();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700785}
786
Chenbo Feng47dd0732018-12-11 12:23:24 -0800787BpfLevel TrafficController::getBpfLevel() {
788 return mBpfLevel;
Chenbo Feng07d43fe2017-12-21 14:38:51 -0800789}
790
Chenbo Feng873ae142019-04-10 12:26:06 -0700791Status TrafficController::swapActiveStatsMap() {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700792 std::lock_guard guard(mMutex);
Chenbo Feng873ae142019-04-10 12:26:06 -0700793
794 if (mBpfLevel == BpfLevel::NONE) {
795 return statusFromErrno(EOPNOTSUPP, "This device doesn't have eBPF support");
796 }
797
798 uint32_t key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
799 auto oldConfiguration = mConfigurationMap.readValue(key);
800 if (!isOk(oldConfiguration)) {
801 ALOGE("Cannot read the old configuration from map: %s",
802 oldConfiguration.status().msg().c_str());
803 return oldConfiguration.status();
804 }
805
806 // Write to the configuration map to inform the kernel eBPF program to switch
807 // from using one map to the other. Use flag BPF_EXIST here since the map should
808 // be already populated in initMaps.
809 uint8_t newConfigure = (oldConfiguration.value() == SELECT_MAP_A) ? SELECT_MAP_B : SELECT_MAP_A;
810 Status res = mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, newConfigure,
811 BPF_EXIST);
812 if (!isOk(res)) {
813 ALOGE("Failed to toggle the stats map: %s", strerror(res.code()));
814 return res;
815 }
816 // After changing the config, we need to make sure all the current running
817 // eBPF programs are finished and all the CPUs are aware of this config change
818 // before we modify the old map. So we do a special hack here to wait for
819 // the kernel to do a synchronize_rcu(). Once the kernel called
820 // synchronize_rcu(), the config we just updated will be available to all cores
821 // and the next eBPF programs triggered inside the kernel will use the new
822 // map configuration. So once this function returns we can safely modify the
823 // old stats map without concerning about race between the kernel and
824 // userspace.
825 int ret = synchronizeKernelRCU();
826 if (ret) {
827 ALOGE("map swap synchronize_rcu() ended with failure: %s", strerror(-ret));
828 return statusFromErrno(-ret, "map swap synchronize_rcu() failed");
829 }
830 return netdutils::status::ok;
831}
832
Chenbo Feng48eaed32018-12-26 17:40:21 -0800833void TrafficController::setPermissionForUids(int permission, const std::vector<uid_t>& uids) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700834 std::lock_guard guard(mMutex);
Chenbo Fengbf660aa2019-02-26 16:12:27 -0800835 if (permission == INetd::PERMISSION_UNINSTALLED) {
836 for (uid_t uid : uids) {
837 // Clean up all permission information for the related uid if all the
838 // packages related to it are uninstalled.
839 mPrivilegedUser.erase(uid);
840 Status ret = mUidPermissionMap.deleteValue(uid);
841 }
842 return;
843 }
844
Chenbo Feng48eaed32018-12-26 17:40:21 -0800845 bool privileged = (permission & INetd::PERMISSION_UPDATE_DEVICE_STATS);
846
847 for (uid_t uid : uids) {
Chenbo Feng527908a2019-04-02 20:14:11 -0700848 // The map stores all the permissions that the UID has, except if the only permission
849 // the UID has is the INTERNET permission, then the UID should not appear in the map.
850 if (permission != INetd::PERMISSION_INTERNET) {
Chenbo Fengbf660aa2019-02-26 16:12:27 -0800851 Status ret = mUidPermissionMap.writeValue(uid, permission, BPF_ANY);
Chenbo Feng48eaed32018-12-26 17:40:21 -0800852 if (!isOk(ret)) {
Chenbo Feng527908a2019-04-02 20:14:11 -0700853 ALOGE("Failed to set permission: %s of uid(%u) to permission map: %s",
854 UidPermissionTypeToString(permission).c_str(), uid, strerror(ret.code()));
Chenbo Feng48eaed32018-12-26 17:40:21 -0800855 }
856 } else {
857 Status ret = mUidPermissionMap.deleteValue(uid);
858 if (!isOk(ret) && ret.code() != ENOENT) {
Chenbo Feng527908a2019-04-02 20:14:11 -0700859 ALOGE("Failed to remove uid %u from permission map: %s", uid, strerror(ret.code()));
Chenbo Feng48eaed32018-12-26 17:40:21 -0800860 }
861 }
862
863 if (privileged) {
864 mPrivilegedUser.insert(uid);
865 } else {
866 mPrivilegedUser.erase(uid);
867 }
868 }
869}
870
Chenbo Fengef297172018-03-26 10:53:33 -0700871std::string getProgramStatus(const char *path) {
872 int ret = access(path, R_OK);
873 if (ret == 0) {
874 return StringPrintf("OK");
875 }
876 if (ret != 0 && errno == ENOENT) {
877 return StringPrintf("program is missing at: %s", path);
878 }
879 return StringPrintf("check Program %s error: %s", path, strerror(errno));
880}
881
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700882std::string getMapStatus(const base::unique_fd& map_fd, const char* path) {
Chenbo Fengef297172018-03-26 10:53:33 -0700883 if (map_fd.get() < 0) {
884 return StringPrintf("map fd lost");
885 }
886 if (access(path, F_OK) != 0) {
887 return StringPrintf("map not pinned to location: %s", path);
888 }
889 return StringPrintf("OK");
890}
891
Bernie Innocentia5161a02019-01-30 22:40:53 +0900892// NOLINTNEXTLINE(google-runtime-references): grandfathered pass by non-const reference
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900893void dumpBpfMap(const std::string& mapName, DumpWriter& dw, const std::string& header) {
Chenbo Fengef297172018-03-26 10:53:33 -0700894 dw.blankline();
895 dw.println("%s:", mapName.c_str());
Erik Klineb31fd692018-06-06 20:50:11 +0900896 if (!header.empty()) {
897 dw.println(header);
Chenbo Fengef297172018-03-26 10:53:33 -0700898 }
899}
900
901const String16 TrafficController::DUMP_KEYWORD = String16("trafficcontroller");
902
903void TrafficController::dump(DumpWriter& dw, bool verbose) {
Chenbo Feng84d9f9f2019-04-12 15:31:02 -0700904 std::lock_guard guard(mMutex);
Erik Klineb31fd692018-06-06 20:50:11 +0900905 ScopedIndent indentTop(dw);
Chenbo Fengef297172018-03-26 10:53:33 -0700906 dw.println("TrafficController");
907
Erik Klineb31fd692018-06-06 20:50:11 +0900908 ScopedIndent indentPreBpfModule(dw);
Chenbo Feng47dd0732018-12-11 12:23:24 -0800909 dw.println("BPF module status: %s", BpfLevelToString(mBpfLevel).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700910
Chenbo Feng47dd0732018-12-11 12:23:24 -0800911 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengef297172018-03-26 10:53:33 -0700912 return;
Erik Klineb31fd692018-06-06 20:50:11 +0900913 }
Chenbo Fengef297172018-03-26 10:53:33 -0700914
915 dw.blankline();
916 dw.println("mCookieTagMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700917 getMapStatus(mCookieTagMap.getMap(), COOKIE_TAG_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700918 dw.println("mUidCounterSetMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700919 getMapStatus(mUidCounterSetMap.getMap(), UID_COUNTERSET_MAP_PATH).c_str());
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700920 dw.println("mAppUidStatsMap status: %s",
921 getMapStatus(mAppUidStatsMap.getMap(), APP_UID_STATS_MAP_PATH).c_str());
Chenbo Fengf434e862018-06-27 14:08:39 -0700922 dw.println("mStatsMapA status: %s",
923 getMapStatus(mStatsMapA.getMap(), STATS_MAP_A_PATH).c_str());
924 dw.println("mStatsMapB status: %s",
925 getMapStatus(mStatsMapB.getMap(), STATS_MAP_B_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700926 dw.println("mIfaceIndexNameMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700927 getMapStatus(mIfaceIndexNameMap.getMap(), IFACE_INDEX_NAME_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700928 dw.println("mIfaceStatsMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700929 getMapStatus(mIfaceStatsMap.getMap(), IFACE_STATS_MAP_PATH).c_str());
Chenbo Feng703798e2018-06-15 17:07:59 -0700930 dw.println("mConfigurationMap status: %s",
931 getMapStatus(mConfigurationMap.getMap(), CONFIGURATION_MAP_PATH).c_str());
932 dw.println("mUidOwnerMap status: %s",
933 getMapStatus(mUidOwnerMap.getMap(), UID_OWNER_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700934
935 dw.blankline();
936 dw.println("Cgroup ingress program status: %s",
937 getProgramStatus(BPF_INGRESS_PROG_PATH).c_str());
938 dw.println("Cgroup egress program status: %s", getProgramStatus(BPF_EGRESS_PROG_PATH).c_str());
939 dw.println("xt_bpf ingress program status: %s",
940 getProgramStatus(XT_BPF_INGRESS_PROG_PATH).c_str());
941 dw.println("xt_bpf egress program status: %s",
942 getProgramStatus(XT_BPF_EGRESS_PROG_PATH).c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700943 dw.println("xt_bpf bandwidth whitelist program status: %s",
944 getProgramStatus(XT_BPF_WHITELIST_PROG_PATH).c_str());
945 dw.println("xt_bpf bandwidth blacklist program status: %s",
946 getProgramStatus(XT_BPF_BLACKLIST_PROG_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700947
Erik Klineb31fd692018-06-06 20:50:11 +0900948 if (!verbose) {
949 return;
950 }
Chenbo Fengef297172018-03-26 10:53:33 -0700951
952 dw.blankline();
953 dw.println("BPF map content:");
954
Erik Klineb31fd692018-06-06 20:50:11 +0900955 ScopedIndent indentForMapContent(dw);
Chenbo Fengef297172018-03-26 10:53:33 -0700956
957 // Print CookieTagMap content.
958 dumpBpfMap("mCookieTagMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700959 const auto printCookieTagInfo = [&dw](const uint64_t& key, const UidTag& value,
960 const BpfMap<uint64_t, UidTag>&) {
961 dw.println("cookie=%" PRIu64 " tag=0x%x uid=%u", key, value.tag, value.uid);
962 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700963 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700964 Status res = mCookieTagMap.iterateWithValue(printCookieTagInfo);
965 if (!isOk(res)) {
966 dw.println("mCookieTagMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700967 }
968
969 // Print UidCounterSetMap Content
970 dumpBpfMap("mUidCounterSetMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700971 const auto printUidInfo = [&dw](const uint32_t& key, const uint8_t& value,
972 const BpfMap<uint32_t, uint8_t>&) {
973 dw.println("%u %u", key, value);
974 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700975 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700976 res = mUidCounterSetMap.iterateWithValue(printUidInfo);
977 if (!isOk(res)) {
978 dw.println("mUidCounterSetMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700979 }
980
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700981 // Print AppUidStatsMap content
982 std::string appUidStatsHeader = StringPrintf("uid rxBytes rxPackets txBytes txPackets");
983 dumpBpfMap("mAppUidStatsMap:", dw, appUidStatsHeader);
984 auto printAppUidStatsInfo = [&dw](const uint32_t& key, const StatsValue& value,
985 const BpfMap<uint32_t, StatsValue>&) {
986 dw.println("%u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, value.rxBytes,
987 value.rxPackets, value.txBytes, value.txPackets);
988 return netdutils::status::ok;
989 };
990 res = mAppUidStatsMap.iterateWithValue(printAppUidStatsInfo);
991 if (!res.ok()) {
992 dw.println("mAppUidStatsMap print end with error: %s", res.msg().c_str());
993 }
994
Chenbo Fengef297172018-03-26 10:53:33 -0700995 // Print uidStatsMap content
996 std::string statsHeader = StringPrintf("ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes"
997 " rxPackets txBytes txPackets");
Chenbo Fengf434e862018-06-27 14:08:39 -0700998 dumpBpfMap("mStatsMapA", dw, statsHeader);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700999 const auto printStatsInfo = [&dw, this](const StatsKey& key, const StatsValue& value,
1000 const BpfMap<StatsKey, StatsValue>&) {
1001 uint32_t ifIndex = key.ifaceIndex;
1002 auto ifname = mIfaceIndexNameMap.readValue(ifIndex);
1003 if (!isOk(ifname)) {
1004 strlcpy(ifname.value().name, "unknown", sizeof(IfaceValue));
Chenbo Fengef297172018-03-26 10:53:33 -07001005 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001006 dw.println("%u %s 0x%x %u %u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, ifIndex,
1007 ifname.value().name, key.tag, key.uid, key.counterSet, value.rxBytes,
1008 value.rxPackets, value.txBytes, value.txPackets);
1009 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -07001010 };
Chenbo Fengf434e862018-06-27 14:08:39 -07001011 res = mStatsMapA.iterateWithValue(printStatsInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001012 if (!isOk(res)) {
Chenbo Fengf434e862018-06-27 14:08:39 -07001013 dw.println("mStatsMapA print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001014 }
1015
1016 // Print TagStatsMap content.
Chenbo Fengf434e862018-06-27 14:08:39 -07001017 dumpBpfMap("mStatsMapB", dw, statsHeader);
1018 res = mStatsMapB.iterateWithValue(printStatsInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001019 if (!isOk(res)) {
Chenbo Fengf434e862018-06-27 14:08:39 -07001020 dw.println("mStatsMapB print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001021 }
1022
1023 // Print ifaceIndexToNameMap content.
1024 dumpBpfMap("mIfaceIndexNameMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001025 const auto printIfaceNameInfo = [&dw](const uint32_t& key, const IfaceValue& value,
1026 const BpfMap<uint32_t, IfaceValue>&) {
1027 const char* ifname = value.name;
1028 dw.println("ifaceIndex=%u ifaceName=%s", key, ifname);
1029 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -07001030 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001031 res = mIfaceIndexNameMap.iterateWithValue(printIfaceNameInfo);
1032 if (!isOk(res)) {
1033 dw.println("mIfaceIndexNameMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001034 }
1035
1036 // Print ifaceStatsMap content
1037 std::string ifaceStatsHeader = StringPrintf("ifaceIndex ifaceName rxBytes rxPackets txBytes"
1038 " txPackets");
1039 dumpBpfMap("mIfaceStatsMap:", dw, ifaceStatsHeader);
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001040 const auto printIfaceStatsInfo = [&dw, this](const uint32_t& key, const StatsValue& value,
1041 const BpfMap<uint32_t, StatsValue>&) {
1042 auto ifname = mIfaceIndexNameMap.readValue(key);
1043 if (!isOk(ifname)) {
1044 strlcpy(ifname.value().name, "unknown", sizeof(IfaceValue));
Chenbo Fengef297172018-03-26 10:53:33 -07001045 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001046 dw.println("%u %s %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, ifname.value().name,
1047 value.rxBytes, value.rxPackets, value.txBytes, value.txPackets);
1048 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -07001049 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001050 res = mIfaceStatsMap.iterateWithValue(printIfaceStatsInfo);
1051 if (!isOk(res)) {
1052 dw.println("mIfaceStatsMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001053 }
1054
Chenbo Feng703798e2018-06-15 17:07:59 -07001055 dw.blankline();
Chenbo Fengef297172018-03-26 10:53:33 -07001056
Chenbo Fengf434e862018-06-27 14:08:39 -07001057 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Chenbo Feng703798e2018-06-15 17:07:59 -07001058 auto configuration = mConfigurationMap.readValue(key);
1059 if (isOk(configuration)) {
Chenbo Fengf434e862018-06-27 14:08:39 -07001060 dw.println("current ownerMatch configuration: %d", configuration.value());
Chenbo Feng703798e2018-06-15 17:07:59 -07001061 } else {
Chenbo Fengf434e862018-06-27 14:08:39 -07001062 dw.println("mConfigurationMap read ownerMatch configure failed with error: %s",
1063 configuration.status().msg().c_str());
1064 }
1065 key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
1066 configuration = mConfigurationMap.readValue(key);
1067 if (isOk(configuration)) {
1068 dw.println("current statsMap configuration: %d", configuration.value());
1069 } else {
1070 dw.println("mConfigurationMap read stats map configure failed with error: %s",
1071 configuration.status().msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -07001072 }
Chenbo Feng703798e2018-06-15 17:07:59 -07001073 dumpBpfMap("mUidOwnerMap", dw, "");
Rubin Xuec27ff22019-01-08 21:33:03 +00001074 const auto printUidMatchInfo = [&dw, this](const uint32_t& key, const UidOwnerValue& value,
1075 const BpfMap<uint32_t, UidOwnerValue>&) {
1076 if (value.rule & IIF_MATCH) {
1077 auto ifname = mIfaceIndexNameMap.readValue(value.iif);
1078 if (isOk(ifname)) {
1079 dw.println("%u %s %s", key, uidMatchTypeToString(value.rule).c_str(),
1080 ifname.value().name);
1081 } else {
1082 dw.println("%u %s %u", key, uidMatchTypeToString(value.rule).c_str(), value.iif);
1083 }
1084 } else {
1085 dw.println("%u %s", key, uidMatchTypeToString(value.rule).c_str());
1086 }
Chenbo Feng703798e2018-06-15 17:07:59 -07001087 return netdutils::status::ok;
1088 };
1089 res = mUidOwnerMap.iterateWithValue(printUidMatchInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -07001090 if (!isOk(res)) {
Chenbo Feng703798e2018-06-15 17:07:59 -07001091 dw.println("mUidOwnerMap print end with error: %s", res.msg().c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -07001092 }
Chenbo Feng48eaed32018-12-26 17:40:21 -08001093 dumpBpfMap("mUidPermissionMap", dw, "");
1094 const auto printUidPermissionInfo = [&dw](const uint32_t& key, const uint8_t& value,
1095 const BpfMap<uint32_t, uint8_t>&) {
1096 dw.println("%u %s", key, UidPermissionTypeToString(value).c_str());
1097 return netdutils::status::ok;
1098 };
1099 res = mUidPermissionMap.iterateWithValue(printUidPermissionInfo);
1100 if (!isOk(res)) {
1101 dw.println("mUidPermissionMap print end with error: %s", res.msg().c_str());
1102 }
1103
1104 dumpBpfMap("mPrivilegedUser", dw, "");
1105 for (uid_t uid : mPrivilegedUser) {
1106 dw.println("%u ALLOW_UPDATE_DEVICE_STATS", (uint32_t)uid);
1107 }
Chenbo Fengef297172018-03-26 10:53:33 -07001108}
1109
Chenbo Fengf2759682017-10-10 17:31:57 -07001110} // namespace net
1111} // namespace android