blob: 9e9e257ceedaff0b077e504333b763951a08b01e [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 Fengef297172018-03-26 10:53:33 -070050#include "DumpWriter.h"
Chenbo Feng89c12f12018-03-21 10:29:18 -070051#include "FirewallController.h"
Chenbo Feng7e974052018-02-28 22:57:21 -080052#include "InterfaceController.h"
Chenbo Feng116d0552017-12-04 17:25:19 -080053#include "NetlinkListener.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;
Chenbo Feng116d0552017-12-04 17:25:19 -080063using netdutils::extract;
64using netdutils::Slice;
65using netdutils::sSyscalls;
Chenbo Fengc10a8a42017-12-15 13:56:33 -080066using netdutils::Status;
67using netdutils::statusFromErrno;
68using netdutils::StatusOr;
Chenbo Feng116d0552017-12-04 17:25:19 -080069using netdutils::status::ok;
Chenbo Fengc10a8a42017-12-15 13:56:33 -080070
Chenbo Feng116d0552017-12-04 17:25:19 -080071constexpr int kSockDiagMsgType = SOCK_DIAG_BY_FAMILY;
72constexpr int kSockDiagDoneMsgType = NLMSG_DONE;
73
Chenbo Feng48eaed32018-12-26 17:40:21 -080074#define FLAG_MSG_TRANS(result, flag, value) \
75 do { \
76 if (value & flag) { \
77 result.append(StringPrintf(" %s", #flag)); \
78 value &= ~flag; \
79 } \
Chenbo Feng703798e2018-06-15 17:07:59 -070080 } while (0)
81
82const std::string uidMatchTypeToString(uint8_t match) {
83 std::string matchType;
Chenbo Feng48eaed32018-12-26 17:40:21 -080084 FLAG_MSG_TRANS(matchType, HAPPY_BOX_MATCH, match);
85 FLAG_MSG_TRANS(matchType, PENALTY_BOX_MATCH, match);
86 FLAG_MSG_TRANS(matchType, DOZABLE_MATCH, match);
87 FLAG_MSG_TRANS(matchType, STANDBY_MATCH, match);
88 FLAG_MSG_TRANS(matchType, POWERSAVE_MATCH, match);
Chenbo Feng703798e2018-06-15 17:07:59 -070089 if (match) {
90 return StringPrintf("Unknown match: %u", match);
91 }
92 return matchType;
93}
94
Chenbo Fengb4a4fa12019-01-09 17:20:45 -080095bool TrafficController::hasUpdateDeviceStatsPermission(uid_t uid) {
Chenbo Feng2142a2b2019-03-14 20:04:02 -070096 return ((uid == AID_ROOT) || (uid == AID_SYSTEM) ||
97 mPrivilegedUser.find(uid) != mPrivilegedUser.end());
Chenbo Fengb4a4fa12019-01-09 17:20:45 -080098}
99
Chenbo Feng48eaed32018-12-26 17:40:21 -0800100const std::string UidPermissionTypeToString(uint8_t permission) {
101 std::string permissionType;
102 FLAG_MSG_TRANS(permissionType, ALLOW_SOCK_CREATE, permission);
103 FLAG_MSG_TRANS(permissionType, ALLOW_UPDATE_DEVICE_STATS, permission);
104 if (permission) {
105 return StringPrintf("Unknown permission: %u", permission);
106 }
107 return permissionType;
108}
109
Chenbo Feng49586642018-08-30 18:01:53 -0700110StatusOr<std::unique_ptr<NetlinkListenerInterface>> TrafficController::makeSkDestroyListener() {
Chenbo Feng116d0552017-12-04 17:25:19 -0800111 const auto& sys = sSyscalls.get();
112 ASSIGN_OR_RETURN(auto event, sys.eventfd(0, EFD_CLOEXEC));
113 const int domain = AF_NETLINK;
114 const int type = SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK;
115 const int protocol = NETLINK_INET_DIAG;
116 ASSIGN_OR_RETURN(auto sock, sys.socket(domain, type, protocol));
117
Lorenzo Colitti436efdb2018-07-26 17:20:57 +0900118 // TODO: if too many sockets are closed too quickly, we can overflow the socket buffer, and
119 // some entries in mCookieTagMap will not be freed. In order to fix this we would need to
120 // periodically dump all sockets and remove the tag entries for sockets that have been closed.
121 // For now, set a large-enough buffer that we can close hundreds of sockets without getting
122 // ENOBUFS and leaking mCookieTagMap entries.
123 int rcvbuf = 512 * 1024;
124 auto ret = sys.setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf));
125 if (!ret.ok()) {
126 ALOGW("Failed to set SkDestroyListener buffer size to %d: %s", rcvbuf, ret.msg().c_str());
127 }
128
Chenbo Feng116d0552017-12-04 17:25:19 -0800129 sockaddr_nl addr = {
130 .nl_family = AF_NETLINK,
131 .nl_groups = 1 << (SKNLGRP_INET_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET_UDP_DESTROY - 1) |
132 1 << (SKNLGRP_INET6_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET6_UDP_DESTROY - 1)};
133 RETURN_IF_NOT_OK(sys.bind(sock, addr));
134
135 const sockaddr_nl kernel = {.nl_family = AF_NETLINK};
136 RETURN_IF_NOT_OK(sys.connect(sock, kernel));
137
138 std::unique_ptr<NetlinkListenerInterface> listener =
Chenbo Feng46296702018-08-23 12:20:22 -0700139 std::make_unique<NetlinkListener>(std::move(event), std::move(sock), "SkDestroyListen");
Chenbo Feng116d0552017-12-04 17:25:19 -0800140
141 return listener;
142}
143
Chenbo Feng89c12f12018-03-21 10:29:18 -0700144Status changeOwnerAndMode(const char* path, gid_t group, const char* debugName, bool netdOnly) {
145 int ret = chown(path, AID_ROOT, group);
146 if (ret != 0) return statusFromErrno(errno, StringPrintf("change %s group failed", debugName));
147
148 if (netdOnly) {
149 ret = chmod(path, S_IRWXU);
150 } else {
151 // Allow both netd and system server to obtain map fd from the path.
152 // chmod doesn't grant permission to all processes in that group to
153 // read/write the bpf map. They still need correct sepolicy to
154 // read/write the map.
Chenbo Fengf434e862018-06-27 14:08:39 -0700155 ret = chmod(path, S_IRWXU | S_IRGRP | S_IWGRP);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700156 }
157 if (ret != 0) return statusFromErrno(errno, StringPrintf("change %s mode failed", debugName));
158 return netdutils::status::ok;
159}
160
Chenbo Feng47dd0732018-12-11 12:23:24 -0800161TrafficController::TrafficController() : mBpfLevel(getBpfSupportLevel()) {}
Chenbo Feng89c12f12018-03-21 10:29:18 -0700162
Chenbo Feng89c12f12018-03-21 10:29:18 -0700163Status TrafficController::initMaps() {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900164 std::lock_guard ownerMapGuard(mOwnerMatchMutex);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700165 RETURN_IF_NOT_OK(
166 mCookieTagMap.getOrCreate(COOKIE_UID_MAP_SIZE, COOKIE_TAG_MAP_PATH, BPF_MAP_TYPE_HASH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700167
168 RETURN_IF_NOT_OK(changeOwnerAndMode(COOKIE_TAG_MAP_PATH, AID_NET_BW_ACCT, "CookieTagMap",
169 false));
170
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700171 RETURN_IF_NOT_OK(mUidCounterSetMap.getOrCreate(UID_COUNTERSET_MAP_SIZE, UID_COUNTERSET_MAP_PATH,
172 BPF_MAP_TYPE_HASH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700173 RETURN_IF_NOT_OK(changeOwnerAndMode(UID_COUNTERSET_MAP_PATH, AID_NET_BW_ACCT,
174 "UidCounterSetMap", false));
175
Chenbo Fengf434e862018-06-27 14:08:39 -0700176 RETURN_IF_NOT_OK(mAppUidStatsMap.getOrCreate(APP_STATS_MAP_SIZE, APP_UID_STATS_MAP_PATH,
177 BPF_MAP_TYPE_HASH));
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700178 RETURN_IF_NOT_OK(
179 changeOwnerAndMode(APP_UID_STATS_MAP_PATH, AID_NET_BW_STATS, "AppUidStatsMap", false));
180
Chenbo Fengf434e862018-06-27 14:08:39 -0700181 RETURN_IF_NOT_OK(mStatsMapA.getOrCreate(STATS_MAP_SIZE, STATS_MAP_A_PATH, BPF_MAP_TYPE_HASH));
182 RETURN_IF_NOT_OK(changeOwnerAndMode(STATS_MAP_A_PATH, AID_NET_BW_STATS, "StatsMapA", false));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700183
Chenbo Fengf434e862018-06-27 14:08:39 -0700184 RETURN_IF_NOT_OK(mStatsMapB.getOrCreate(STATS_MAP_SIZE, STATS_MAP_B_PATH, BPF_MAP_TYPE_HASH));
185 RETURN_IF_NOT_OK(changeOwnerAndMode(STATS_MAP_B_PATH, AID_NET_BW_STATS, "StatsMapB", false));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700186
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700187 RETURN_IF_NOT_OK(mIfaceIndexNameMap.getOrCreate(IFACE_INDEX_NAME_MAP_SIZE,
188 IFACE_INDEX_NAME_MAP_PATH, BPF_MAP_TYPE_HASH));
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
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700192 RETURN_IF_NOT_OK(
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700193 mIfaceStatsMap.getOrCreate(IFACE_STATS_MAP_SIZE, IFACE_STATS_MAP_PATH, BPF_MAP_TYPE_HASH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700194 RETURN_IF_NOT_OK(changeOwnerAndMode(IFACE_STATS_MAP_PATH, AID_NET_BW_STATS, "IfaceStatsMap",
195 false));
Chenbo Feng95892f32018-06-07 14:52:02 -0700196
Chenbo Feng703798e2018-06-15 17:07:59 -0700197 RETURN_IF_NOT_OK(mConfigurationMap.getOrCreate(CONFIGURATION_MAP_SIZE, CONFIGURATION_MAP_PATH,
198 BPF_MAP_TYPE_HASH));
Chenbo Fengf434e862018-06-27 14:08:39 -0700199 RETURN_IF_NOT_OK(changeOwnerAndMode(CONFIGURATION_MAP_PATH, AID_NET_BW_STATS,
200 "ConfigurationMap", false));
Chenbo Feng703798e2018-06-15 17:07:59 -0700201 RETURN_IF_NOT_OK(
Chenbo Fengf434e862018-06-27 14:08:39 -0700202 mConfigurationMap.writeValue(UID_RULES_CONFIGURATION_KEY, DEFAULT_CONFIG, BPF_ANY));
203 RETURN_IF_NOT_OK(mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, SELECT_MAP_A,
204 BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700205
206 RETURN_IF_NOT_OK(
207 mUidOwnerMap.getOrCreate(UID_OWNER_MAP_SIZE, UID_OWNER_MAP_PATH, BPF_MAP_TYPE_HASH));
208 RETURN_IF_NOT_OK(changeOwnerAndMode(UID_OWNER_MAP_PATH, AID_ROOT, "UidOwnerMap", true));
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900209 RETURN_IF_NOT_OK(mUidOwnerMap.clear());
Chenbo Feng48eaed32018-12-26 17:40:21 -0800210 RETURN_IF_NOT_OK(mUidPermissionMap.getOrCreate(UID_OWNER_MAP_SIZE, UID_PERMISSION_MAP_PATH,
211 BPF_MAP_TYPE_HASH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700212 return netdutils::status::ok;
213}
214
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800215static Status attachProgramToCgroup(const char* programPath, const int cgroupFd,
216 bpf_attach_type type) {
217 unique_fd cgroupProg(bpfFdGet(programPath, 0));
218 if (cgroupProg == -1) {
219 int ret = errno;
220 ALOGE("Failed to get program from %s: %s", programPath, strerror(ret));
221 return statusFromErrno(ret, "cgroup program get failed");
222 }
223 if (android::bpf::attachProgram(type, cgroupProg, cgroupFd)) {
224 int ret = errno;
225 ALOGE("Program from %s attach failed: %s", programPath, strerror(ret));
226 return statusFromErrno(ret, "program attach failed");
227 }
228 return netdutils::status::ok;
229}
230
231static Status initPrograms() {
Suren Baghdasaryane072a3c2019-01-16 14:36:07 -0800232 std::string cg2_path;
233
234 if (!CgroupGetControllerPath(CGROUPV2_CONTROLLER_NAME, &cg2_path)) {
235 int ret = errno;
236 ALOGE("Failed to find cgroup v2 root");
237 return statusFromErrno(ret, "Failed to find cgroup v2 root");
238 }
239
240 unique_fd cg_fd(open(cg2_path.c_str(), O_DIRECTORY | O_RDONLY | O_CLOEXEC));
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800241 if (cg_fd == -1) {
242 int ret = errno;
243 ALOGE("Failed to open the cgroup directory: %s", strerror(ret));
244 return statusFromErrno(ret, "Open the cgroup directory failed");
245 }
246 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_EGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_EGRESS));
247 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_INGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_INGRESS));
Chenbo Fenga51f4fa2019-01-15 15:03:32 -0800248
249 // For the devices that support cgroup socket filter, the socket filter
250 // should be loaded successfully by bpfloader. So we attach the filter to
251 // cgroup if the program is pinned properly.
252 // TODO: delete the if statement once all devices should support cgroup
253 // socket filter (ie. the minimum kernel version required is 4.14).
254 if (!access(CGROUP_SOCKET_PROG_PATH, F_OK)) {
255 RETURN_IF_NOT_OK(
256 attachProgramToCgroup(CGROUP_SOCKET_PROG_PATH, cg_fd, BPF_CGROUP_INET_SOCK_CREATE));
257 }
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800258 return netdutils::status::ok;
259}
260
Chenbo Feng89c12f12018-03-21 10:29:18 -0700261Status TrafficController::start() {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800262 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800263 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700264 }
265
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900266 /* When netd restarts from a crash without total system reboot, the program
Chenbo Fengf2759682017-10-10 17:31:57 -0700267 * is still attached to the cgroup, detach it so the program can be freed
268 * and we can load and attach new program into the target cgroup.
269 *
270 * TODO: Scrape existing socket when run-time restart and clean up the map
271 * if the socket no longer exist
272 */
273
Chenbo Feng89c12f12018-03-21 10:29:18 -0700274 RETURN_IF_NOT_OK(initMaps());
Chenbo Feng7e974052018-02-28 22:57:21 -0800275
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800276 RETURN_IF_NOT_OK(initPrograms());
277
Chenbo Feng7e974052018-02-28 22:57:21 -0800278 // Fetch the list of currently-existing interfaces. At this point NetlinkHandler is
279 // already running, so it will call addInterface() when any new interface appears.
280 std::map<std::string, uint32_t> ifacePairs;
281 ASSIGN_OR_RETURN(ifacePairs, InterfaceController::getIfaceList());
282 for (const auto& ifacePair:ifacePairs) {
283 addInterface(ifacePair.first.c_str(), ifacePair.second);
284 }
285
Chenbo Feng116d0552017-12-04 17:25:19 -0800286 auto result = makeSkDestroyListener();
287 if (!isOk(result)) {
288 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
289 } else {
290 mSkDestroyListener = std::move(result.value());
291 }
292 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
293 const auto rxHandler = [this](const nlmsghdr&, const Slice msg) {
294 inet_diag_msg diagmsg = {};
295 if (extract(msg, diagmsg) < sizeof(inet_diag_msg)) {
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900296 ALOGE("Unrecognized netlink message: %s", toString(msg).c_str());
Chenbo Feng116d0552017-12-04 17:25:19 -0800297 return;
298 }
299 uint64_t sock_cookie = static_cast<uint64_t>(diagmsg.id.idiag_cookie[0]) |
300 (static_cast<uint64_t>(diagmsg.id.idiag_cookie[1]) << 32);
301
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900302 Status s = mCookieTagMap.deleteValue(sock_cookie);
Chenbo Feng1d4c5db2018-10-18 15:50:46 -0700303 if (!isOk(s) && s.code() != ENOENT) {
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900304 ALOGE("Failed to delete cookie %" PRIx64 ": %s", sock_cookie, toString(s).c_str());
305 return;
306 }
Chenbo Feng116d0552017-12-04 17:25:19 -0800307 };
308 expectOk(mSkDestroyListener->subscribe(kSockDiagMsgType, rxHandler));
309
310 // In case multiple netlink message comes in as a stream, we need to handle the rxDone message
311 // properly.
312 const auto rxDoneHandler = [](const nlmsghdr&, const Slice msg) {
313 // Ignore NLMSG_DONE messages
314 inet_diag_msg diagmsg = {};
315 extract(msg, diagmsg);
316 };
317 expectOk(mSkDestroyListener->subscribe(kSockDiagDoneMsgType, rxDoneHandler));
318
Chenbo Feng05393d82018-01-09 15:18:43 -0800319 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700320}
321
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800322int TrafficController::tagSocket(int sockFd, uint32_t tag, uid_t uid, uid_t callingUid) {
323 if (uid != callingUid && !hasUpdateDeviceStatsPermission(callingUid)) {
324 return -EPERM;
325 }
326
Chenbo Feng47dd0732018-12-11 12:23:24 -0800327 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700328 if (legacy_tagSocket(sockFd, tag, uid)) return -errno;
329 return 0;
330 }
Chenbo Feng33cc1032017-10-23 15:16:37 -0700331
Chenbo Fengf2759682017-10-10 17:31:57 -0700332 uint64_t sock_cookie = getSocketCookie(sockFd);
Chenbo Fengef1cab32018-04-13 19:50:49 -0700333 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
Chenbo Fengf2759682017-10-10 17:31:57 -0700334 UidTag newKey = {.uid = (uint32_t)uid, .tag = tag};
335
336 // Update the tag information of a socket to the cookieUidMap. Use BPF_ANY
337 // flag so it will insert a new entry to the map if that value doesn't exist
338 // yet. And update the tag if there is already a tag stored. Since the eBPF
339 // program in kernel only read this map, and is protected by rcu read lock. It
340 // should be fine to cocurrently update the map while eBPF program is running.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700341 Status res = mCookieTagMap.writeValue(sock_cookie, newKey, BPF_ANY);
342 if (!isOk(res)) {
343 ALOGE("Failed to tag the socket: %s, fd: %d", strerror(res.code()),
344 mCookieTagMap.getMap().get());
Chenbo Fengf2759682017-10-10 17:31:57 -0700345 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700346 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700347}
348
349int TrafficController::untagSocket(int sockFd) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800350 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700351 if (legacy_untagSocket(sockFd)) return -errno;
352 return 0;
353 }
Chenbo Fengf2759682017-10-10 17:31:57 -0700354 uint64_t sock_cookie = getSocketCookie(sockFd);
355
Chenbo Fengef1cab32018-04-13 19:50:49 -0700356 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700357 Status res = mCookieTagMap.deleteValue(sock_cookie);
358 if (!isOk(res)) {
359 ALOGE("Failed to untag socket: %s\n", strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700360 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700361 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700362}
363
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800364int TrafficController::setCounterSet(int counterSetNum, uid_t uid, uid_t callingUid) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700365 if (counterSetNum < 0 || counterSetNum >= OVERFLOW_COUNTERSET) return -EINVAL;
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800366
367 if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
368
Chenbo Feng47dd0732018-12-11 12:23:24 -0800369 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700370 if (legacy_setCounterSet(counterSetNum, uid)) return -errno;
371 return 0;
372 }
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800373
374 // The default counter set for all uid is 0, so deleting the current counterset for that uid
375 // will automatically set it to 0.
Chenbo Fengf2759682017-10-10 17:31:57 -0700376 if (counterSetNum == 0) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700377 Status res = mUidCounterSetMap.deleteValue(uid);
378 if (isOk(res) || (!isOk(res) && res.code() == ENOENT)) {
Chenbo Fengf2759682017-10-10 17:31:57 -0700379 return 0;
380 } else {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700381 ALOGE("Failed to delete the counterSet: %s\n", strerror(res.code()));
382 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700383 }
384 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700385 uint8_t tmpCounterSetNum = (uint8_t)counterSetNum;
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800386 Status res = mUidCounterSetMap.writeValue(uid, tmpCounterSetNum, BPF_ANY);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700387 if (!isOk(res)) {
388 ALOGE("Failed to set the counterSet: %s, fd: %d", strerror(res.code()),
389 mUidCounterSetMap.getMap().get());
390 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700391 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700392 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700393}
394
Chenbo Fengf434e862018-06-27 14:08:39 -0700395// This method only get called by system_server when an app get uinstalled, it
396// is called inside removeUidsLocked() while holding mStatsLock. So it is safe
397// to iterate and modify the stats maps.
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800398int TrafficController::deleteTagData(uint32_t tag, uid_t uid, uid_t callingUid) {
399 if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
400
Chenbo Feng47dd0732018-12-11 12:23:24 -0800401 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700402 if (legacy_deleteTagData(tag, uid)) return -errno;
403 return 0;
404 }
Chenbo Feng33cc1032017-10-23 15:16:37 -0700405
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800406 // First we go through the cookieTagMap to delete the target uid tag combination. Or delete all
Chenbo Fengef1cab32018-04-13 19:50:49 -0700407 // the tags related to the uid if the tag is 0.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700408 const auto deleteMatchedCookieEntries = [uid, tag](const uint64_t& key, const UidTag& value,
409 BpfMap<uint64_t, UidTag>& map) {
410 if (value.uid == uid && (value.tag == tag || tag == 0)) {
411 Status res = map.deleteValue(key);
412 if (isOk(res) || (res.code() == ENOENT)) {
413 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700414 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700415 ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s\n", key, strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700416 }
Chenbo Fengef1cab32018-04-13 19:50:49 -0700417 // Move forward to next cookie in the map.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700418 return netdutils::status::ok;
Chenbo Fengef1cab32018-04-13 19:50:49 -0700419 };
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900420 mCookieTagMap.iterateWithValue(deleteMatchedCookieEntries).ignoreError();
Chenbo Fengf2759682017-10-10 17:31:57 -0700421 // 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 -0700422 // combination. Or all tag stats under that uid if the target tag is 0.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700423 const auto deleteMatchedUidTagEntries = [uid, tag](const StatsKey& key,
424 BpfMap<StatsKey, StatsValue>& map) {
425 if (key.uid == uid && (key.tag == tag || tag == 0)) {
426 Status res = map.deleteValue(key);
427 if (isOk(res) || (res.code() == ENOENT)) {
Chenbo Fengef1cab32018-04-13 19:50:49 -0700428 //Entry is deleted, use the current key to get a new nextKey;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700429 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700430 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700431 ALOGE("Failed to delete data(uid=%u, tag=%u): %s\n", key.uid, key.tag,
432 strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700433 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700434 return netdutils::status::ok;
Chenbo Fengef1cab32018-04-13 19:50:49 -0700435 };
Chenbo Fengf434e862018-06-27 14:08:39 -0700436 mStatsMapB.iterate(deleteMatchedUidTagEntries).ignoreError();
437 mStatsMapA.iterate(deleteMatchedUidTagEntries).ignoreError();
Chenbo Fengf2759682017-10-10 17:31:57 -0700438 // 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 -0800439 // need to delete the stats stored in uidStatsMap and counterSet map.
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800440 if (tag != 0) return 0;
441
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700442 Status res = mUidCounterSetMap.deleteValue(uid);
443 if (!isOk(res) && res.code() != ENOENT) {
444 ALOGE("Failed to delete counterSet data(uid=%u, tag=%u): %s\n", uid, tag,
445 strerror(res.code()));
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800446 }
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700447
448 auto deleteAppUidStatsEntry = [uid](const uint32_t& key, BpfMap<uint32_t, StatsValue>& map) {
449 if (key == uid) {
450 Status res = map.deleteValue(key);
451 if (isOk(res) || (res.code() == ENOENT)) {
452 return netdutils::status::ok;
453 }
454 ALOGE("Failed to delete data(uid=%u): %s", key, strerror(res.code()));
455 }
456 return netdutils::status::ok;
457 };
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900458 mAppUidStatsMap.iterate(deleteAppUidStatsEntry).ignoreError();
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700459 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700460}
461
Chenbo Feng7e974052018-02-28 22:57:21 -0800462int TrafficController::addInterface(const char* name, uint32_t ifaceIndex) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800463 if (mBpfLevel == BpfLevel::NONE) return 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800464
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700465 IfaceValue iface;
Chenbo Feng7e974052018-02-28 22:57:21 -0800466 if (ifaceIndex == 0) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700467 ALOGE("Unknown interface %s(%d)", name, ifaceIndex);
Chenbo Feng7e974052018-02-28 22:57:21 -0800468 return -1;
469 }
470
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700471 strlcpy(iface.name, name, sizeof(IfaceValue));
472 Status res = mIfaceIndexNameMap.writeValue(ifaceIndex, iface, BPF_ANY);
473 if (!isOk(res)) {
474 ALOGE("Failed to add iface %s(%d): %s", name, ifaceIndex, strerror(res.code()));
475 return -res.code();
Chenbo Feng7e974052018-02-28 22:57:21 -0800476 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700477 return 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800478}
479
Chenbo Feng703798e2018-06-15 17:07:59 -0700480Status TrafficController::updateOwnerMapEntry(UidOwnerMatchType match, uid_t uid, FirewallRule rule,
481 FirewallType type) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900482 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700483 if ((rule == ALLOW && type == WHITELIST) || (rule == DENY && type == BLACKLIST)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700484 RETURN_IF_NOT_OK(addMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700485 } else if ((rule == ALLOW && type == BLACKLIST) || (rule == DENY && type == WHITELIST)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700486 RETURN_IF_NOT_OK(removeMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700487 } else {
488 //Cannot happen.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700489 return statusFromErrno(-EINVAL, "");
Chenbo Feng89c12f12018-03-21 10:29:18 -0700490 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700491 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700492}
493
Chenbo Feng703798e2018-06-15 17:07:59 -0700494UidOwnerMatchType TrafficController::jumpOpToMatch(BandwidthController::IptJumpOp jumpHandling) {
Chenbo Feng95892f32018-06-07 14:52:02 -0700495 switch (jumpHandling) {
496 case BandwidthController::IptJumpReject:
Chenbo Feng703798e2018-06-15 17:07:59 -0700497 return PENALTY_BOX_MATCH;
Chenbo Feng95892f32018-06-07 14:52:02 -0700498 case BandwidthController::IptJumpReturn:
Chenbo Feng703798e2018-06-15 17:07:59 -0700499 return HAPPY_BOX_MATCH;
Chenbo Feng95892f32018-06-07 14:52:02 -0700500 case BandwidthController::IptJumpNoAdd:
501 return NO_MATCH;
502 }
503}
504
Chenbo Feng703798e2018-06-15 17:07:59 -0700505Status TrafficController::removeMatch(BpfMap<uint32_t, uint8_t>& map, uint32_t uid,
506 UidOwnerMatchType match) {
507 auto oldMatch = map.readValue(uid);
508 if (isOk(oldMatch)) {
509 uint8_t newMatch = oldMatch.value() & ~match;
510 if (newMatch == 0) {
511 RETURN_IF_NOT_OK(map.deleteValue(uid));
512 } else {
513 RETURN_IF_NOT_OK(map.writeValue(uid, newMatch, BPF_ANY));
514 }
515 } else {
516 return statusFromErrno(ENOENT, StringPrintf("uid: %u does not exist in map", uid));
517 }
518 return netdutils::status::ok;
519}
520
521Status TrafficController::addMatch(BpfMap<uint32_t, uint8_t>& map, uint32_t uid,
522 UidOwnerMatchType match) {
523 auto oldMatch = map.readValue(uid);
524 if (isOk(oldMatch)) {
525 uint8_t newMatch = oldMatch.value() | match;
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900526 RETURN_IF_NOT_OK(map.writeValue((uint32_t) uid, newMatch, BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700527 } else {
528 RETURN_IF_NOT_OK(map.writeValue(uid, match, BPF_ANY));
529 }
530 return netdutils::status::ok;
531}
532
533Status TrafficController::updateUidOwnerMap(const std::vector<std::string>& appStrUids,
534 BandwidthController::IptJumpOp jumpHandling,
535 BandwidthController::IptOp op) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900536 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Feng703798e2018-06-15 17:07:59 -0700537 UidOwnerMatchType match = jumpOpToMatch(jumpHandling);
538 if (match == NO_MATCH) {
539 return statusFromErrno(
540 EINVAL, StringPrintf("invalid IptJumpOp: %d, command: %d", jumpHandling, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700541 }
542 for (const auto& appStrUid : appStrUids) {
543 char* endPtr;
544 long uid = strtol(appStrUid.c_str(), &endPtr, 10);
545 if ((errno == ERANGE && (uid == LONG_MAX || uid == LONG_MIN)) ||
546 (endPtr == appStrUid.c_str()) || (*endPtr != '\0')) {
547 return statusFromErrno(errno, "invalid uid string:" + appStrUid);
548 }
549
Chenbo Feng95892f32018-06-07 14:52:02 -0700550 if (op == BandwidthController::IptOpDelete) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700551 RETURN_IF_NOT_OK(removeMatch(mUidOwnerMap, uid, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700552 } else if (op == BandwidthController::IptOpInsert) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700553 RETURN_IF_NOT_OK(addMatch(mUidOwnerMap, uid, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700554 } else {
555 // Cannot happen.
Chenbo Feng703798e2018-06-15 17:07:59 -0700556 return statusFromErrno(EINVAL, StringPrintf("invalid IptOp: %d, %d", op, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700557 }
558 }
559 return netdutils::status::ok;
560}
561
Chenbo Feng89c12f12018-03-21 10:29:18 -0700562int TrafficController::changeUidOwnerRule(ChildChain chain, uid_t uid, FirewallRule rule,
563 FirewallType type) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800564 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Feng89c12f12018-03-21 10:29:18 -0700565 ALOGE("bpf is not set up, should use iptables rule");
566 return -ENOSYS;
567 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700568 Status res;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700569 switch (chain) {
570 case DOZABLE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700571 res = updateOwnerMapEntry(DOZABLE_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700572 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700573 case STANDBY:
Chenbo Feng703798e2018-06-15 17:07:59 -0700574 res = updateOwnerMapEntry(STANDBY_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700575 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700576 case POWERSAVE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700577 res = updateOwnerMapEntry(POWERSAVE_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700578 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700579 case NONE:
580 default:
581 return -EINVAL;
582 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700583 if (!isOk(res)) {
584 ALOGE("change uid(%u) rule of %d failed: %s, rule: %d, type: %d", uid, chain,
585 res.msg().c_str(), rule, type);
586 return -res.code();
587 }
588 return 0;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700589}
590
Chenbo Feng703798e2018-06-15 17:07:59 -0700591Status TrafficController::replaceUidsInMap(const UidOwnerMatchType match,
592 const std::vector<int32_t>& uids) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900593 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700594 std::set<int32_t> uidSet(uids.begin(), uids.end());
595 std::vector<uint32_t> uidsToDelete;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700596 auto getUidsToDelete = [&uidsToDelete, &uidSet](const uint32_t& key,
597 const BpfMap<uint32_t, uint8_t>&) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700598 if (uidSet.find((int32_t) key) == uidSet.end()) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700599 uidsToDelete.push_back(key);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700600 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700601 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700602 };
Chenbo Feng703798e2018-06-15 17:07:59 -0700603 RETURN_IF_NOT_OK(mUidOwnerMap.iterate(getUidsToDelete));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700604
605 for(auto uid : uidsToDelete) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700606 RETURN_IF_NOT_OK(removeMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700607 }
608
609 for (auto uid : uids) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700610 RETURN_IF_NOT_OK(addMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700611 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700612 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700613}
614
615int TrafficController::replaceUidOwnerMap(const std::string& name, bool isWhitelist,
616 const std::vector<int32_t>& uids) {
Chenbo Feng89c12f12018-03-21 10:29:18 -0700617 FirewallRule rule;
618 FirewallType type;
619 if (isWhitelist) {
620 type = WHITELIST;
621 rule = ALLOW;
622 } else {
623 type = BLACKLIST;
624 rule = DENY;
625 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700626 Status res;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700627 if (!name.compare(FirewallController::LOCAL_DOZABLE)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700628 res = replaceUidsInMap(DOZABLE_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700629 } else if (!name.compare(FirewallController::LOCAL_STANDBY)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700630 res = replaceUidsInMap(STANDBY_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700631 } else if (!name.compare(FirewallController::LOCAL_POWERSAVE)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700632 res = replaceUidsInMap(POWERSAVE_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700633 } else {
634 ALOGE("unknown chain name: %s", name.c_str());
635 return -EINVAL;
636 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700637 if (!isOk(res)) {
638 ALOGE("Failed to clean up chain: %s: %s", name.c_str(), res.msg().c_str());
639 return -res.code();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700640 }
641 return 0;
642}
643
644int TrafficController::toggleUidOwnerMap(ChildChain chain, bool enable) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900645 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Fengf434e862018-06-27 14:08:39 -0700646 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Chenbo Feng703798e2018-06-15 17:07:59 -0700647 auto oldConfiguration = mConfigurationMap.readValue(key);
648 if (!isOk(oldConfiguration)) {
649 ALOGE("Cannot read the old configuration from map: %s",
650 oldConfiguration.status().msg().c_str());
651 return -oldConfiguration.status().code();
652 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700653 Status res;
Chenbo Feng703798e2018-06-15 17:07:59 -0700654 BpfConfig newConfiguration;
655 uint8_t match;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700656 switch (chain) {
657 case DOZABLE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700658 match = DOZABLE_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700659 break;
660 case STANDBY:
Chenbo Feng703798e2018-06-15 17:07:59 -0700661 match = STANDBY_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700662 break;
663 case POWERSAVE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700664 match = POWERSAVE_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700665 break;
666 default:
667 return -EINVAL;
668 }
Chenbo Feng703798e2018-06-15 17:07:59 -0700669 newConfiguration =
670 enable ? (oldConfiguration.value() | match) : (oldConfiguration.value() & (~match));
671 res = mConfigurationMap.writeValue(key, newConfiguration, BPF_EXIST);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700672 if (!isOk(res)) {
673 ALOGE("Failed to toggleUidOwnerMap(%d): %s", chain, res.msg().c_str());
Chenbo Feng89c12f12018-03-21 10:29:18 -0700674 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700675 return -res.code();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700676}
677
Chenbo Feng47dd0732018-12-11 12:23:24 -0800678BpfLevel TrafficController::getBpfLevel() {
679 return mBpfLevel;
Chenbo Feng07d43fe2017-12-21 14:38:51 -0800680}
681
Chenbo Feng48eaed32018-12-26 17:40:21 -0800682void TrafficController::setPermissionForUids(int permission, const std::vector<uid_t>& uids) {
683 bool internet = (permission & INetd::PERMISSION_INTERNET);
684 bool privileged = (permission & INetd::PERMISSION_UPDATE_DEVICE_STATS);
685
686 for (uid_t uid : uids) {
687 if (internet) {
688 Status ret = mUidPermissionMap.writeValue(uid, ALLOW_SOCK_CREATE, BPF_ANY);
689 if (!isOk(ret)) {
690 ALOGE("Failed to grant INTERNET permission to uid: %u: %s", uid,
691 strerror(ret.code()));
692 }
693 } else {
694 Status ret = mUidPermissionMap.deleteValue(uid);
695 if (!isOk(ret) && ret.code() != ENOENT) {
696 ALOGE("Failed to revoke permission INTERNET from uid: %u: %s", uid,
697 strerror(ret.code()));
698 }
699 }
700
701 if (privileged) {
702 mPrivilegedUser.insert(uid);
703 } else {
704 mPrivilegedUser.erase(uid);
705 }
706 }
707}
708
Chenbo Fengef297172018-03-26 10:53:33 -0700709std::string getProgramStatus(const char *path) {
710 int ret = access(path, R_OK);
711 if (ret == 0) {
712 return StringPrintf("OK");
713 }
714 if (ret != 0 && errno == ENOENT) {
715 return StringPrintf("program is missing at: %s", path);
716 }
717 return StringPrintf("check Program %s error: %s", path, strerror(errno));
718}
719
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700720std::string getMapStatus(const base::unique_fd& map_fd, const char* path) {
Chenbo Fengef297172018-03-26 10:53:33 -0700721 if (map_fd.get() < 0) {
722 return StringPrintf("map fd lost");
723 }
724 if (access(path, F_OK) != 0) {
725 return StringPrintf("map not pinned to location: %s", path);
726 }
727 return StringPrintf("OK");
728}
729
Bernie Innocentia5161a02019-01-30 22:40:53 +0900730// NOLINTNEXTLINE(google-runtime-references): grandfathered pass by non-const reference
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900731void dumpBpfMap(const std::string& mapName, DumpWriter& dw, const std::string& header) {
Chenbo Fengef297172018-03-26 10:53:33 -0700732 dw.blankline();
733 dw.println("%s:", mapName.c_str());
Erik Klineb31fd692018-06-06 20:50:11 +0900734 if (!header.empty()) {
735 dw.println(header);
Chenbo Fengef297172018-03-26 10:53:33 -0700736 }
737}
738
739const String16 TrafficController::DUMP_KEYWORD = String16("trafficcontroller");
740
741void TrafficController::dump(DumpWriter& dw, bool verbose) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900742 std::lock_guard ownerMapGuard(mOwnerMatchMutex);
Erik Klineb31fd692018-06-06 20:50:11 +0900743 ScopedIndent indentTop(dw);
Chenbo Fengef297172018-03-26 10:53:33 -0700744 dw.println("TrafficController");
745
Erik Klineb31fd692018-06-06 20:50:11 +0900746 ScopedIndent indentPreBpfModule(dw);
Chenbo Feng47dd0732018-12-11 12:23:24 -0800747 dw.println("BPF module status: %s", BpfLevelToString(mBpfLevel).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700748
Chenbo Feng47dd0732018-12-11 12:23:24 -0800749 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengef297172018-03-26 10:53:33 -0700750 return;
Erik Klineb31fd692018-06-06 20:50:11 +0900751 }
Chenbo Fengef297172018-03-26 10:53:33 -0700752
753 dw.blankline();
754 dw.println("mCookieTagMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700755 getMapStatus(mCookieTagMap.getMap(), COOKIE_TAG_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700756 dw.println("mUidCounterSetMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700757 getMapStatus(mUidCounterSetMap.getMap(), UID_COUNTERSET_MAP_PATH).c_str());
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700758 dw.println("mAppUidStatsMap status: %s",
759 getMapStatus(mAppUidStatsMap.getMap(), APP_UID_STATS_MAP_PATH).c_str());
Chenbo Fengf434e862018-06-27 14:08:39 -0700760 dw.println("mStatsMapA status: %s",
761 getMapStatus(mStatsMapA.getMap(), STATS_MAP_A_PATH).c_str());
762 dw.println("mStatsMapB status: %s",
763 getMapStatus(mStatsMapB.getMap(), STATS_MAP_B_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700764 dw.println("mIfaceIndexNameMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700765 getMapStatus(mIfaceIndexNameMap.getMap(), IFACE_INDEX_NAME_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700766 dw.println("mIfaceStatsMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700767 getMapStatus(mIfaceStatsMap.getMap(), IFACE_STATS_MAP_PATH).c_str());
Chenbo Feng703798e2018-06-15 17:07:59 -0700768 dw.println("mConfigurationMap status: %s",
769 getMapStatus(mConfigurationMap.getMap(), CONFIGURATION_MAP_PATH).c_str());
770 dw.println("mUidOwnerMap status: %s",
771 getMapStatus(mUidOwnerMap.getMap(), UID_OWNER_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700772
773 dw.blankline();
774 dw.println("Cgroup ingress program status: %s",
775 getProgramStatus(BPF_INGRESS_PROG_PATH).c_str());
776 dw.println("Cgroup egress program status: %s", getProgramStatus(BPF_EGRESS_PROG_PATH).c_str());
777 dw.println("xt_bpf ingress program status: %s",
778 getProgramStatus(XT_BPF_INGRESS_PROG_PATH).c_str());
779 dw.println("xt_bpf egress program status: %s",
780 getProgramStatus(XT_BPF_EGRESS_PROG_PATH).c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700781 dw.println("xt_bpf bandwidth whitelist program status: %s",
782 getProgramStatus(XT_BPF_WHITELIST_PROG_PATH).c_str());
783 dw.println("xt_bpf bandwidth blacklist program status: %s",
784 getProgramStatus(XT_BPF_BLACKLIST_PROG_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700785
Erik Klineb31fd692018-06-06 20:50:11 +0900786 if (!verbose) {
787 return;
788 }
Chenbo Fengef297172018-03-26 10:53:33 -0700789
790 dw.blankline();
791 dw.println("BPF map content:");
792
Erik Klineb31fd692018-06-06 20:50:11 +0900793 ScopedIndent indentForMapContent(dw);
Chenbo Fengef297172018-03-26 10:53:33 -0700794
795 // Print CookieTagMap content.
796 dumpBpfMap("mCookieTagMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700797 const auto printCookieTagInfo = [&dw](const uint64_t& key, const UidTag& value,
798 const BpfMap<uint64_t, UidTag>&) {
799 dw.println("cookie=%" PRIu64 " tag=0x%x uid=%u", key, value.tag, value.uid);
800 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700801 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700802 Status res = mCookieTagMap.iterateWithValue(printCookieTagInfo);
803 if (!isOk(res)) {
804 dw.println("mCookieTagMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700805 }
806
807 // Print UidCounterSetMap Content
808 dumpBpfMap("mUidCounterSetMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700809 const auto printUidInfo = [&dw](const uint32_t& key, const uint8_t& value,
810 const BpfMap<uint32_t, uint8_t>&) {
811 dw.println("%u %u", key, value);
812 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700813 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700814 res = mUidCounterSetMap.iterateWithValue(printUidInfo);
815 if (!isOk(res)) {
816 dw.println("mUidCounterSetMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700817 }
818
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700819 // Print AppUidStatsMap content
820 std::string appUidStatsHeader = StringPrintf("uid rxBytes rxPackets txBytes txPackets");
821 dumpBpfMap("mAppUidStatsMap:", dw, appUidStatsHeader);
822 auto printAppUidStatsInfo = [&dw](const uint32_t& key, const StatsValue& value,
823 const BpfMap<uint32_t, StatsValue>&) {
824 dw.println("%u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, value.rxBytes,
825 value.rxPackets, value.txBytes, value.txPackets);
826 return netdutils::status::ok;
827 };
828 res = mAppUidStatsMap.iterateWithValue(printAppUidStatsInfo);
829 if (!res.ok()) {
830 dw.println("mAppUidStatsMap print end with error: %s", res.msg().c_str());
831 }
832
Chenbo Fengef297172018-03-26 10:53:33 -0700833 // Print uidStatsMap content
834 std::string statsHeader = StringPrintf("ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes"
835 " rxPackets txBytes txPackets");
Chenbo Fengf434e862018-06-27 14:08:39 -0700836 dumpBpfMap("mStatsMapA", dw, statsHeader);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700837 const auto printStatsInfo = [&dw, this](const StatsKey& key, const StatsValue& value,
838 const BpfMap<StatsKey, StatsValue>&) {
839 uint32_t ifIndex = key.ifaceIndex;
840 auto ifname = mIfaceIndexNameMap.readValue(ifIndex);
841 if (!isOk(ifname)) {
842 strlcpy(ifname.value().name, "unknown", sizeof(IfaceValue));
Chenbo Fengef297172018-03-26 10:53:33 -0700843 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700844 dw.println("%u %s 0x%x %u %u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, ifIndex,
845 ifname.value().name, key.tag, key.uid, key.counterSet, value.rxBytes,
846 value.rxPackets, value.txBytes, value.txPackets);
847 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700848 };
Chenbo Fengf434e862018-06-27 14:08:39 -0700849 res = mStatsMapA.iterateWithValue(printStatsInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700850 if (!isOk(res)) {
Chenbo Fengf434e862018-06-27 14:08:39 -0700851 dw.println("mStatsMapA print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700852 }
853
854 // Print TagStatsMap content.
Chenbo Fengf434e862018-06-27 14:08:39 -0700855 dumpBpfMap("mStatsMapB", dw, statsHeader);
856 res = mStatsMapB.iterateWithValue(printStatsInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700857 if (!isOk(res)) {
Chenbo Fengf434e862018-06-27 14:08:39 -0700858 dw.println("mStatsMapB print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700859 }
860
861 // Print ifaceIndexToNameMap content.
862 dumpBpfMap("mIfaceIndexNameMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700863 const auto printIfaceNameInfo = [&dw](const uint32_t& key, const IfaceValue& value,
864 const BpfMap<uint32_t, IfaceValue>&) {
865 const char* ifname = value.name;
866 dw.println("ifaceIndex=%u ifaceName=%s", key, ifname);
867 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700868 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700869 res = mIfaceIndexNameMap.iterateWithValue(printIfaceNameInfo);
870 if (!isOk(res)) {
871 dw.println("mIfaceIndexNameMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700872 }
873
874 // Print ifaceStatsMap content
875 std::string ifaceStatsHeader = StringPrintf("ifaceIndex ifaceName rxBytes rxPackets txBytes"
876 " txPackets");
877 dumpBpfMap("mIfaceStatsMap:", dw, ifaceStatsHeader);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700878 const auto printIfaceStatsInfo = [&dw, this](const uint32_t& key, const StatsValue& value,
879 const BpfMap<uint32_t, StatsValue>&) {
880 auto ifname = mIfaceIndexNameMap.readValue(key);
881 if (!isOk(ifname)) {
882 strlcpy(ifname.value().name, "unknown", sizeof(IfaceValue));
Chenbo Fengef297172018-03-26 10:53:33 -0700883 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700884 dw.println("%u %s %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, ifname.value().name,
885 value.rxBytes, value.rxPackets, value.txBytes, value.txPackets);
886 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700887 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700888 res = mIfaceStatsMap.iterateWithValue(printIfaceStatsInfo);
889 if (!isOk(res)) {
890 dw.println("mIfaceStatsMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700891 }
892
Chenbo Feng703798e2018-06-15 17:07:59 -0700893 dw.blankline();
Chenbo Fengef297172018-03-26 10:53:33 -0700894
Chenbo Fengf434e862018-06-27 14:08:39 -0700895 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Chenbo Feng703798e2018-06-15 17:07:59 -0700896 auto configuration = mConfigurationMap.readValue(key);
897 if (isOk(configuration)) {
Chenbo Fengf434e862018-06-27 14:08:39 -0700898 dw.println("current ownerMatch configuration: %d", configuration.value());
Chenbo Feng703798e2018-06-15 17:07:59 -0700899 } else {
Chenbo Fengf434e862018-06-27 14:08:39 -0700900 dw.println("mConfigurationMap read ownerMatch configure failed with error: %s",
901 configuration.status().msg().c_str());
902 }
903 key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
904 configuration = mConfigurationMap.readValue(key);
905 if (isOk(configuration)) {
906 dw.println("current statsMap configuration: %d", configuration.value());
907 } else {
908 dw.println("mConfigurationMap read stats map configure failed with error: %s",
909 configuration.status().msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700910 }
Chenbo Feng703798e2018-06-15 17:07:59 -0700911 dumpBpfMap("mUidOwnerMap", dw, "");
912 const auto printUidMatchInfo = [&dw](const uint32_t& key, const uint8_t& value,
913 const BpfMap<uint32_t, uint8_t>&) {
914 dw.println("%u %s", key, uidMatchTypeToString(value).c_str());
915 return netdutils::status::ok;
916 };
917 res = mUidOwnerMap.iterateWithValue(printUidMatchInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700918 if (!isOk(res)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700919 dw.println("mUidOwnerMap print end with error: %s", res.msg().c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700920 }
Chenbo Feng48eaed32018-12-26 17:40:21 -0800921 dumpBpfMap("mUidPermissionMap", dw, "");
922 const auto printUidPermissionInfo = [&dw](const uint32_t& key, const uint8_t& value,
923 const BpfMap<uint32_t, uint8_t>&) {
924 dw.println("%u %s", key, UidPermissionTypeToString(value).c_str());
925 return netdutils::status::ok;
926 };
927 res = mUidPermissionMap.iterateWithValue(printUidPermissionInfo);
928 if (!isOk(res)) {
929 dw.println("mUidPermissionMap print end with error: %s", res.msg().c_str());
930 }
931
932 dumpBpfMap("mPrivilegedUser", dw, "");
933 for (uid_t uid : mPrivilegedUser) {
934 dw.println("%u ALLOW_UPDATE_DEVICE_STATS", (uint32_t)uid);
935 }
Chenbo Fengef297172018-03-26 10:53:33 -0700936}
937
Chenbo Fengf2759682017-10-10 17:31:57 -0700938} // namespace net
939} // namespace android