blob: 677f32ca304825f7515aafea9fa532b896dad606 [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 Feng86c4aff2019-02-07 19:30:33 -080096 return ((uid == AID_ROOT) || mPrivilegedUser.find(uid) != mPrivilegedUser.end());
Chenbo Fengb4a4fa12019-01-09 17:20:45 -080097}
98
Chenbo Feng48eaed32018-12-26 17:40:21 -080099const std::string UidPermissionTypeToString(uint8_t permission) {
100 std::string permissionType;
101 FLAG_MSG_TRANS(permissionType, ALLOW_SOCK_CREATE, permission);
102 FLAG_MSG_TRANS(permissionType, ALLOW_UPDATE_DEVICE_STATS, permission);
103 if (permission) {
104 return StringPrintf("Unknown permission: %u", permission);
105 }
106 return permissionType;
107}
108
Chenbo Feng49586642018-08-30 18:01:53 -0700109StatusOr<std::unique_ptr<NetlinkListenerInterface>> TrafficController::makeSkDestroyListener() {
Chenbo Feng116d0552017-12-04 17:25:19 -0800110 const auto& sys = sSyscalls.get();
111 ASSIGN_OR_RETURN(auto event, sys.eventfd(0, EFD_CLOEXEC));
112 const int domain = AF_NETLINK;
113 const int type = SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK;
114 const int protocol = NETLINK_INET_DIAG;
115 ASSIGN_OR_RETURN(auto sock, sys.socket(domain, type, protocol));
116
Lorenzo Colitti436efdb2018-07-26 17:20:57 +0900117 // TODO: if too many sockets are closed too quickly, we can overflow the socket buffer, and
118 // some entries in mCookieTagMap will not be freed. In order to fix this we would need to
119 // periodically dump all sockets and remove the tag entries for sockets that have been closed.
120 // For now, set a large-enough buffer that we can close hundreds of sockets without getting
121 // ENOBUFS and leaking mCookieTagMap entries.
122 int rcvbuf = 512 * 1024;
123 auto ret = sys.setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf));
124 if (!ret.ok()) {
125 ALOGW("Failed to set SkDestroyListener buffer size to %d: %s", rcvbuf, ret.msg().c_str());
126 }
127
Chenbo Feng116d0552017-12-04 17:25:19 -0800128 sockaddr_nl addr = {
129 .nl_family = AF_NETLINK,
130 .nl_groups = 1 << (SKNLGRP_INET_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET_UDP_DESTROY - 1) |
131 1 << (SKNLGRP_INET6_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET6_UDP_DESTROY - 1)};
132 RETURN_IF_NOT_OK(sys.bind(sock, addr));
133
134 const sockaddr_nl kernel = {.nl_family = AF_NETLINK};
135 RETURN_IF_NOT_OK(sys.connect(sock, kernel));
136
137 std::unique_ptr<NetlinkListenerInterface> listener =
Chenbo Feng46296702018-08-23 12:20:22 -0700138 std::make_unique<NetlinkListener>(std::move(event), std::move(sock), "SkDestroyListen");
Chenbo Feng116d0552017-12-04 17:25:19 -0800139
140 return listener;
141}
142
Chenbo Feng89c12f12018-03-21 10:29:18 -0700143Status changeOwnerAndMode(const char* path, gid_t group, const char* debugName, bool netdOnly) {
144 int ret = chown(path, AID_ROOT, group);
145 if (ret != 0) return statusFromErrno(errno, StringPrintf("change %s group failed", debugName));
146
147 if (netdOnly) {
148 ret = chmod(path, S_IRWXU);
149 } else {
150 // Allow both netd and system server to obtain map fd from the path.
151 // chmod doesn't grant permission to all processes in that group to
152 // read/write the bpf map. They still need correct sepolicy to
153 // read/write the map.
Chenbo Fengf434e862018-06-27 14:08:39 -0700154 ret = chmod(path, S_IRWXU | S_IRGRP | S_IWGRP);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700155 }
156 if (ret != 0) return statusFromErrno(errno, StringPrintf("change %s mode failed", debugName));
157 return netdutils::status::ok;
158}
159
Chenbo Feng47dd0732018-12-11 12:23:24 -0800160TrafficController::TrafficController() : mBpfLevel(getBpfSupportLevel()) {}
Chenbo Feng89c12f12018-03-21 10:29:18 -0700161
Chenbo Feng89c12f12018-03-21 10:29:18 -0700162Status TrafficController::initMaps() {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900163 std::lock_guard ownerMapGuard(mOwnerMatchMutex);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700164 RETURN_IF_NOT_OK(
165 mCookieTagMap.getOrCreate(COOKIE_UID_MAP_SIZE, COOKIE_TAG_MAP_PATH, BPF_MAP_TYPE_HASH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700166
167 RETURN_IF_NOT_OK(changeOwnerAndMode(COOKIE_TAG_MAP_PATH, AID_NET_BW_ACCT, "CookieTagMap",
168 false));
169
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700170 RETURN_IF_NOT_OK(mUidCounterSetMap.getOrCreate(UID_COUNTERSET_MAP_SIZE, UID_COUNTERSET_MAP_PATH,
171 BPF_MAP_TYPE_HASH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700172 RETURN_IF_NOT_OK(changeOwnerAndMode(UID_COUNTERSET_MAP_PATH, AID_NET_BW_ACCT,
173 "UidCounterSetMap", false));
174
Chenbo Fengf434e862018-06-27 14:08:39 -0700175 RETURN_IF_NOT_OK(mAppUidStatsMap.getOrCreate(APP_STATS_MAP_SIZE, APP_UID_STATS_MAP_PATH,
176 BPF_MAP_TYPE_HASH));
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700177 RETURN_IF_NOT_OK(
178 changeOwnerAndMode(APP_UID_STATS_MAP_PATH, AID_NET_BW_STATS, "AppUidStatsMap", false));
179
Chenbo Fengf434e862018-06-27 14:08:39 -0700180 RETURN_IF_NOT_OK(mStatsMapA.getOrCreate(STATS_MAP_SIZE, STATS_MAP_A_PATH, BPF_MAP_TYPE_HASH));
181 RETURN_IF_NOT_OK(changeOwnerAndMode(STATS_MAP_A_PATH, AID_NET_BW_STATS, "StatsMapA", false));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700182
Chenbo Fengf434e862018-06-27 14:08:39 -0700183 RETURN_IF_NOT_OK(mStatsMapB.getOrCreate(STATS_MAP_SIZE, STATS_MAP_B_PATH, BPF_MAP_TYPE_HASH));
184 RETURN_IF_NOT_OK(changeOwnerAndMode(STATS_MAP_B_PATH, AID_NET_BW_STATS, "StatsMapB", false));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700185
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700186 RETURN_IF_NOT_OK(mIfaceIndexNameMap.getOrCreate(IFACE_INDEX_NAME_MAP_SIZE,
187 IFACE_INDEX_NAME_MAP_PATH, BPF_MAP_TYPE_HASH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700188 RETURN_IF_NOT_OK(changeOwnerAndMode(IFACE_INDEX_NAME_MAP_PATH, AID_NET_BW_STATS,
189 "IfaceIndexNameMap", false));
190
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700191 RETURN_IF_NOT_OK(
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700192 mIfaceStatsMap.getOrCreate(IFACE_STATS_MAP_SIZE, IFACE_STATS_MAP_PATH, BPF_MAP_TYPE_HASH));
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
Chenbo Feng703798e2018-06-15 17:07:59 -0700196 RETURN_IF_NOT_OK(mConfigurationMap.getOrCreate(CONFIGURATION_MAP_SIZE, CONFIGURATION_MAP_PATH,
197 BPF_MAP_TYPE_HASH));
Chenbo Fengf434e862018-06-27 14:08:39 -0700198 RETURN_IF_NOT_OK(changeOwnerAndMode(CONFIGURATION_MAP_PATH, AID_NET_BW_STATS,
199 "ConfigurationMap", false));
Chenbo Feng703798e2018-06-15 17:07:59 -0700200 RETURN_IF_NOT_OK(
Chenbo Fengf434e862018-06-27 14:08:39 -0700201 mConfigurationMap.writeValue(UID_RULES_CONFIGURATION_KEY, DEFAULT_CONFIG, BPF_ANY));
202 RETURN_IF_NOT_OK(mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, SELECT_MAP_A,
203 BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700204
205 RETURN_IF_NOT_OK(
206 mUidOwnerMap.getOrCreate(UID_OWNER_MAP_SIZE, UID_OWNER_MAP_PATH, BPF_MAP_TYPE_HASH));
207 RETURN_IF_NOT_OK(changeOwnerAndMode(UID_OWNER_MAP_PATH, AID_ROOT, "UidOwnerMap", true));
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900208 RETURN_IF_NOT_OK(mUidOwnerMap.clear());
Chenbo Feng48eaed32018-12-26 17:40:21 -0800209 RETURN_IF_NOT_OK(mUidPermissionMap.getOrCreate(UID_OWNER_MAP_SIZE, UID_PERMISSION_MAP_PATH,
210 BPF_MAP_TYPE_HASH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700211 return netdutils::status::ok;
212}
213
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800214static Status attachProgramToCgroup(const char* programPath, const int cgroupFd,
215 bpf_attach_type type) {
216 unique_fd cgroupProg(bpfFdGet(programPath, 0));
217 if (cgroupProg == -1) {
218 int ret = errno;
219 ALOGE("Failed to get program from %s: %s", programPath, strerror(ret));
220 return statusFromErrno(ret, "cgroup program get failed");
221 }
222 if (android::bpf::attachProgram(type, cgroupProg, cgroupFd)) {
223 int ret = errno;
224 ALOGE("Program from %s attach failed: %s", programPath, strerror(ret));
225 return statusFromErrno(ret, "program attach failed");
226 }
227 return netdutils::status::ok;
228}
229
230static Status initPrograms() {
Suren Baghdasaryane072a3c2019-01-16 14:36:07 -0800231 std::string cg2_path;
232
233 if (!CgroupGetControllerPath(CGROUPV2_CONTROLLER_NAME, &cg2_path)) {
234 int ret = errno;
235 ALOGE("Failed to find cgroup v2 root");
236 return statusFromErrno(ret, "Failed to find cgroup v2 root");
237 }
238
239 unique_fd cg_fd(open(cg2_path.c_str(), O_DIRECTORY | O_RDONLY | O_CLOEXEC));
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800240 if (cg_fd == -1) {
241 int ret = errno;
242 ALOGE("Failed to open the cgroup directory: %s", strerror(ret));
243 return statusFromErrno(ret, "Open the cgroup directory failed");
244 }
245 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_EGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_EGRESS));
246 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_INGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_INGRESS));
Chenbo Fenga51f4fa2019-01-15 15:03:32 -0800247
248 // For the devices that support cgroup socket filter, the socket filter
249 // should be loaded successfully by bpfloader. So we attach the filter to
250 // cgroup if the program is pinned properly.
251 // TODO: delete the if statement once all devices should support cgroup
252 // socket filter (ie. the minimum kernel version required is 4.14).
253 if (!access(CGROUP_SOCKET_PROG_PATH, F_OK)) {
254 RETURN_IF_NOT_OK(
255 attachProgramToCgroup(CGROUP_SOCKET_PROG_PATH, cg_fd, BPF_CGROUP_INET_SOCK_CREATE));
256 }
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800257 return netdutils::status::ok;
258}
259
Chenbo Feng89c12f12018-03-21 10:29:18 -0700260Status TrafficController::start() {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800261 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800262 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700263 }
264
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900265 /* When netd restarts from a crash without total system reboot, the program
Chenbo Fengf2759682017-10-10 17:31:57 -0700266 * is still attached to the cgroup, detach it so the program can be freed
267 * and we can load and attach new program into the target cgroup.
268 *
269 * TODO: Scrape existing socket when run-time restart and clean up the map
270 * if the socket no longer exist
271 */
272
Chenbo Feng89c12f12018-03-21 10:29:18 -0700273 RETURN_IF_NOT_OK(initMaps());
Chenbo Feng7e974052018-02-28 22:57:21 -0800274
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800275 RETURN_IF_NOT_OK(initPrograms());
276
Chenbo Feng7e974052018-02-28 22:57:21 -0800277 // Fetch the list of currently-existing interfaces. At this point NetlinkHandler is
278 // already running, so it will call addInterface() when any new interface appears.
279 std::map<std::string, uint32_t> ifacePairs;
280 ASSIGN_OR_RETURN(ifacePairs, InterfaceController::getIfaceList());
281 for (const auto& ifacePair:ifacePairs) {
282 addInterface(ifacePair.first.c_str(), ifacePair.second);
283 }
284
Chenbo Feng116d0552017-12-04 17:25:19 -0800285 auto result = makeSkDestroyListener();
286 if (!isOk(result)) {
287 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
288 } else {
289 mSkDestroyListener = std::move(result.value());
290 }
291 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
292 const auto rxHandler = [this](const nlmsghdr&, const Slice msg) {
293 inet_diag_msg diagmsg = {};
294 if (extract(msg, diagmsg) < sizeof(inet_diag_msg)) {
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900295 ALOGE("Unrecognized netlink message: %s", toString(msg).c_str());
Chenbo Feng116d0552017-12-04 17:25:19 -0800296 return;
297 }
298 uint64_t sock_cookie = static_cast<uint64_t>(diagmsg.id.idiag_cookie[0]) |
299 (static_cast<uint64_t>(diagmsg.id.idiag_cookie[1]) << 32);
300
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900301 Status s = mCookieTagMap.deleteValue(sock_cookie);
Chenbo Feng1d4c5db2018-10-18 15:50:46 -0700302 if (!isOk(s) && s.code() != ENOENT) {
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900303 ALOGE("Failed to delete cookie %" PRIx64 ": %s", sock_cookie, toString(s).c_str());
304 return;
305 }
Chenbo Feng116d0552017-12-04 17:25:19 -0800306 };
307 expectOk(mSkDestroyListener->subscribe(kSockDiagMsgType, rxHandler));
308
309 // In case multiple netlink message comes in as a stream, we need to handle the rxDone message
310 // properly.
311 const auto rxDoneHandler = [](const nlmsghdr&, const Slice msg) {
312 // Ignore NLMSG_DONE messages
313 inet_diag_msg diagmsg = {};
314 extract(msg, diagmsg);
315 };
316 expectOk(mSkDestroyListener->subscribe(kSockDiagDoneMsgType, rxDoneHandler));
317
Chenbo Feng05393d82018-01-09 15:18:43 -0800318 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700319}
320
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800321int TrafficController::tagSocket(int sockFd, uint32_t tag, uid_t uid, uid_t callingUid) {
322 if (uid != callingUid && !hasUpdateDeviceStatsPermission(callingUid)) {
323 return -EPERM;
324 }
325
Chenbo Feng47dd0732018-12-11 12:23:24 -0800326 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700327 if (legacy_tagSocket(sockFd, tag, uid)) return -errno;
328 return 0;
329 }
Chenbo Feng33cc1032017-10-23 15:16:37 -0700330
Chenbo Fengf2759682017-10-10 17:31:57 -0700331 uint64_t sock_cookie = getSocketCookie(sockFd);
Chenbo Fengef1cab32018-04-13 19:50:49 -0700332 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
Chenbo Fengf2759682017-10-10 17:31:57 -0700333 UidTag newKey = {.uid = (uint32_t)uid, .tag = tag};
334
335 // Update the tag information of a socket to the cookieUidMap. Use BPF_ANY
336 // flag so it will insert a new entry to the map if that value doesn't exist
337 // yet. And update the tag if there is already a tag stored. Since the eBPF
338 // program in kernel only read this map, and is protected by rcu read lock. It
339 // should be fine to cocurrently update the map while eBPF program is running.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700340 Status res = mCookieTagMap.writeValue(sock_cookie, newKey, BPF_ANY);
341 if (!isOk(res)) {
342 ALOGE("Failed to tag the socket: %s, fd: %d", strerror(res.code()),
343 mCookieTagMap.getMap().get());
Chenbo Fengf2759682017-10-10 17:31:57 -0700344 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700345 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700346}
347
348int TrafficController::untagSocket(int sockFd) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800349 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700350 if (legacy_untagSocket(sockFd)) return -errno;
351 return 0;
352 }
Chenbo Fengf2759682017-10-10 17:31:57 -0700353 uint64_t sock_cookie = getSocketCookie(sockFd);
354
Chenbo Fengef1cab32018-04-13 19:50:49 -0700355 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700356 Status res = mCookieTagMap.deleteValue(sock_cookie);
357 if (!isOk(res)) {
358 ALOGE("Failed to untag socket: %s\n", strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700359 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700360 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700361}
362
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800363int TrafficController::setCounterSet(int counterSetNum, uid_t uid, uid_t callingUid) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700364 if (counterSetNum < 0 || counterSetNum >= OVERFLOW_COUNTERSET) return -EINVAL;
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800365
366 if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
367
Chenbo Feng47dd0732018-12-11 12:23:24 -0800368 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700369 if (legacy_setCounterSet(counterSetNum, uid)) return -errno;
370 return 0;
371 }
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800372
373 // The default counter set for all uid is 0, so deleting the current counterset for that uid
374 // will automatically set it to 0.
Chenbo Fengf2759682017-10-10 17:31:57 -0700375 if (counterSetNum == 0) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700376 Status res = mUidCounterSetMap.deleteValue(uid);
377 if (isOk(res) || (!isOk(res) && res.code() == ENOENT)) {
Chenbo Fengf2759682017-10-10 17:31:57 -0700378 return 0;
379 } else {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700380 ALOGE("Failed to delete the counterSet: %s\n", strerror(res.code()));
381 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700382 }
383 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700384 uint8_t tmpCounterSetNum = (uint8_t)counterSetNum;
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800385 Status res = mUidCounterSetMap.writeValue(uid, tmpCounterSetNum, BPF_ANY);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700386 if (!isOk(res)) {
387 ALOGE("Failed to set the counterSet: %s, fd: %d", strerror(res.code()),
388 mUidCounterSetMap.getMap().get());
389 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700390 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700391 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700392}
393
Chenbo Fengf434e862018-06-27 14:08:39 -0700394// This method only get called by system_server when an app get uinstalled, it
395// is called inside removeUidsLocked() while holding mStatsLock. So it is safe
396// to iterate and modify the stats maps.
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800397int TrafficController::deleteTagData(uint32_t tag, uid_t uid, uid_t callingUid) {
398 if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
399
Chenbo Feng47dd0732018-12-11 12:23:24 -0800400 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700401 if (legacy_deleteTagData(tag, uid)) return -errno;
402 return 0;
403 }
Chenbo Feng33cc1032017-10-23 15:16:37 -0700404
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800405 // First we go through the cookieTagMap to delete the target uid tag combination. Or delete all
Chenbo Fengef1cab32018-04-13 19:50:49 -0700406 // the tags related to the uid if the tag is 0.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700407 const auto deleteMatchedCookieEntries = [uid, tag](const uint64_t& key, const UidTag& value,
408 BpfMap<uint64_t, UidTag>& map) {
409 if (value.uid == uid && (value.tag == tag || tag == 0)) {
410 Status res = map.deleteValue(key);
411 if (isOk(res) || (res.code() == ENOENT)) {
412 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700413 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700414 ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s\n", key, strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700415 }
Chenbo Fengef1cab32018-04-13 19:50:49 -0700416 // Move forward to next cookie in the map.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700417 return netdutils::status::ok;
Chenbo Fengef1cab32018-04-13 19:50:49 -0700418 };
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900419 mCookieTagMap.iterateWithValue(deleteMatchedCookieEntries).ignoreError();
Chenbo Fengf2759682017-10-10 17:31:57 -0700420 // 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 -0700421 // combination. Or all tag stats under that uid if the target tag is 0.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700422 const auto deleteMatchedUidTagEntries = [uid, tag](const StatsKey& key,
423 BpfMap<StatsKey, StatsValue>& map) {
424 if (key.uid == uid && (key.tag == tag || tag == 0)) {
425 Status res = map.deleteValue(key);
426 if (isOk(res) || (res.code() == ENOENT)) {
Chenbo Fengef1cab32018-04-13 19:50:49 -0700427 //Entry is deleted, use the current key to get a new nextKey;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700428 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700429 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700430 ALOGE("Failed to delete data(uid=%u, tag=%u): %s\n", key.uid, key.tag,
431 strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700432 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700433 return netdutils::status::ok;
Chenbo Fengef1cab32018-04-13 19:50:49 -0700434 };
Chenbo Fengf434e862018-06-27 14:08:39 -0700435 mStatsMapB.iterate(deleteMatchedUidTagEntries).ignoreError();
436 mStatsMapA.iterate(deleteMatchedUidTagEntries).ignoreError();
Chenbo Fengf2759682017-10-10 17:31:57 -0700437 // 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 -0800438 // need to delete the stats stored in uidStatsMap and counterSet map.
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800439 if (tag != 0) return 0;
440
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700441 Status res = mUidCounterSetMap.deleteValue(uid);
442 if (!isOk(res) && res.code() != ENOENT) {
443 ALOGE("Failed to delete counterSet data(uid=%u, tag=%u): %s\n", uid, tag,
444 strerror(res.code()));
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800445 }
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700446
447 auto deleteAppUidStatsEntry = [uid](const uint32_t& key, BpfMap<uint32_t, StatsValue>& map) {
448 if (key == uid) {
449 Status res = map.deleteValue(key);
450 if (isOk(res) || (res.code() == ENOENT)) {
451 return netdutils::status::ok;
452 }
453 ALOGE("Failed to delete data(uid=%u): %s", key, strerror(res.code()));
454 }
455 return netdutils::status::ok;
456 };
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900457 mAppUidStatsMap.iterate(deleteAppUidStatsEntry).ignoreError();
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700458 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700459}
460
Chenbo Feng7e974052018-02-28 22:57:21 -0800461int TrafficController::addInterface(const char* name, uint32_t ifaceIndex) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800462 if (mBpfLevel == BpfLevel::NONE) return 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800463
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700464 IfaceValue iface;
Chenbo Feng7e974052018-02-28 22:57:21 -0800465 if (ifaceIndex == 0) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700466 ALOGE("Unknown interface %s(%d)", name, ifaceIndex);
Chenbo Feng7e974052018-02-28 22:57:21 -0800467 return -1;
468 }
469
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700470 strlcpy(iface.name, name, sizeof(IfaceValue));
471 Status res = mIfaceIndexNameMap.writeValue(ifaceIndex, iface, BPF_ANY);
472 if (!isOk(res)) {
473 ALOGE("Failed to add iface %s(%d): %s", name, ifaceIndex, strerror(res.code()));
474 return -res.code();
Chenbo Feng7e974052018-02-28 22:57:21 -0800475 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700476 return 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800477}
478
Chenbo Feng703798e2018-06-15 17:07:59 -0700479Status TrafficController::updateOwnerMapEntry(UidOwnerMatchType match, uid_t uid, FirewallRule rule,
480 FirewallType type) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900481 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700482 if ((rule == ALLOW && type == WHITELIST) || (rule == DENY && type == BLACKLIST)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700483 RETURN_IF_NOT_OK(addMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700484 } else if ((rule == ALLOW && type == BLACKLIST) || (rule == DENY && type == WHITELIST)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700485 RETURN_IF_NOT_OK(removeMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700486 } else {
487 //Cannot happen.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700488 return statusFromErrno(-EINVAL, "");
Chenbo Feng89c12f12018-03-21 10:29:18 -0700489 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700490 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700491}
492
Chenbo Feng703798e2018-06-15 17:07:59 -0700493UidOwnerMatchType TrafficController::jumpOpToMatch(BandwidthController::IptJumpOp jumpHandling) {
Chenbo Feng95892f32018-06-07 14:52:02 -0700494 switch (jumpHandling) {
495 case BandwidthController::IptJumpReject:
Chenbo Feng703798e2018-06-15 17:07:59 -0700496 return PENALTY_BOX_MATCH;
Chenbo Feng95892f32018-06-07 14:52:02 -0700497 case BandwidthController::IptJumpReturn:
Chenbo Feng703798e2018-06-15 17:07:59 -0700498 return HAPPY_BOX_MATCH;
Chenbo Feng95892f32018-06-07 14:52:02 -0700499 case BandwidthController::IptJumpNoAdd:
500 return NO_MATCH;
501 }
502}
503
Chenbo Feng703798e2018-06-15 17:07:59 -0700504Status TrafficController::removeMatch(BpfMap<uint32_t, uint8_t>& map, uint32_t uid,
505 UidOwnerMatchType match) {
506 auto oldMatch = map.readValue(uid);
507 if (isOk(oldMatch)) {
508 uint8_t newMatch = oldMatch.value() & ~match;
509 if (newMatch == 0) {
510 RETURN_IF_NOT_OK(map.deleteValue(uid));
511 } else {
512 RETURN_IF_NOT_OK(map.writeValue(uid, newMatch, BPF_ANY));
513 }
514 } else {
515 return statusFromErrno(ENOENT, StringPrintf("uid: %u does not exist in map", uid));
516 }
517 return netdutils::status::ok;
518}
519
520Status TrafficController::addMatch(BpfMap<uint32_t, uint8_t>& map, uint32_t uid,
521 UidOwnerMatchType match) {
522 auto oldMatch = map.readValue(uid);
523 if (isOk(oldMatch)) {
524 uint8_t newMatch = oldMatch.value() | match;
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900525 RETURN_IF_NOT_OK(map.writeValue((uint32_t) uid, newMatch, BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700526 } else {
527 RETURN_IF_NOT_OK(map.writeValue(uid, match, BPF_ANY));
528 }
529 return netdutils::status::ok;
530}
531
532Status TrafficController::updateUidOwnerMap(const std::vector<std::string>& appStrUids,
533 BandwidthController::IptJumpOp jumpHandling,
534 BandwidthController::IptOp op) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900535 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Feng703798e2018-06-15 17:07:59 -0700536 UidOwnerMatchType match = jumpOpToMatch(jumpHandling);
537 if (match == NO_MATCH) {
538 return statusFromErrno(
539 EINVAL, StringPrintf("invalid IptJumpOp: %d, command: %d", jumpHandling, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700540 }
541 for (const auto& appStrUid : appStrUids) {
542 char* endPtr;
543 long uid = strtol(appStrUid.c_str(), &endPtr, 10);
544 if ((errno == ERANGE && (uid == LONG_MAX || uid == LONG_MIN)) ||
545 (endPtr == appStrUid.c_str()) || (*endPtr != '\0')) {
546 return statusFromErrno(errno, "invalid uid string:" + appStrUid);
547 }
548
Chenbo Feng95892f32018-06-07 14:52:02 -0700549 if (op == BandwidthController::IptOpDelete) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700550 RETURN_IF_NOT_OK(removeMatch(mUidOwnerMap, uid, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700551 } else if (op == BandwidthController::IptOpInsert) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700552 RETURN_IF_NOT_OK(addMatch(mUidOwnerMap, uid, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700553 } else {
554 // Cannot happen.
Chenbo Feng703798e2018-06-15 17:07:59 -0700555 return statusFromErrno(EINVAL, StringPrintf("invalid IptOp: %d, %d", op, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700556 }
557 }
558 return netdutils::status::ok;
559}
560
Chenbo Feng89c12f12018-03-21 10:29:18 -0700561int TrafficController::changeUidOwnerRule(ChildChain chain, uid_t uid, FirewallRule rule,
562 FirewallType type) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800563 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Feng89c12f12018-03-21 10:29:18 -0700564 ALOGE("bpf is not set up, should use iptables rule");
565 return -ENOSYS;
566 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700567 Status res;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700568 switch (chain) {
569 case DOZABLE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700570 res = updateOwnerMapEntry(DOZABLE_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700571 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700572 case STANDBY:
Chenbo Feng703798e2018-06-15 17:07:59 -0700573 res = updateOwnerMapEntry(STANDBY_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700574 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700575 case POWERSAVE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700576 res = updateOwnerMapEntry(POWERSAVE_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700577 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700578 case NONE:
579 default:
580 return -EINVAL;
581 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700582 if (!isOk(res)) {
583 ALOGE("change uid(%u) rule of %d failed: %s, rule: %d, type: %d", uid, chain,
584 res.msg().c_str(), rule, type);
585 return -res.code();
586 }
587 return 0;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700588}
589
Chenbo Feng703798e2018-06-15 17:07:59 -0700590Status TrafficController::replaceUidsInMap(const UidOwnerMatchType match,
591 const std::vector<int32_t>& uids) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900592 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700593 std::set<int32_t> uidSet(uids.begin(), uids.end());
594 std::vector<uint32_t> uidsToDelete;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700595 auto getUidsToDelete = [&uidsToDelete, &uidSet](const uint32_t& key,
596 const BpfMap<uint32_t, uint8_t>&) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700597 if (uidSet.find((int32_t) key) == uidSet.end()) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700598 uidsToDelete.push_back(key);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700599 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700600 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700601 };
Chenbo Feng703798e2018-06-15 17:07:59 -0700602 RETURN_IF_NOT_OK(mUidOwnerMap.iterate(getUidsToDelete));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700603
604 for(auto uid : uidsToDelete) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700605 RETURN_IF_NOT_OK(removeMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700606 }
607
608 for (auto uid : uids) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700609 RETURN_IF_NOT_OK(addMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700610 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700611 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700612}
613
614int TrafficController::replaceUidOwnerMap(const std::string& name, bool isWhitelist,
615 const std::vector<int32_t>& uids) {
Chenbo Feng89c12f12018-03-21 10:29:18 -0700616 FirewallRule rule;
617 FirewallType type;
618 if (isWhitelist) {
619 type = WHITELIST;
620 rule = ALLOW;
621 } else {
622 type = BLACKLIST;
623 rule = DENY;
624 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700625 Status res;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700626 if (!name.compare(FirewallController::LOCAL_DOZABLE)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700627 res = replaceUidsInMap(DOZABLE_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700628 } else if (!name.compare(FirewallController::LOCAL_STANDBY)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700629 res = replaceUidsInMap(STANDBY_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700630 } else if (!name.compare(FirewallController::LOCAL_POWERSAVE)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700631 res = replaceUidsInMap(POWERSAVE_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700632 } else {
633 ALOGE("unknown chain name: %s", name.c_str());
634 return -EINVAL;
635 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700636 if (!isOk(res)) {
637 ALOGE("Failed to clean up chain: %s: %s", name.c_str(), res.msg().c_str());
638 return -res.code();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700639 }
640 return 0;
641}
642
643int TrafficController::toggleUidOwnerMap(ChildChain chain, bool enable) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900644 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Fengf434e862018-06-27 14:08:39 -0700645 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Chenbo Feng703798e2018-06-15 17:07:59 -0700646 auto oldConfiguration = mConfigurationMap.readValue(key);
647 if (!isOk(oldConfiguration)) {
648 ALOGE("Cannot read the old configuration from map: %s",
649 oldConfiguration.status().msg().c_str());
650 return -oldConfiguration.status().code();
651 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700652 Status res;
Chenbo Feng703798e2018-06-15 17:07:59 -0700653 BpfConfig newConfiguration;
654 uint8_t match;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700655 switch (chain) {
656 case DOZABLE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700657 match = DOZABLE_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700658 break;
659 case STANDBY:
Chenbo Feng703798e2018-06-15 17:07:59 -0700660 match = STANDBY_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700661 break;
662 case POWERSAVE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700663 match = POWERSAVE_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700664 break;
665 default:
666 return -EINVAL;
667 }
Chenbo Feng703798e2018-06-15 17:07:59 -0700668 newConfiguration =
669 enable ? (oldConfiguration.value() | match) : (oldConfiguration.value() & (~match));
670 res = mConfigurationMap.writeValue(key, newConfiguration, BPF_EXIST);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700671 if (!isOk(res)) {
672 ALOGE("Failed to toggleUidOwnerMap(%d): %s", chain, res.msg().c_str());
Chenbo Feng89c12f12018-03-21 10:29:18 -0700673 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700674 return -res.code();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700675}
676
Chenbo Feng47dd0732018-12-11 12:23:24 -0800677BpfLevel TrafficController::getBpfLevel() {
678 return mBpfLevel;
Chenbo Feng07d43fe2017-12-21 14:38:51 -0800679}
680
Chenbo Feng48eaed32018-12-26 17:40:21 -0800681void TrafficController::setPermissionForUids(int permission, const std::vector<uid_t>& uids) {
682 bool internet = (permission & INetd::PERMISSION_INTERNET);
683 bool privileged = (permission & INetd::PERMISSION_UPDATE_DEVICE_STATS);
684
685 for (uid_t uid : uids) {
686 if (internet) {
687 Status ret = mUidPermissionMap.writeValue(uid, ALLOW_SOCK_CREATE, BPF_ANY);
688 if (!isOk(ret)) {
689 ALOGE("Failed to grant INTERNET permission to uid: %u: %s", uid,
690 strerror(ret.code()));
691 }
692 } else {
693 Status ret = mUidPermissionMap.deleteValue(uid);
694 if (!isOk(ret) && ret.code() != ENOENT) {
695 ALOGE("Failed to revoke permission INTERNET from uid: %u: %s", uid,
696 strerror(ret.code()));
697 }
698 }
699
700 if (privileged) {
701 mPrivilegedUser.insert(uid);
702 } else {
703 mPrivilegedUser.erase(uid);
704 }
705 }
706}
707
Chenbo Fengef297172018-03-26 10:53:33 -0700708std::string getProgramStatus(const char *path) {
709 int ret = access(path, R_OK);
710 if (ret == 0) {
711 return StringPrintf("OK");
712 }
713 if (ret != 0 && errno == ENOENT) {
714 return StringPrintf("program is missing at: %s", path);
715 }
716 return StringPrintf("check Program %s error: %s", path, strerror(errno));
717}
718
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700719std::string getMapStatus(const base::unique_fd& map_fd, const char* path) {
Chenbo Fengef297172018-03-26 10:53:33 -0700720 if (map_fd.get() < 0) {
721 return StringPrintf("map fd lost");
722 }
723 if (access(path, F_OK) != 0) {
724 return StringPrintf("map not pinned to location: %s", path);
725 }
726 return StringPrintf("OK");
727}
728
Bernie Innocentia5161a02019-01-30 22:40:53 +0900729// NOLINTNEXTLINE(google-runtime-references): grandfathered pass by non-const reference
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900730void dumpBpfMap(const std::string& mapName, DumpWriter& dw, const std::string& header) {
Chenbo Fengef297172018-03-26 10:53:33 -0700731 dw.blankline();
732 dw.println("%s:", mapName.c_str());
Erik Klineb31fd692018-06-06 20:50:11 +0900733 if (!header.empty()) {
734 dw.println(header);
Chenbo Fengef297172018-03-26 10:53:33 -0700735 }
736}
737
738const String16 TrafficController::DUMP_KEYWORD = String16("trafficcontroller");
739
740void TrafficController::dump(DumpWriter& dw, bool verbose) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900741 std::lock_guard ownerMapGuard(mOwnerMatchMutex);
Erik Klineb31fd692018-06-06 20:50:11 +0900742 ScopedIndent indentTop(dw);
Chenbo Fengef297172018-03-26 10:53:33 -0700743 dw.println("TrafficController");
744
Erik Klineb31fd692018-06-06 20:50:11 +0900745 ScopedIndent indentPreBpfModule(dw);
Chenbo Feng47dd0732018-12-11 12:23:24 -0800746 dw.println("BPF module status: %s", BpfLevelToString(mBpfLevel).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700747
Chenbo Feng47dd0732018-12-11 12:23:24 -0800748 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengef297172018-03-26 10:53:33 -0700749 return;
Erik Klineb31fd692018-06-06 20:50:11 +0900750 }
Chenbo Fengef297172018-03-26 10:53:33 -0700751
752 dw.blankline();
753 dw.println("mCookieTagMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700754 getMapStatus(mCookieTagMap.getMap(), COOKIE_TAG_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700755 dw.println("mUidCounterSetMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700756 getMapStatus(mUidCounterSetMap.getMap(), UID_COUNTERSET_MAP_PATH).c_str());
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700757 dw.println("mAppUidStatsMap status: %s",
758 getMapStatus(mAppUidStatsMap.getMap(), APP_UID_STATS_MAP_PATH).c_str());
Chenbo Fengf434e862018-06-27 14:08:39 -0700759 dw.println("mStatsMapA status: %s",
760 getMapStatus(mStatsMapA.getMap(), STATS_MAP_A_PATH).c_str());
761 dw.println("mStatsMapB status: %s",
762 getMapStatus(mStatsMapB.getMap(), STATS_MAP_B_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700763 dw.println("mIfaceIndexNameMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700764 getMapStatus(mIfaceIndexNameMap.getMap(), IFACE_INDEX_NAME_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700765 dw.println("mIfaceStatsMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700766 getMapStatus(mIfaceStatsMap.getMap(), IFACE_STATS_MAP_PATH).c_str());
Chenbo Feng703798e2018-06-15 17:07:59 -0700767 dw.println("mConfigurationMap status: %s",
768 getMapStatus(mConfigurationMap.getMap(), CONFIGURATION_MAP_PATH).c_str());
769 dw.println("mUidOwnerMap status: %s",
770 getMapStatus(mUidOwnerMap.getMap(), UID_OWNER_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700771
772 dw.blankline();
773 dw.println("Cgroup ingress program status: %s",
774 getProgramStatus(BPF_INGRESS_PROG_PATH).c_str());
775 dw.println("Cgroup egress program status: %s", getProgramStatus(BPF_EGRESS_PROG_PATH).c_str());
776 dw.println("xt_bpf ingress program status: %s",
777 getProgramStatus(XT_BPF_INGRESS_PROG_PATH).c_str());
778 dw.println("xt_bpf egress program status: %s",
779 getProgramStatus(XT_BPF_EGRESS_PROG_PATH).c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700780 dw.println("xt_bpf bandwidth whitelist program status: %s",
781 getProgramStatus(XT_BPF_WHITELIST_PROG_PATH).c_str());
782 dw.println("xt_bpf bandwidth blacklist program status: %s",
783 getProgramStatus(XT_BPF_BLACKLIST_PROG_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700784
Erik Klineb31fd692018-06-06 20:50:11 +0900785 if (!verbose) {
786 return;
787 }
Chenbo Fengef297172018-03-26 10:53:33 -0700788
789 dw.blankline();
790 dw.println("BPF map content:");
791
Erik Klineb31fd692018-06-06 20:50:11 +0900792 ScopedIndent indentForMapContent(dw);
Chenbo Fengef297172018-03-26 10:53:33 -0700793
794 // Print CookieTagMap content.
795 dumpBpfMap("mCookieTagMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700796 const auto printCookieTagInfo = [&dw](const uint64_t& key, const UidTag& value,
797 const BpfMap<uint64_t, UidTag>&) {
798 dw.println("cookie=%" PRIu64 " tag=0x%x uid=%u", key, value.tag, value.uid);
799 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700800 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700801 Status res = mCookieTagMap.iterateWithValue(printCookieTagInfo);
802 if (!isOk(res)) {
803 dw.println("mCookieTagMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700804 }
805
806 // Print UidCounterSetMap Content
807 dumpBpfMap("mUidCounterSetMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700808 const auto printUidInfo = [&dw](const uint32_t& key, const uint8_t& value,
809 const BpfMap<uint32_t, uint8_t>&) {
810 dw.println("%u %u", key, value);
811 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700812 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700813 res = mUidCounterSetMap.iterateWithValue(printUidInfo);
814 if (!isOk(res)) {
815 dw.println("mUidCounterSetMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700816 }
817
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700818 // Print AppUidStatsMap content
819 std::string appUidStatsHeader = StringPrintf("uid rxBytes rxPackets txBytes txPackets");
820 dumpBpfMap("mAppUidStatsMap:", dw, appUidStatsHeader);
821 auto printAppUidStatsInfo = [&dw](const uint32_t& key, const StatsValue& value,
822 const BpfMap<uint32_t, StatsValue>&) {
823 dw.println("%u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, value.rxBytes,
824 value.rxPackets, value.txBytes, value.txPackets);
825 return netdutils::status::ok;
826 };
827 res = mAppUidStatsMap.iterateWithValue(printAppUidStatsInfo);
828 if (!res.ok()) {
829 dw.println("mAppUidStatsMap print end with error: %s", res.msg().c_str());
830 }
831
Chenbo Fengef297172018-03-26 10:53:33 -0700832 // Print uidStatsMap content
833 std::string statsHeader = StringPrintf("ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes"
834 " rxPackets txBytes txPackets");
Chenbo Fengf434e862018-06-27 14:08:39 -0700835 dumpBpfMap("mStatsMapA", dw, statsHeader);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700836 const auto printStatsInfo = [&dw, this](const StatsKey& key, const StatsValue& value,
837 const BpfMap<StatsKey, StatsValue>&) {
838 uint32_t ifIndex = key.ifaceIndex;
839 auto ifname = mIfaceIndexNameMap.readValue(ifIndex);
840 if (!isOk(ifname)) {
841 strlcpy(ifname.value().name, "unknown", sizeof(IfaceValue));
Chenbo Fengef297172018-03-26 10:53:33 -0700842 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700843 dw.println("%u %s 0x%x %u %u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, ifIndex,
844 ifname.value().name, key.tag, key.uid, key.counterSet, value.rxBytes,
845 value.rxPackets, value.txBytes, value.txPackets);
846 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700847 };
Chenbo Fengf434e862018-06-27 14:08:39 -0700848 res = mStatsMapA.iterateWithValue(printStatsInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700849 if (!isOk(res)) {
Chenbo Fengf434e862018-06-27 14:08:39 -0700850 dw.println("mStatsMapA print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700851 }
852
853 // Print TagStatsMap content.
Chenbo Fengf434e862018-06-27 14:08:39 -0700854 dumpBpfMap("mStatsMapB", dw, statsHeader);
855 res = mStatsMapB.iterateWithValue(printStatsInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700856 if (!isOk(res)) {
Chenbo Fengf434e862018-06-27 14:08:39 -0700857 dw.println("mStatsMapB print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700858 }
859
860 // Print ifaceIndexToNameMap content.
861 dumpBpfMap("mIfaceIndexNameMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700862 const auto printIfaceNameInfo = [&dw](const uint32_t& key, const IfaceValue& value,
863 const BpfMap<uint32_t, IfaceValue>&) {
864 const char* ifname = value.name;
865 dw.println("ifaceIndex=%u ifaceName=%s", key, ifname);
866 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700867 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700868 res = mIfaceIndexNameMap.iterateWithValue(printIfaceNameInfo);
869 if (!isOk(res)) {
870 dw.println("mIfaceIndexNameMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700871 }
872
873 // Print ifaceStatsMap content
874 std::string ifaceStatsHeader = StringPrintf("ifaceIndex ifaceName rxBytes rxPackets txBytes"
875 " txPackets");
876 dumpBpfMap("mIfaceStatsMap:", dw, ifaceStatsHeader);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700877 const auto printIfaceStatsInfo = [&dw, this](const uint32_t& key, const StatsValue& value,
878 const BpfMap<uint32_t, StatsValue>&) {
879 auto ifname = mIfaceIndexNameMap.readValue(key);
880 if (!isOk(ifname)) {
881 strlcpy(ifname.value().name, "unknown", sizeof(IfaceValue));
Chenbo Fengef297172018-03-26 10:53:33 -0700882 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700883 dw.println("%u %s %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, ifname.value().name,
884 value.rxBytes, value.rxPackets, value.txBytes, value.txPackets);
885 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700886 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700887 res = mIfaceStatsMap.iterateWithValue(printIfaceStatsInfo);
888 if (!isOk(res)) {
889 dw.println("mIfaceStatsMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700890 }
891
Chenbo Feng703798e2018-06-15 17:07:59 -0700892 dw.blankline();
Chenbo Fengef297172018-03-26 10:53:33 -0700893
Chenbo Fengf434e862018-06-27 14:08:39 -0700894 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Chenbo Feng703798e2018-06-15 17:07:59 -0700895 auto configuration = mConfigurationMap.readValue(key);
896 if (isOk(configuration)) {
Chenbo Fengf434e862018-06-27 14:08:39 -0700897 dw.println("current ownerMatch configuration: %d", configuration.value());
Chenbo Feng703798e2018-06-15 17:07:59 -0700898 } else {
Chenbo Fengf434e862018-06-27 14:08:39 -0700899 dw.println("mConfigurationMap read ownerMatch configure failed with error: %s",
900 configuration.status().msg().c_str());
901 }
902 key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
903 configuration = mConfigurationMap.readValue(key);
904 if (isOk(configuration)) {
905 dw.println("current statsMap configuration: %d", configuration.value());
906 } else {
907 dw.println("mConfigurationMap read stats map configure failed with error: %s",
908 configuration.status().msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700909 }
Chenbo Feng703798e2018-06-15 17:07:59 -0700910 dumpBpfMap("mUidOwnerMap", dw, "");
911 const auto printUidMatchInfo = [&dw](const uint32_t& key, const uint8_t& value,
912 const BpfMap<uint32_t, uint8_t>&) {
913 dw.println("%u %s", key, uidMatchTypeToString(value).c_str());
914 return netdutils::status::ok;
915 };
916 res = mUidOwnerMap.iterateWithValue(printUidMatchInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700917 if (!isOk(res)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700918 dw.println("mUidOwnerMap print end with error: %s", res.msg().c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700919 }
Chenbo Feng48eaed32018-12-26 17:40:21 -0800920 dumpBpfMap("mUidPermissionMap", dw, "");
921 const auto printUidPermissionInfo = [&dw](const uint32_t& key, const uint8_t& value,
922 const BpfMap<uint32_t, uint8_t>&) {
923 dw.println("%u %s", key, UidPermissionTypeToString(value).c_str());
924 return netdutils::status::ok;
925 };
926 res = mUidPermissionMap.iterateWithValue(printUidPermissionInfo);
927 if (!isOk(res)) {
928 dw.println("mUidPermissionMap print end with error: %s", res.msg().c_str());
929 }
930
931 dumpBpfMap("mPrivilegedUser", dw, "");
932 for (uid_t uid : mPrivilegedUser) {
933 dw.println("%u ALLOW_UPDATE_DEVICE_STATS", (uint32_t)uid);
934 }
Chenbo Fengef297172018-03-26 10:53:33 -0700935}
936
Chenbo Fengf2759682017-10-10 17:31:57 -0700937} // namespace net
938} // namespace android