blob: b80de35c9ce6114c1f3db5f2acdff1fdf5ec62b9 [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;
75
Chenbo Feng48eaed32018-12-26 17:40:21 -080076#define FLAG_MSG_TRANS(result, flag, value) \
77 do { \
78 if (value & flag) { \
79 result.append(StringPrintf(" %s", #flag)); \
80 value &= ~flag; \
81 } \
Chenbo Feng703798e2018-06-15 17:07:59 -070082 } while (0)
83
84const std::string uidMatchTypeToString(uint8_t match) {
85 std::string matchType;
Chenbo Feng48eaed32018-12-26 17:40:21 -080086 FLAG_MSG_TRANS(matchType, HAPPY_BOX_MATCH, match);
87 FLAG_MSG_TRANS(matchType, PENALTY_BOX_MATCH, match);
88 FLAG_MSG_TRANS(matchType, DOZABLE_MATCH, match);
89 FLAG_MSG_TRANS(matchType, STANDBY_MATCH, match);
90 FLAG_MSG_TRANS(matchType, POWERSAVE_MATCH, match);
Chenbo Feng703798e2018-06-15 17:07:59 -070091 if (match) {
92 return StringPrintf("Unknown match: %u", match);
93 }
94 return matchType;
95}
96
Chenbo Fengb4a4fa12019-01-09 17:20:45 -080097bool TrafficController::hasUpdateDeviceStatsPermission(uid_t uid) {
Chenbo Feng3969c262019-03-19 14:53:57 -070098 // This implementation is the same logic as method ActivityManager#checkComponentPermission.
99 // It implies that the calling uid can never be the same as PER_USER_RANGE.
100 uint32_t appId = uid % PER_USER_RANGE;
101 return ((appId == AID_ROOT) || (appId == AID_SYSTEM) ||
102 mPrivilegedUser.find(appId) != mPrivilegedUser.end());
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800103}
104
Chenbo Feng48eaed32018-12-26 17:40:21 -0800105const std::string UidPermissionTypeToString(uint8_t permission) {
106 std::string permissionType;
107 FLAG_MSG_TRANS(permissionType, ALLOW_SOCK_CREATE, permission);
108 FLAG_MSG_TRANS(permissionType, ALLOW_UPDATE_DEVICE_STATS, permission);
109 if (permission) {
110 return StringPrintf("Unknown permission: %u", permission);
111 }
112 return permissionType;
113}
114
Chenbo Feng49586642018-08-30 18:01:53 -0700115StatusOr<std::unique_ptr<NetlinkListenerInterface>> TrafficController::makeSkDestroyListener() {
Chenbo Feng116d0552017-12-04 17:25:19 -0800116 const auto& sys = sSyscalls.get();
117 ASSIGN_OR_RETURN(auto event, sys.eventfd(0, EFD_CLOEXEC));
118 const int domain = AF_NETLINK;
119 const int type = SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK;
120 const int protocol = NETLINK_INET_DIAG;
121 ASSIGN_OR_RETURN(auto sock, sys.socket(domain, type, protocol));
122
Lorenzo Colitti436efdb2018-07-26 17:20:57 +0900123 // TODO: if too many sockets are closed too quickly, we can overflow the socket buffer, and
124 // some entries in mCookieTagMap will not be freed. In order to fix this we would need to
125 // periodically dump all sockets and remove the tag entries for sockets that have been closed.
126 // For now, set a large-enough buffer that we can close hundreds of sockets without getting
127 // ENOBUFS and leaking mCookieTagMap entries.
128 int rcvbuf = 512 * 1024;
129 auto ret = sys.setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf));
130 if (!ret.ok()) {
131 ALOGW("Failed to set SkDestroyListener buffer size to %d: %s", rcvbuf, ret.msg().c_str());
132 }
133
Chenbo Feng116d0552017-12-04 17:25:19 -0800134 sockaddr_nl addr = {
135 .nl_family = AF_NETLINK,
136 .nl_groups = 1 << (SKNLGRP_INET_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET_UDP_DESTROY - 1) |
137 1 << (SKNLGRP_INET6_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET6_UDP_DESTROY - 1)};
138 RETURN_IF_NOT_OK(sys.bind(sock, addr));
139
140 const sockaddr_nl kernel = {.nl_family = AF_NETLINK};
141 RETURN_IF_NOT_OK(sys.connect(sock, kernel));
142
143 std::unique_ptr<NetlinkListenerInterface> listener =
Chenbo Feng46296702018-08-23 12:20:22 -0700144 std::make_unique<NetlinkListener>(std::move(event), std::move(sock), "SkDestroyListen");
Chenbo Feng116d0552017-12-04 17:25:19 -0800145
146 return listener;
147}
148
Chenbo Feng89c12f12018-03-21 10:29:18 -0700149Status changeOwnerAndMode(const char* path, gid_t group, const char* debugName, bool netdOnly) {
150 int ret = chown(path, AID_ROOT, group);
151 if (ret != 0) return statusFromErrno(errno, StringPrintf("change %s group failed", debugName));
152
153 if (netdOnly) {
154 ret = chmod(path, S_IRWXU);
155 } else {
156 // Allow both netd and system server to obtain map fd from the path.
157 // chmod doesn't grant permission to all processes in that group to
158 // read/write the bpf map. They still need correct sepolicy to
159 // read/write the map.
Chenbo Fengf434e862018-06-27 14:08:39 -0700160 ret = chmod(path, S_IRWXU | S_IRGRP | S_IWGRP);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700161 }
162 if (ret != 0) return statusFromErrno(errno, StringPrintf("change %s mode failed", debugName));
163 return netdutils::status::ok;
164}
165
Chenbo Feng47dd0732018-12-11 12:23:24 -0800166TrafficController::TrafficController() : mBpfLevel(getBpfSupportLevel()) {}
Chenbo Feng89c12f12018-03-21 10:29:18 -0700167
Chenbo Feng89c12f12018-03-21 10:29:18 -0700168Status TrafficController::initMaps() {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900169 std::lock_guard ownerMapGuard(mOwnerMatchMutex);
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700170 RETURN_IF_NOT_OK(mCookieTagMap.init(COOKIE_TAG_MAP_PATH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700171 RETURN_IF_NOT_OK(changeOwnerAndMode(COOKIE_TAG_MAP_PATH, AID_NET_BW_ACCT, "CookieTagMap",
172 false));
173
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700174 RETURN_IF_NOT_OK(mUidCounterSetMap.init(UID_COUNTERSET_MAP_PATH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700175 RETURN_IF_NOT_OK(changeOwnerAndMode(UID_COUNTERSET_MAP_PATH, AID_NET_BW_ACCT,
176 "UidCounterSetMap", false));
177
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700178 RETURN_IF_NOT_OK(mAppUidStatsMap.init(APP_UID_STATS_MAP_PATH));
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700179 RETURN_IF_NOT_OK(
180 changeOwnerAndMode(APP_UID_STATS_MAP_PATH, AID_NET_BW_STATS, "AppUidStatsMap", false));
181
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700182 RETURN_IF_NOT_OK(mStatsMapA.init(STATS_MAP_A_PATH));
Chenbo Fengf434e862018-06-27 14:08:39 -0700183 RETURN_IF_NOT_OK(changeOwnerAndMode(STATS_MAP_A_PATH, AID_NET_BW_STATS, "StatsMapA", false));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700184
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700185 RETURN_IF_NOT_OK(mStatsMapB.init(STATS_MAP_B_PATH));
Chenbo Fengf434e862018-06-27 14:08:39 -0700186 RETURN_IF_NOT_OK(changeOwnerAndMode(STATS_MAP_B_PATH, AID_NET_BW_STATS, "StatsMapB", false));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700187
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700188 RETURN_IF_NOT_OK(mIfaceIndexNameMap.init(IFACE_INDEX_NAME_MAP_PATH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700189 RETURN_IF_NOT_OK(changeOwnerAndMode(IFACE_INDEX_NAME_MAP_PATH, AID_NET_BW_STATS,
190 "IfaceIndexNameMap", false));
191
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700192 RETURN_IF_NOT_OK(mIfaceStatsMap.init(IFACE_STATS_MAP_PATH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700193 RETURN_IF_NOT_OK(changeOwnerAndMode(IFACE_STATS_MAP_PATH, AID_NET_BW_STATS, "IfaceStatsMap",
194 false));
Chenbo Feng95892f32018-06-07 14:52:02 -0700195
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700196 RETURN_IF_NOT_OK(mConfigurationMap.init(CONFIGURATION_MAP_PATH));
Chenbo Fengf434e862018-06-27 14:08:39 -0700197 RETURN_IF_NOT_OK(changeOwnerAndMode(CONFIGURATION_MAP_PATH, AID_NET_BW_STATS,
198 "ConfigurationMap", false));
Chenbo Feng703798e2018-06-15 17:07:59 -0700199 RETURN_IF_NOT_OK(
Chenbo Fengf434e862018-06-27 14:08:39 -0700200 mConfigurationMap.writeValue(UID_RULES_CONFIGURATION_KEY, DEFAULT_CONFIG, BPF_ANY));
201 RETURN_IF_NOT_OK(mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, SELECT_MAP_A,
202 BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700203
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700204 RETURN_IF_NOT_OK(mUidOwnerMap.init(UID_OWNER_MAP_PATH));
Chenbo Feng703798e2018-06-15 17:07:59 -0700205 RETURN_IF_NOT_OK(changeOwnerAndMode(UID_OWNER_MAP_PATH, AID_ROOT, "UidOwnerMap", true));
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900206 RETURN_IF_NOT_OK(mUidOwnerMap.clear());
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700207 RETURN_IF_NOT_OK(mUidPermissionMap.init(UID_PERMISSION_MAP_PATH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700208 return netdutils::status::ok;
209}
210
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800211static Status attachProgramToCgroup(const char* programPath, const int cgroupFd,
212 bpf_attach_type type) {
213 unique_fd cgroupProg(bpfFdGet(programPath, 0));
214 if (cgroupProg == -1) {
215 int ret = errno;
216 ALOGE("Failed to get program from %s: %s", programPath, strerror(ret));
217 return statusFromErrno(ret, "cgroup program get failed");
218 }
219 if (android::bpf::attachProgram(type, cgroupProg, cgroupFd)) {
220 int ret = errno;
221 ALOGE("Program from %s attach failed: %s", programPath, strerror(ret));
222 return statusFromErrno(ret, "program attach failed");
223 }
224 return netdutils::status::ok;
225}
226
227static Status initPrograms() {
Suren Baghdasaryane072a3c2019-01-16 14:36:07 -0800228 std::string cg2_path;
229
230 if (!CgroupGetControllerPath(CGROUPV2_CONTROLLER_NAME, &cg2_path)) {
231 int ret = errno;
232 ALOGE("Failed to find cgroup v2 root");
233 return statusFromErrno(ret, "Failed to find cgroup v2 root");
234 }
235
236 unique_fd cg_fd(open(cg2_path.c_str(), O_DIRECTORY | O_RDONLY | O_CLOEXEC));
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800237 if (cg_fd == -1) {
238 int ret = errno;
239 ALOGE("Failed to open the cgroup directory: %s", strerror(ret));
240 return statusFromErrno(ret, "Open the cgroup directory failed");
241 }
242 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_EGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_EGRESS));
243 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_INGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_INGRESS));
Chenbo Fenga51f4fa2019-01-15 15:03:32 -0800244
245 // For the devices that support cgroup socket filter, the socket filter
246 // should be loaded successfully by bpfloader. So we attach the filter to
247 // cgroup if the program is pinned properly.
248 // TODO: delete the if statement once all devices should support cgroup
249 // socket filter (ie. the minimum kernel version required is 4.14).
250 if (!access(CGROUP_SOCKET_PROG_PATH, F_OK)) {
251 RETURN_IF_NOT_OK(
252 attachProgramToCgroup(CGROUP_SOCKET_PROG_PATH, cg_fd, BPF_CGROUP_INET_SOCK_CREATE));
253 }
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800254 return netdutils::status::ok;
255}
256
Chenbo Feng89c12f12018-03-21 10:29:18 -0700257Status TrafficController::start() {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800258 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800259 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700260 }
261
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900262 /* When netd restarts from a crash without total system reboot, the program
Chenbo Fengf2759682017-10-10 17:31:57 -0700263 * is still attached to the cgroup, detach it so the program can be freed
264 * and we can load and attach new program into the target cgroup.
265 *
266 * TODO: Scrape existing socket when run-time restart and clean up the map
267 * if the socket no longer exist
268 */
269
Chenbo Feng89c12f12018-03-21 10:29:18 -0700270 RETURN_IF_NOT_OK(initMaps());
Chenbo Feng7e974052018-02-28 22:57:21 -0800271
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800272 RETURN_IF_NOT_OK(initPrograms());
273
Chenbo Feng7e974052018-02-28 22:57:21 -0800274 // Fetch the list of currently-existing interfaces. At this point NetlinkHandler is
275 // already running, so it will call addInterface() when any new interface appears.
276 std::map<std::string, uint32_t> ifacePairs;
277 ASSIGN_OR_RETURN(ifacePairs, InterfaceController::getIfaceList());
278 for (const auto& ifacePair:ifacePairs) {
279 addInterface(ifacePair.first.c_str(), ifacePair.second);
280 }
281
Chenbo Feng116d0552017-12-04 17:25:19 -0800282 auto result = makeSkDestroyListener();
283 if (!isOk(result)) {
284 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
285 } else {
286 mSkDestroyListener = std::move(result.value());
287 }
288 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
289 const auto rxHandler = [this](const nlmsghdr&, const Slice msg) {
290 inet_diag_msg diagmsg = {};
291 if (extract(msg, diagmsg) < sizeof(inet_diag_msg)) {
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900292 ALOGE("Unrecognized netlink message: %s", toString(msg).c_str());
Chenbo Feng116d0552017-12-04 17:25:19 -0800293 return;
294 }
295 uint64_t sock_cookie = static_cast<uint64_t>(diagmsg.id.idiag_cookie[0]) |
296 (static_cast<uint64_t>(diagmsg.id.idiag_cookie[1]) << 32);
297
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900298 Status s = mCookieTagMap.deleteValue(sock_cookie);
Chenbo Feng1d4c5db2018-10-18 15:50:46 -0700299 if (!isOk(s) && s.code() != ENOENT) {
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900300 ALOGE("Failed to delete cookie %" PRIx64 ": %s", sock_cookie, toString(s).c_str());
301 return;
302 }
Chenbo Feng116d0552017-12-04 17:25:19 -0800303 };
304 expectOk(mSkDestroyListener->subscribe(kSockDiagMsgType, rxHandler));
305
306 // In case multiple netlink message comes in as a stream, we need to handle the rxDone message
307 // properly.
308 const auto rxDoneHandler = [](const nlmsghdr&, const Slice msg) {
309 // Ignore NLMSG_DONE messages
310 inet_diag_msg diagmsg = {};
311 extract(msg, diagmsg);
312 };
313 expectOk(mSkDestroyListener->subscribe(kSockDiagDoneMsgType, rxDoneHandler));
314
Chenbo Feng05393d82018-01-09 15:18:43 -0800315 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700316}
317
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800318int TrafficController::tagSocket(int sockFd, uint32_t tag, uid_t uid, uid_t callingUid) {
319 if (uid != callingUid && !hasUpdateDeviceStatsPermission(callingUid)) {
320 return -EPERM;
321 }
322
Chenbo Feng47dd0732018-12-11 12:23:24 -0800323 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700324 if (legacy_tagSocket(sockFd, tag, uid)) return -errno;
325 return 0;
326 }
Chenbo Feng33cc1032017-10-23 15:16:37 -0700327
Chenbo Fengf2759682017-10-10 17:31:57 -0700328 uint64_t sock_cookie = getSocketCookie(sockFd);
Chenbo Fengef1cab32018-04-13 19:50:49 -0700329 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
Chenbo Fengf2759682017-10-10 17:31:57 -0700330 UidTag newKey = {.uid = (uint32_t)uid, .tag = tag};
331
332 // Update the tag information of a socket to the cookieUidMap. Use BPF_ANY
333 // flag so it will insert a new entry to the map if that value doesn't exist
334 // yet. And update the tag if there is already a tag stored. Since the eBPF
335 // program in kernel only read this map, and is protected by rcu read lock. It
336 // should be fine to cocurrently update the map while eBPF program is running.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700337 Status res = mCookieTagMap.writeValue(sock_cookie, newKey, BPF_ANY);
338 if (!isOk(res)) {
339 ALOGE("Failed to tag the socket: %s, fd: %d", strerror(res.code()),
340 mCookieTagMap.getMap().get());
Chenbo Fengf2759682017-10-10 17:31:57 -0700341 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700342 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700343}
344
345int TrafficController::untagSocket(int sockFd) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800346 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700347 if (legacy_untagSocket(sockFd)) return -errno;
348 return 0;
349 }
Chenbo Fengf2759682017-10-10 17:31:57 -0700350 uint64_t sock_cookie = getSocketCookie(sockFd);
351
Chenbo Fengef1cab32018-04-13 19:50:49 -0700352 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700353 Status res = mCookieTagMap.deleteValue(sock_cookie);
354 if (!isOk(res)) {
355 ALOGE("Failed to untag socket: %s\n", strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700356 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700357 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700358}
359
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800360int TrafficController::setCounterSet(int counterSetNum, uid_t uid, uid_t callingUid) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700361 if (counterSetNum < 0 || counterSetNum >= OVERFLOW_COUNTERSET) return -EINVAL;
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800362
363 if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
364
Chenbo Feng47dd0732018-12-11 12:23:24 -0800365 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700366 if (legacy_setCounterSet(counterSetNum, uid)) return -errno;
367 return 0;
368 }
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800369
370 // The default counter set for all uid is 0, so deleting the current counterset for that uid
371 // will automatically set it to 0.
Chenbo Fengf2759682017-10-10 17:31:57 -0700372 if (counterSetNum == 0) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700373 Status res = mUidCounterSetMap.deleteValue(uid);
374 if (isOk(res) || (!isOk(res) && res.code() == ENOENT)) {
Chenbo Fengf2759682017-10-10 17:31:57 -0700375 return 0;
376 } else {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700377 ALOGE("Failed to delete the counterSet: %s\n", strerror(res.code()));
378 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700379 }
380 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700381 uint8_t tmpCounterSetNum = (uint8_t)counterSetNum;
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800382 Status res = mUidCounterSetMap.writeValue(uid, tmpCounterSetNum, BPF_ANY);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700383 if (!isOk(res)) {
384 ALOGE("Failed to set the counterSet: %s, fd: %d", strerror(res.code()),
385 mUidCounterSetMap.getMap().get());
386 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700387 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700388 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700389}
390
Chenbo Fengf434e862018-06-27 14:08:39 -0700391// This method only get called by system_server when an app get uinstalled, it
392// is called inside removeUidsLocked() while holding mStatsLock. So it is safe
393// to iterate and modify the stats maps.
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800394int TrafficController::deleteTagData(uint32_t tag, uid_t uid, uid_t callingUid) {
395 if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
396
Chenbo Feng47dd0732018-12-11 12:23:24 -0800397 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700398 if (legacy_deleteTagData(tag, uid)) return -errno;
399 return 0;
400 }
Chenbo Feng33cc1032017-10-23 15:16:37 -0700401
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800402 // First we go through the cookieTagMap to delete the target uid tag combination. Or delete all
Chenbo Fengef1cab32018-04-13 19:50:49 -0700403 // the tags related to the uid if the tag is 0.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700404 const auto deleteMatchedCookieEntries = [uid, tag](const uint64_t& key, const UidTag& value,
405 BpfMap<uint64_t, UidTag>& map) {
406 if (value.uid == uid && (value.tag == tag || tag == 0)) {
407 Status res = map.deleteValue(key);
408 if (isOk(res) || (res.code() == ENOENT)) {
409 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700410 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700411 ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s\n", key, strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700412 }
Chenbo Fengef1cab32018-04-13 19:50:49 -0700413 // Move forward to next cookie in the map.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700414 return netdutils::status::ok;
Chenbo Fengef1cab32018-04-13 19:50:49 -0700415 };
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900416 mCookieTagMap.iterateWithValue(deleteMatchedCookieEntries).ignoreError();
Chenbo Fengf2759682017-10-10 17:31:57 -0700417 // 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 -0700418 // combination. Or all tag stats under that uid if the target tag is 0.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700419 const auto deleteMatchedUidTagEntries = [uid, tag](const StatsKey& key,
420 BpfMap<StatsKey, StatsValue>& map) {
421 if (key.uid == uid && (key.tag == tag || tag == 0)) {
422 Status res = map.deleteValue(key);
423 if (isOk(res) || (res.code() == ENOENT)) {
Chenbo Fengef1cab32018-04-13 19:50:49 -0700424 //Entry is deleted, use the current key to get a new nextKey;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700425 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700426 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700427 ALOGE("Failed to delete data(uid=%u, tag=%u): %s\n", key.uid, key.tag,
428 strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700429 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700430 return netdutils::status::ok;
Chenbo Fengef1cab32018-04-13 19:50:49 -0700431 };
Chenbo Fengf434e862018-06-27 14:08:39 -0700432 mStatsMapB.iterate(deleteMatchedUidTagEntries).ignoreError();
433 mStatsMapA.iterate(deleteMatchedUidTagEntries).ignoreError();
Chenbo Fengf2759682017-10-10 17:31:57 -0700434 // 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 -0800435 // need to delete the stats stored in uidStatsMap and counterSet map.
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800436 if (tag != 0) return 0;
437
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700438 Status res = mUidCounterSetMap.deleteValue(uid);
439 if (!isOk(res) && res.code() != ENOENT) {
440 ALOGE("Failed to delete counterSet data(uid=%u, tag=%u): %s\n", uid, tag,
441 strerror(res.code()));
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800442 }
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700443
444 auto deleteAppUidStatsEntry = [uid](const uint32_t& key, BpfMap<uint32_t, StatsValue>& map) {
445 if (key == uid) {
446 Status res = map.deleteValue(key);
447 if (isOk(res) || (res.code() == ENOENT)) {
448 return netdutils::status::ok;
449 }
450 ALOGE("Failed to delete data(uid=%u): %s", key, strerror(res.code()));
451 }
452 return netdutils::status::ok;
453 };
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900454 mAppUidStatsMap.iterate(deleteAppUidStatsEntry).ignoreError();
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700455 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700456}
457
Chenbo Feng7e974052018-02-28 22:57:21 -0800458int TrafficController::addInterface(const char* name, uint32_t ifaceIndex) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800459 if (mBpfLevel == BpfLevel::NONE) return 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800460
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700461 IfaceValue iface;
Chenbo Feng7e974052018-02-28 22:57:21 -0800462 if (ifaceIndex == 0) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700463 ALOGE("Unknown interface %s(%d)", name, ifaceIndex);
Chenbo Feng7e974052018-02-28 22:57:21 -0800464 return -1;
465 }
466
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700467 strlcpy(iface.name, name, sizeof(IfaceValue));
468 Status res = mIfaceIndexNameMap.writeValue(ifaceIndex, iface, BPF_ANY);
469 if (!isOk(res)) {
470 ALOGE("Failed to add iface %s(%d): %s", name, ifaceIndex, strerror(res.code()));
471 return -res.code();
Chenbo Feng7e974052018-02-28 22:57:21 -0800472 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700473 return 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800474}
475
Chenbo Feng703798e2018-06-15 17:07:59 -0700476Status TrafficController::updateOwnerMapEntry(UidOwnerMatchType match, uid_t uid, FirewallRule rule,
477 FirewallType type) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900478 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700479 if ((rule == ALLOW && type == WHITELIST) || (rule == DENY && type == BLACKLIST)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700480 RETURN_IF_NOT_OK(addMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700481 } else if ((rule == ALLOW && type == BLACKLIST) || (rule == DENY && type == WHITELIST)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700482 RETURN_IF_NOT_OK(removeMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700483 } else {
484 //Cannot happen.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700485 return statusFromErrno(-EINVAL, "");
Chenbo Feng89c12f12018-03-21 10:29:18 -0700486 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700487 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700488}
489
Chenbo Feng703798e2018-06-15 17:07:59 -0700490UidOwnerMatchType TrafficController::jumpOpToMatch(BandwidthController::IptJumpOp jumpHandling) {
Chenbo Feng95892f32018-06-07 14:52:02 -0700491 switch (jumpHandling) {
492 case BandwidthController::IptJumpReject:
Chenbo Feng703798e2018-06-15 17:07:59 -0700493 return PENALTY_BOX_MATCH;
Chenbo Feng95892f32018-06-07 14:52:02 -0700494 case BandwidthController::IptJumpReturn:
Chenbo Feng703798e2018-06-15 17:07:59 -0700495 return HAPPY_BOX_MATCH;
Chenbo Feng95892f32018-06-07 14:52:02 -0700496 case BandwidthController::IptJumpNoAdd:
497 return NO_MATCH;
498 }
499}
500
Chenbo Feng703798e2018-06-15 17:07:59 -0700501Status TrafficController::removeMatch(BpfMap<uint32_t, uint8_t>& map, uint32_t uid,
502 UidOwnerMatchType match) {
503 auto oldMatch = map.readValue(uid);
504 if (isOk(oldMatch)) {
505 uint8_t newMatch = oldMatch.value() & ~match;
506 if (newMatch == 0) {
507 RETURN_IF_NOT_OK(map.deleteValue(uid));
508 } else {
509 RETURN_IF_NOT_OK(map.writeValue(uid, newMatch, BPF_ANY));
510 }
511 } else {
512 return statusFromErrno(ENOENT, StringPrintf("uid: %u does not exist in map", uid));
513 }
514 return netdutils::status::ok;
515}
516
517Status TrafficController::addMatch(BpfMap<uint32_t, uint8_t>& map, uint32_t uid,
518 UidOwnerMatchType match) {
519 auto oldMatch = map.readValue(uid);
520 if (isOk(oldMatch)) {
521 uint8_t newMatch = oldMatch.value() | match;
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900522 RETURN_IF_NOT_OK(map.writeValue((uint32_t) uid, newMatch, BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700523 } else {
524 RETURN_IF_NOT_OK(map.writeValue(uid, match, BPF_ANY));
525 }
526 return netdutils::status::ok;
527}
528
529Status TrafficController::updateUidOwnerMap(const std::vector<std::string>& appStrUids,
530 BandwidthController::IptJumpOp jumpHandling,
531 BandwidthController::IptOp op) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900532 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Feng703798e2018-06-15 17:07:59 -0700533 UidOwnerMatchType match = jumpOpToMatch(jumpHandling);
534 if (match == NO_MATCH) {
535 return statusFromErrno(
536 EINVAL, StringPrintf("invalid IptJumpOp: %d, command: %d", jumpHandling, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700537 }
538 for (const auto& appStrUid : appStrUids) {
539 char* endPtr;
540 long uid = strtol(appStrUid.c_str(), &endPtr, 10);
541 if ((errno == ERANGE && (uid == LONG_MAX || uid == LONG_MIN)) ||
542 (endPtr == appStrUid.c_str()) || (*endPtr != '\0')) {
543 return statusFromErrno(errno, "invalid uid string:" + appStrUid);
544 }
545
Chenbo Feng95892f32018-06-07 14:52:02 -0700546 if (op == BandwidthController::IptOpDelete) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700547 RETURN_IF_NOT_OK(removeMatch(mUidOwnerMap, uid, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700548 } else if (op == BandwidthController::IptOpInsert) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700549 RETURN_IF_NOT_OK(addMatch(mUidOwnerMap, uid, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700550 } else {
551 // Cannot happen.
Chenbo Feng703798e2018-06-15 17:07:59 -0700552 return statusFromErrno(EINVAL, StringPrintf("invalid IptOp: %d, %d", op, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700553 }
554 }
555 return netdutils::status::ok;
556}
557
Chenbo Feng89c12f12018-03-21 10:29:18 -0700558int TrafficController::changeUidOwnerRule(ChildChain chain, uid_t uid, FirewallRule rule,
559 FirewallType type) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800560 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Feng89c12f12018-03-21 10:29:18 -0700561 ALOGE("bpf is not set up, should use iptables rule");
562 return -ENOSYS;
563 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700564 Status res;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700565 switch (chain) {
566 case DOZABLE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700567 res = updateOwnerMapEntry(DOZABLE_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700568 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700569 case STANDBY:
Chenbo Feng703798e2018-06-15 17:07:59 -0700570 res = updateOwnerMapEntry(STANDBY_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700571 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700572 case POWERSAVE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700573 res = updateOwnerMapEntry(POWERSAVE_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700574 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700575 case NONE:
576 default:
577 return -EINVAL;
578 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700579 if (!isOk(res)) {
580 ALOGE("change uid(%u) rule of %d failed: %s, rule: %d, type: %d", uid, chain,
581 res.msg().c_str(), rule, type);
582 return -res.code();
583 }
584 return 0;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700585}
586
Chenbo Feng703798e2018-06-15 17:07:59 -0700587Status TrafficController::replaceUidsInMap(const UidOwnerMatchType match,
588 const std::vector<int32_t>& uids) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900589 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700590 std::set<int32_t> uidSet(uids.begin(), uids.end());
591 std::vector<uint32_t> uidsToDelete;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700592 auto getUidsToDelete = [&uidsToDelete, &uidSet](const uint32_t& key,
593 const BpfMap<uint32_t, uint8_t>&) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700594 if (uidSet.find((int32_t) key) == uidSet.end()) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700595 uidsToDelete.push_back(key);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700596 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700597 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700598 };
Chenbo Feng703798e2018-06-15 17:07:59 -0700599 RETURN_IF_NOT_OK(mUidOwnerMap.iterate(getUidsToDelete));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700600
601 for(auto uid : uidsToDelete) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700602 RETURN_IF_NOT_OK(removeMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700603 }
604
605 for (auto uid : uids) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700606 RETURN_IF_NOT_OK(addMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700607 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700608 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700609}
610
611int TrafficController::replaceUidOwnerMap(const std::string& name, bool isWhitelist,
612 const std::vector<int32_t>& uids) {
Chenbo Feng89c12f12018-03-21 10:29:18 -0700613 FirewallRule rule;
614 FirewallType type;
615 if (isWhitelist) {
616 type = WHITELIST;
617 rule = ALLOW;
618 } else {
619 type = BLACKLIST;
620 rule = DENY;
621 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700622 Status res;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700623 if (!name.compare(FirewallController::LOCAL_DOZABLE)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700624 res = replaceUidsInMap(DOZABLE_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700625 } else if (!name.compare(FirewallController::LOCAL_STANDBY)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700626 res = replaceUidsInMap(STANDBY_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700627 } else if (!name.compare(FirewallController::LOCAL_POWERSAVE)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700628 res = replaceUidsInMap(POWERSAVE_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700629 } else {
630 ALOGE("unknown chain name: %s", name.c_str());
631 return -EINVAL;
632 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700633 if (!isOk(res)) {
634 ALOGE("Failed to clean up chain: %s: %s", name.c_str(), res.msg().c_str());
635 return -res.code();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700636 }
637 return 0;
638}
639
640int TrafficController::toggleUidOwnerMap(ChildChain chain, bool enable) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900641 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Fengf434e862018-06-27 14:08:39 -0700642 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Chenbo Feng703798e2018-06-15 17:07:59 -0700643 auto oldConfiguration = mConfigurationMap.readValue(key);
644 if (!isOk(oldConfiguration)) {
645 ALOGE("Cannot read the old configuration from map: %s",
646 oldConfiguration.status().msg().c_str());
647 return -oldConfiguration.status().code();
648 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700649 Status res;
Chenbo Feng703798e2018-06-15 17:07:59 -0700650 BpfConfig newConfiguration;
651 uint8_t match;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700652 switch (chain) {
653 case DOZABLE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700654 match = DOZABLE_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700655 break;
656 case STANDBY:
Chenbo Feng703798e2018-06-15 17:07:59 -0700657 match = STANDBY_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700658 break;
659 case POWERSAVE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700660 match = POWERSAVE_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700661 break;
662 default:
663 return -EINVAL;
664 }
Chenbo Feng703798e2018-06-15 17:07:59 -0700665 newConfiguration =
666 enable ? (oldConfiguration.value() | match) : (oldConfiguration.value() & (~match));
667 res = mConfigurationMap.writeValue(key, newConfiguration, BPF_EXIST);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700668 if (!isOk(res)) {
669 ALOGE("Failed to toggleUidOwnerMap(%d): %s", chain, res.msg().c_str());
Chenbo Feng89c12f12018-03-21 10:29:18 -0700670 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700671 return -res.code();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700672}
673
Chenbo Feng47dd0732018-12-11 12:23:24 -0800674BpfLevel TrafficController::getBpfLevel() {
675 return mBpfLevel;
Chenbo Feng07d43fe2017-12-21 14:38:51 -0800676}
677
Chenbo Feng48eaed32018-12-26 17:40:21 -0800678void TrafficController::setPermissionForUids(int permission, const std::vector<uid_t>& uids) {
679 bool internet = (permission & INetd::PERMISSION_INTERNET);
680 bool privileged = (permission & INetd::PERMISSION_UPDATE_DEVICE_STATS);
681
682 for (uid_t uid : uids) {
683 if (internet) {
684 Status ret = mUidPermissionMap.writeValue(uid, ALLOW_SOCK_CREATE, BPF_ANY);
685 if (!isOk(ret)) {
686 ALOGE("Failed to grant INTERNET permission to uid: %u: %s", uid,
687 strerror(ret.code()));
688 }
689 } else {
690 Status ret = mUidPermissionMap.deleteValue(uid);
691 if (!isOk(ret) && ret.code() != ENOENT) {
692 ALOGE("Failed to revoke permission INTERNET from uid: %u: %s", uid,
693 strerror(ret.code()));
694 }
695 }
696
697 if (privileged) {
698 mPrivilegedUser.insert(uid);
699 } else {
700 mPrivilegedUser.erase(uid);
701 }
702 }
703}
704
Chenbo Fengef297172018-03-26 10:53:33 -0700705std::string getProgramStatus(const char *path) {
706 int ret = access(path, R_OK);
707 if (ret == 0) {
708 return StringPrintf("OK");
709 }
710 if (ret != 0 && errno == ENOENT) {
711 return StringPrintf("program is missing at: %s", path);
712 }
713 return StringPrintf("check Program %s error: %s", path, strerror(errno));
714}
715
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700716std::string getMapStatus(const base::unique_fd& map_fd, const char* path) {
Chenbo Fengef297172018-03-26 10:53:33 -0700717 if (map_fd.get() < 0) {
718 return StringPrintf("map fd lost");
719 }
720 if (access(path, F_OK) != 0) {
721 return StringPrintf("map not pinned to location: %s", path);
722 }
723 return StringPrintf("OK");
724}
725
Bernie Innocentia5161a02019-01-30 22:40:53 +0900726// NOLINTNEXTLINE(google-runtime-references): grandfathered pass by non-const reference
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900727void dumpBpfMap(const std::string& mapName, DumpWriter& dw, const std::string& header) {
Chenbo Fengef297172018-03-26 10:53:33 -0700728 dw.blankline();
729 dw.println("%s:", mapName.c_str());
Erik Klineb31fd692018-06-06 20:50:11 +0900730 if (!header.empty()) {
731 dw.println(header);
Chenbo Fengef297172018-03-26 10:53:33 -0700732 }
733}
734
735const String16 TrafficController::DUMP_KEYWORD = String16("trafficcontroller");
736
737void TrafficController::dump(DumpWriter& dw, bool verbose) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900738 std::lock_guard ownerMapGuard(mOwnerMatchMutex);
Erik Klineb31fd692018-06-06 20:50:11 +0900739 ScopedIndent indentTop(dw);
Chenbo Fengef297172018-03-26 10:53:33 -0700740 dw.println("TrafficController");
741
Erik Klineb31fd692018-06-06 20:50:11 +0900742 ScopedIndent indentPreBpfModule(dw);
Chenbo Feng47dd0732018-12-11 12:23:24 -0800743 dw.println("BPF module status: %s", BpfLevelToString(mBpfLevel).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700744
Chenbo Feng47dd0732018-12-11 12:23:24 -0800745 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengef297172018-03-26 10:53:33 -0700746 return;
Erik Klineb31fd692018-06-06 20:50:11 +0900747 }
Chenbo Fengef297172018-03-26 10:53:33 -0700748
749 dw.blankline();
750 dw.println("mCookieTagMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700751 getMapStatus(mCookieTagMap.getMap(), COOKIE_TAG_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700752 dw.println("mUidCounterSetMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700753 getMapStatus(mUidCounterSetMap.getMap(), UID_COUNTERSET_MAP_PATH).c_str());
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700754 dw.println("mAppUidStatsMap status: %s",
755 getMapStatus(mAppUidStatsMap.getMap(), APP_UID_STATS_MAP_PATH).c_str());
Chenbo Fengf434e862018-06-27 14:08:39 -0700756 dw.println("mStatsMapA status: %s",
757 getMapStatus(mStatsMapA.getMap(), STATS_MAP_A_PATH).c_str());
758 dw.println("mStatsMapB status: %s",
759 getMapStatus(mStatsMapB.getMap(), STATS_MAP_B_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700760 dw.println("mIfaceIndexNameMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700761 getMapStatus(mIfaceIndexNameMap.getMap(), IFACE_INDEX_NAME_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700762 dw.println("mIfaceStatsMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700763 getMapStatus(mIfaceStatsMap.getMap(), IFACE_STATS_MAP_PATH).c_str());
Chenbo Feng703798e2018-06-15 17:07:59 -0700764 dw.println("mConfigurationMap status: %s",
765 getMapStatus(mConfigurationMap.getMap(), CONFIGURATION_MAP_PATH).c_str());
766 dw.println("mUidOwnerMap status: %s",
767 getMapStatus(mUidOwnerMap.getMap(), UID_OWNER_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700768
769 dw.blankline();
770 dw.println("Cgroup ingress program status: %s",
771 getProgramStatus(BPF_INGRESS_PROG_PATH).c_str());
772 dw.println("Cgroup egress program status: %s", getProgramStatus(BPF_EGRESS_PROG_PATH).c_str());
773 dw.println("xt_bpf ingress program status: %s",
774 getProgramStatus(XT_BPF_INGRESS_PROG_PATH).c_str());
775 dw.println("xt_bpf egress program status: %s",
776 getProgramStatus(XT_BPF_EGRESS_PROG_PATH).c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700777 dw.println("xt_bpf bandwidth whitelist program status: %s",
778 getProgramStatus(XT_BPF_WHITELIST_PROG_PATH).c_str());
779 dw.println("xt_bpf bandwidth blacklist program status: %s",
780 getProgramStatus(XT_BPF_BLACKLIST_PROG_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700781
Erik Klineb31fd692018-06-06 20:50:11 +0900782 if (!verbose) {
783 return;
784 }
Chenbo Fengef297172018-03-26 10:53:33 -0700785
786 dw.blankline();
787 dw.println("BPF map content:");
788
Erik Klineb31fd692018-06-06 20:50:11 +0900789 ScopedIndent indentForMapContent(dw);
Chenbo Fengef297172018-03-26 10:53:33 -0700790
791 // Print CookieTagMap content.
792 dumpBpfMap("mCookieTagMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700793 const auto printCookieTagInfo = [&dw](const uint64_t& key, const UidTag& value,
794 const BpfMap<uint64_t, UidTag>&) {
795 dw.println("cookie=%" PRIu64 " tag=0x%x uid=%u", key, value.tag, value.uid);
796 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700797 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700798 Status res = mCookieTagMap.iterateWithValue(printCookieTagInfo);
799 if (!isOk(res)) {
800 dw.println("mCookieTagMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700801 }
802
803 // Print UidCounterSetMap Content
804 dumpBpfMap("mUidCounterSetMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700805 const auto printUidInfo = [&dw](const uint32_t& key, const uint8_t& value,
806 const BpfMap<uint32_t, uint8_t>&) {
807 dw.println("%u %u", key, value);
808 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700809 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700810 res = mUidCounterSetMap.iterateWithValue(printUidInfo);
811 if (!isOk(res)) {
812 dw.println("mUidCounterSetMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700813 }
814
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700815 // Print AppUidStatsMap content
816 std::string appUidStatsHeader = StringPrintf("uid rxBytes rxPackets txBytes txPackets");
817 dumpBpfMap("mAppUidStatsMap:", dw, appUidStatsHeader);
818 auto printAppUidStatsInfo = [&dw](const uint32_t& key, const StatsValue& value,
819 const BpfMap<uint32_t, StatsValue>&) {
820 dw.println("%u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, value.rxBytes,
821 value.rxPackets, value.txBytes, value.txPackets);
822 return netdutils::status::ok;
823 };
824 res = mAppUidStatsMap.iterateWithValue(printAppUidStatsInfo);
825 if (!res.ok()) {
826 dw.println("mAppUidStatsMap print end with error: %s", res.msg().c_str());
827 }
828
Chenbo Fengef297172018-03-26 10:53:33 -0700829 // Print uidStatsMap content
830 std::string statsHeader = StringPrintf("ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes"
831 " rxPackets txBytes txPackets");
Chenbo Fengf434e862018-06-27 14:08:39 -0700832 dumpBpfMap("mStatsMapA", dw, statsHeader);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700833 const auto printStatsInfo = [&dw, this](const StatsKey& key, const StatsValue& value,
834 const BpfMap<StatsKey, StatsValue>&) {
835 uint32_t ifIndex = key.ifaceIndex;
836 auto ifname = mIfaceIndexNameMap.readValue(ifIndex);
837 if (!isOk(ifname)) {
838 strlcpy(ifname.value().name, "unknown", sizeof(IfaceValue));
Chenbo Fengef297172018-03-26 10:53:33 -0700839 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700840 dw.println("%u %s 0x%x %u %u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, ifIndex,
841 ifname.value().name, key.tag, key.uid, key.counterSet, value.rxBytes,
842 value.rxPackets, value.txBytes, value.txPackets);
843 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700844 };
Chenbo Fengf434e862018-06-27 14:08:39 -0700845 res = mStatsMapA.iterateWithValue(printStatsInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700846 if (!isOk(res)) {
Chenbo Fengf434e862018-06-27 14:08:39 -0700847 dw.println("mStatsMapA print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700848 }
849
850 // Print TagStatsMap content.
Chenbo Fengf434e862018-06-27 14:08:39 -0700851 dumpBpfMap("mStatsMapB", dw, statsHeader);
852 res = mStatsMapB.iterateWithValue(printStatsInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700853 if (!isOk(res)) {
Chenbo Fengf434e862018-06-27 14:08:39 -0700854 dw.println("mStatsMapB print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700855 }
856
857 // Print ifaceIndexToNameMap content.
858 dumpBpfMap("mIfaceIndexNameMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700859 const auto printIfaceNameInfo = [&dw](const uint32_t& key, const IfaceValue& value,
860 const BpfMap<uint32_t, IfaceValue>&) {
861 const char* ifname = value.name;
862 dw.println("ifaceIndex=%u ifaceName=%s", key, ifname);
863 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700864 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700865 res = mIfaceIndexNameMap.iterateWithValue(printIfaceNameInfo);
866 if (!isOk(res)) {
867 dw.println("mIfaceIndexNameMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700868 }
869
870 // Print ifaceStatsMap content
871 std::string ifaceStatsHeader = StringPrintf("ifaceIndex ifaceName rxBytes rxPackets txBytes"
872 " txPackets");
873 dumpBpfMap("mIfaceStatsMap:", dw, ifaceStatsHeader);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700874 const auto printIfaceStatsInfo = [&dw, this](const uint32_t& key, const StatsValue& value,
875 const BpfMap<uint32_t, StatsValue>&) {
876 auto ifname = mIfaceIndexNameMap.readValue(key);
877 if (!isOk(ifname)) {
878 strlcpy(ifname.value().name, "unknown", sizeof(IfaceValue));
Chenbo Fengef297172018-03-26 10:53:33 -0700879 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700880 dw.println("%u %s %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, ifname.value().name,
881 value.rxBytes, value.rxPackets, value.txBytes, value.txPackets);
882 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700883 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700884 res = mIfaceStatsMap.iterateWithValue(printIfaceStatsInfo);
885 if (!isOk(res)) {
886 dw.println("mIfaceStatsMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700887 }
888
Chenbo Feng703798e2018-06-15 17:07:59 -0700889 dw.blankline();
Chenbo Fengef297172018-03-26 10:53:33 -0700890
Chenbo Fengf434e862018-06-27 14:08:39 -0700891 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Chenbo Feng703798e2018-06-15 17:07:59 -0700892 auto configuration = mConfigurationMap.readValue(key);
893 if (isOk(configuration)) {
Chenbo Fengf434e862018-06-27 14:08:39 -0700894 dw.println("current ownerMatch configuration: %d", configuration.value());
Chenbo Feng703798e2018-06-15 17:07:59 -0700895 } else {
Chenbo Fengf434e862018-06-27 14:08:39 -0700896 dw.println("mConfigurationMap read ownerMatch configure failed with error: %s",
897 configuration.status().msg().c_str());
898 }
899 key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
900 configuration = mConfigurationMap.readValue(key);
901 if (isOk(configuration)) {
902 dw.println("current statsMap configuration: %d", configuration.value());
903 } else {
904 dw.println("mConfigurationMap read stats map configure failed with error: %s",
905 configuration.status().msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700906 }
Chenbo Feng703798e2018-06-15 17:07:59 -0700907 dumpBpfMap("mUidOwnerMap", dw, "");
908 const auto printUidMatchInfo = [&dw](const uint32_t& key, const uint8_t& value,
909 const BpfMap<uint32_t, uint8_t>&) {
910 dw.println("%u %s", key, uidMatchTypeToString(value).c_str());
911 return netdutils::status::ok;
912 };
913 res = mUidOwnerMap.iterateWithValue(printUidMatchInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700914 if (!isOk(res)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700915 dw.println("mUidOwnerMap print end with error: %s", res.msg().c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700916 }
Chenbo Feng48eaed32018-12-26 17:40:21 -0800917 dumpBpfMap("mUidPermissionMap", dw, "");
918 const auto printUidPermissionInfo = [&dw](const uint32_t& key, const uint8_t& value,
919 const BpfMap<uint32_t, uint8_t>&) {
920 dw.println("%u %s", key, UidPermissionTypeToString(value).c_str());
921 return netdutils::status::ok;
922 };
923 res = mUidPermissionMap.iterateWithValue(printUidPermissionInfo);
924 if (!isOk(res)) {
925 dw.println("mUidPermissionMap print end with error: %s", res.msg().c_str());
926 }
927
928 dumpBpfMap("mPrivilegedUser", dw, "");
929 for (uid_t uid : mPrivilegedUser) {
930 dw.println("%u ALLOW_UPDATE_DEVICE_STATS", (uint32_t)uid);
931 }
Chenbo Fengef297172018-03-26 10:53:33 -0700932}
933
Chenbo Fengf2759682017-10-10 17:31:57 -0700934} // namespace net
935} // namespace android