blob: 7012dc3a42796de8ec3c8fd8b1d9030b18072b3e [file] [log] [blame]
Chenbo Fengf2759682017-10-10 17:31:57 -07001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Chenbo Fengc10a8a42017-12-15 13:56:33 -080017#define LOG_TAG "TrafficController"
Chenbo Feng33cc1032017-10-23 15:16:37 -070018#include <inttypes.h>
Chenbo Fengf2759682017-10-10 17:31:57 -070019#include <linux/bpf.h>
20#include <linux/if_ether.h>
21#include <linux/in.h>
22#include <linux/inet_diag.h>
Chenbo Feng116d0552017-12-04 17:25:19 -080023#include <linux/netlink.h>
24#include <linux/sock_diag.h>
Chenbo Fengf2759682017-10-10 17:31:57 -070025#include <linux/unistd.h>
Chenbo Fengc10a8a42017-12-15 13:56:33 -080026#include <net/if.h>
Chenbo Fengf2759682017-10-10 17:31:57 -070027#include <stdlib.h>
28#include <string.h>
29#include <sys/socket.h>
Chenbo Fengc10a8a42017-12-15 13:56:33 -080030#include <sys/stat.h>
Chenbo Feng05393d82018-01-09 15:18:43 -080031#include <sys/types.h>
Chenbo Feng33cc1032017-10-23 15:16:37 -070032#include <sys/utsname.h>
Chenbo Feng05393d82018-01-09 15:18:43 -080033#include <sys/wait.h>
Chenbo Feng89c12f12018-03-21 10:29:18 -070034#include <mutex>
Chenbo Fengc10a8a42017-12-15 13:56:33 -080035#include <unordered_set>
36#include <vector>
37
38#include <android-base/stringprintf.h>
Chenbo Fengef297172018-03-26 10:53:33 -070039#include <android-base/strings.h>
Chenbo Fengc10a8a42017-12-15 13:56:33 -080040#include <android-base/unique_fd.h>
Chenbo Feng05393d82018-01-09 15:18:43 -080041#include <logwrap/logwrap.h>
Chenbo Fengc10a8a42017-12-15 13:56:33 -080042#include <netdutils/StatusOr.h>
Chenbo Fengf2759682017-10-10 17:31:57 -070043
Chenbo Feng116d0552017-12-04 17:25:19 -080044#include <netdutils/Misc.h>
45#include <netdutils/Syscalls.h>
Suren Baghdasaryane072a3c2019-01-16 14:36:07 -080046#include <processgroup/processgroup.h>
Chenbo Fengf2759682017-10-10 17:31:57 -070047#include "TrafficController.h"
Chenbo Feng4f6c2372018-04-26 10:37:55 -070048#include "bpf/BpfMap.h"
Chenbo Feng116d0552017-12-04 17:25:19 -080049
Chenbo Feng89c12f12018-03-21 10:29:18 -070050#include "FirewallController.h"
Chenbo Feng7e974052018-02-28 22:57:21 -080051#include "InterfaceController.h"
Chenbo Feng116d0552017-12-04 17:25:19 -080052#include "NetlinkListener.h"
Luke Huangb257d612019-03-14 21:19:13 +080053#include "netdutils/DumpWriter.h"
Chenbo Feng33cc1032017-10-23 15:16:37 -070054#include "qtaguid/qtaguid.h"
Chenbo Fengf2759682017-10-10 17:31:57 -070055
Bernie Innocenti7e25ec02018-07-02 19:32:17 +090056using namespace android::bpf; // NOLINT(google-build-using-namespace): grandfathered
Chenbo Fengf2759682017-10-10 17:31:57 -070057
58namespace android {
59namespace net {
60
Chenbo Fengc10a8a42017-12-15 13:56:33 -080061using base::StringPrintf;
62using base::unique_fd;
Luke Huangb257d612019-03-14 21:19:13 +080063using netdutils::DumpWriter;
Chenbo Feng116d0552017-12-04 17:25:19 -080064using netdutils::extract;
Luke Huangb257d612019-03-14 21:19:13 +080065using netdutils::ScopedIndent;
Chenbo Feng116d0552017-12-04 17:25:19 -080066using netdutils::Slice;
67using netdutils::sSyscalls;
Chenbo Fengc10a8a42017-12-15 13:56:33 -080068using netdutils::Status;
69using netdutils::statusFromErrno;
70using netdutils::StatusOr;
Chenbo Feng116d0552017-12-04 17:25:19 -080071using netdutils::status::ok;
Chenbo Fengc10a8a42017-12-15 13:56:33 -080072
Chenbo Feng116d0552017-12-04 17:25:19 -080073constexpr int kSockDiagMsgType = SOCK_DIAG_BY_FAMILY;
74constexpr int kSockDiagDoneMsgType = NLMSG_DONE;
75
Chenbo Fengbf660aa2019-02-26 16:12:27 -080076static_assert(BPF_PERMISSION_INTERNET == INetd::PERMISSION_INTERNET,
77 "Mismatch between BPF and AIDL permissions: PERMISSION_INTERNET");
78static_assert(BPF_PERMISSION_UPDATE_DEVICE_STATS == INetd::PERMISSION_UPDATE_DEVICE_STATS,
79 "Mismatch between BPF and AIDL permissions: PERMISSION_UPDATE_DEVICE_STATS");
80
Chenbo Feng48eaed32018-12-26 17:40:21 -080081#define FLAG_MSG_TRANS(result, flag, value) \
82 do { \
83 if (value & flag) { \
84 result.append(StringPrintf(" %s", #flag)); \
85 value &= ~flag; \
86 } \
Chenbo Feng703798e2018-06-15 17:07:59 -070087 } while (0)
88
89const std::string uidMatchTypeToString(uint8_t match) {
90 std::string matchType;
Chenbo Feng48eaed32018-12-26 17:40:21 -080091 FLAG_MSG_TRANS(matchType, HAPPY_BOX_MATCH, match);
92 FLAG_MSG_TRANS(matchType, PENALTY_BOX_MATCH, match);
93 FLAG_MSG_TRANS(matchType, DOZABLE_MATCH, match);
94 FLAG_MSG_TRANS(matchType, STANDBY_MATCH, match);
95 FLAG_MSG_TRANS(matchType, POWERSAVE_MATCH, match);
Chenbo Feng703798e2018-06-15 17:07:59 -070096 if (match) {
97 return StringPrintf("Unknown match: %u", match);
98 }
99 return matchType;
100}
101
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800102bool TrafficController::hasUpdateDeviceStatsPermission(uid_t uid) {
Chenbo Feng3969c262019-03-19 14:53:57 -0700103 // This implementation is the same logic as method ActivityManager#checkComponentPermission.
104 // It implies that the calling uid can never be the same as PER_USER_RANGE.
105 uint32_t appId = uid % PER_USER_RANGE;
106 return ((appId == AID_ROOT) || (appId == AID_SYSTEM) ||
107 mPrivilegedUser.find(appId) != mPrivilegedUser.end());
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800108}
109
Chenbo Feng48eaed32018-12-26 17:40:21 -0800110const std::string UidPermissionTypeToString(uint8_t permission) {
Chenbo Fengbf660aa2019-02-26 16:12:27 -0800111 if (permission == INetd::NO_PERMISSIONS) {
112 return "NO_PERMISSIONS";
113 }
Chenbo Feng527908a2019-04-02 20:14:11 -0700114 if (permission == INetd::PERMISSION_UNINSTALLED) {
115 // This should never appear in the map, complain loudly if it does.
116 return "PERMISSION_UNINSTALLED error!";
117 }
Chenbo Feng48eaed32018-12-26 17:40:21 -0800118 std::string permissionType;
Chenbo Fengbf660aa2019-02-26 16:12:27 -0800119 FLAG_MSG_TRANS(permissionType, BPF_PERMISSION_INTERNET, permission);
120 FLAG_MSG_TRANS(permissionType, BPF_PERMISSION_UPDATE_DEVICE_STATS, permission);
Chenbo Feng48eaed32018-12-26 17:40:21 -0800121 if (permission) {
122 return StringPrintf("Unknown permission: %u", permission);
123 }
124 return permissionType;
125}
126
Chenbo Feng49586642018-08-30 18:01:53 -0700127StatusOr<std::unique_ptr<NetlinkListenerInterface>> TrafficController::makeSkDestroyListener() {
Chenbo Feng116d0552017-12-04 17:25:19 -0800128 const auto& sys = sSyscalls.get();
129 ASSIGN_OR_RETURN(auto event, sys.eventfd(0, EFD_CLOEXEC));
130 const int domain = AF_NETLINK;
131 const int type = SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK;
132 const int protocol = NETLINK_INET_DIAG;
133 ASSIGN_OR_RETURN(auto sock, sys.socket(domain, type, protocol));
134
Lorenzo Colitti436efdb2018-07-26 17:20:57 +0900135 // TODO: if too many sockets are closed too quickly, we can overflow the socket buffer, and
136 // some entries in mCookieTagMap will not be freed. In order to fix this we would need to
137 // periodically dump all sockets and remove the tag entries for sockets that have been closed.
138 // For now, set a large-enough buffer that we can close hundreds of sockets without getting
139 // ENOBUFS and leaking mCookieTagMap entries.
140 int rcvbuf = 512 * 1024;
141 auto ret = sys.setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf));
142 if (!ret.ok()) {
143 ALOGW("Failed to set SkDestroyListener buffer size to %d: %s", rcvbuf, ret.msg().c_str());
144 }
145
Chenbo Feng116d0552017-12-04 17:25:19 -0800146 sockaddr_nl addr = {
147 .nl_family = AF_NETLINK,
148 .nl_groups = 1 << (SKNLGRP_INET_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET_UDP_DESTROY - 1) |
149 1 << (SKNLGRP_INET6_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET6_UDP_DESTROY - 1)};
150 RETURN_IF_NOT_OK(sys.bind(sock, addr));
151
152 const sockaddr_nl kernel = {.nl_family = AF_NETLINK};
153 RETURN_IF_NOT_OK(sys.connect(sock, kernel));
154
155 std::unique_ptr<NetlinkListenerInterface> listener =
Chenbo Feng46296702018-08-23 12:20:22 -0700156 std::make_unique<NetlinkListener>(std::move(event), std::move(sock), "SkDestroyListen");
Chenbo Feng116d0552017-12-04 17:25:19 -0800157
158 return listener;
159}
160
Chenbo Feng89c12f12018-03-21 10:29:18 -0700161Status changeOwnerAndMode(const char* path, gid_t group, const char* debugName, bool netdOnly) {
162 int ret = chown(path, AID_ROOT, group);
163 if (ret != 0) return statusFromErrno(errno, StringPrintf("change %s group failed", debugName));
164
165 if (netdOnly) {
166 ret = chmod(path, S_IRWXU);
167 } else {
168 // Allow both netd and system server to obtain map fd from the path.
169 // chmod doesn't grant permission to all processes in that group to
170 // read/write the bpf map. They still need correct sepolicy to
171 // read/write the map.
Chenbo Fengf434e862018-06-27 14:08:39 -0700172 ret = chmod(path, S_IRWXU | S_IRGRP | S_IWGRP);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700173 }
174 if (ret != 0) return statusFromErrno(errno, StringPrintf("change %s mode failed", debugName));
175 return netdutils::status::ok;
176}
177
Chenbo Feng47dd0732018-12-11 12:23:24 -0800178TrafficController::TrafficController() : mBpfLevel(getBpfSupportLevel()) {}
Chenbo Feng89c12f12018-03-21 10:29:18 -0700179
Chenbo Feng89c12f12018-03-21 10:29:18 -0700180Status TrafficController::initMaps() {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900181 std::lock_guard ownerMapGuard(mOwnerMatchMutex);
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700182 RETURN_IF_NOT_OK(mCookieTagMap.init(COOKIE_TAG_MAP_PATH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700183 RETURN_IF_NOT_OK(changeOwnerAndMode(COOKIE_TAG_MAP_PATH, AID_NET_BW_ACCT, "CookieTagMap",
184 false));
185
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700186 RETURN_IF_NOT_OK(mUidCounterSetMap.init(UID_COUNTERSET_MAP_PATH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700187 RETURN_IF_NOT_OK(changeOwnerAndMode(UID_COUNTERSET_MAP_PATH, AID_NET_BW_ACCT,
188 "UidCounterSetMap", false));
189
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700190 RETURN_IF_NOT_OK(mAppUidStatsMap.init(APP_UID_STATS_MAP_PATH));
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700191 RETURN_IF_NOT_OK(
192 changeOwnerAndMode(APP_UID_STATS_MAP_PATH, AID_NET_BW_STATS, "AppUidStatsMap", false));
193
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700194 RETURN_IF_NOT_OK(mStatsMapA.init(STATS_MAP_A_PATH));
Chenbo Fengf434e862018-06-27 14:08:39 -0700195 RETURN_IF_NOT_OK(changeOwnerAndMode(STATS_MAP_A_PATH, AID_NET_BW_STATS, "StatsMapA", false));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700196
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700197 RETURN_IF_NOT_OK(mStatsMapB.init(STATS_MAP_B_PATH));
Chenbo Fengf434e862018-06-27 14:08:39 -0700198 RETURN_IF_NOT_OK(changeOwnerAndMode(STATS_MAP_B_PATH, AID_NET_BW_STATS, "StatsMapB", false));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700199
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700200 RETURN_IF_NOT_OK(mIfaceIndexNameMap.init(IFACE_INDEX_NAME_MAP_PATH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700201 RETURN_IF_NOT_OK(changeOwnerAndMode(IFACE_INDEX_NAME_MAP_PATH, AID_NET_BW_STATS,
202 "IfaceIndexNameMap", false));
203
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700204 RETURN_IF_NOT_OK(mIfaceStatsMap.init(IFACE_STATS_MAP_PATH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700205 RETURN_IF_NOT_OK(changeOwnerAndMode(IFACE_STATS_MAP_PATH, AID_NET_BW_STATS, "IfaceStatsMap",
206 false));
Chenbo Feng95892f32018-06-07 14:52:02 -0700207
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700208 RETURN_IF_NOT_OK(mConfigurationMap.init(CONFIGURATION_MAP_PATH));
Chenbo Fengf434e862018-06-27 14:08:39 -0700209 RETURN_IF_NOT_OK(changeOwnerAndMode(CONFIGURATION_MAP_PATH, AID_NET_BW_STATS,
210 "ConfigurationMap", false));
Chenbo Feng703798e2018-06-15 17:07:59 -0700211 RETURN_IF_NOT_OK(
Chenbo Fengf434e862018-06-27 14:08:39 -0700212 mConfigurationMap.writeValue(UID_RULES_CONFIGURATION_KEY, DEFAULT_CONFIG, BPF_ANY));
213 RETURN_IF_NOT_OK(mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, SELECT_MAP_A,
214 BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700215
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700216 RETURN_IF_NOT_OK(mUidOwnerMap.init(UID_OWNER_MAP_PATH));
Chenbo Feng703798e2018-06-15 17:07:59 -0700217 RETURN_IF_NOT_OK(changeOwnerAndMode(UID_OWNER_MAP_PATH, AID_ROOT, "UidOwnerMap", true));
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900218 RETURN_IF_NOT_OK(mUidOwnerMap.clear());
Maciej Żenczykowski02554372019-04-01 10:44:54 -0700219 RETURN_IF_NOT_OK(mUidPermissionMap.init(UID_PERMISSION_MAP_PATH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700220 return netdutils::status::ok;
221}
222
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800223static Status attachProgramToCgroup(const char* programPath, const int cgroupFd,
224 bpf_attach_type type) {
225 unique_fd cgroupProg(bpfFdGet(programPath, 0));
226 if (cgroupProg == -1) {
227 int ret = errno;
228 ALOGE("Failed to get program from %s: %s", programPath, strerror(ret));
229 return statusFromErrno(ret, "cgroup program get failed");
230 }
231 if (android::bpf::attachProgram(type, cgroupProg, cgroupFd)) {
232 int ret = errno;
233 ALOGE("Program from %s attach failed: %s", programPath, strerror(ret));
234 return statusFromErrno(ret, "program attach failed");
235 }
236 return netdutils::status::ok;
237}
238
239static Status initPrograms() {
Suren Baghdasaryane072a3c2019-01-16 14:36:07 -0800240 std::string cg2_path;
241
242 if (!CgroupGetControllerPath(CGROUPV2_CONTROLLER_NAME, &cg2_path)) {
243 int ret = errno;
244 ALOGE("Failed to find cgroup v2 root");
245 return statusFromErrno(ret, "Failed to find cgroup v2 root");
246 }
247
248 unique_fd cg_fd(open(cg2_path.c_str(), O_DIRECTORY | O_RDONLY | O_CLOEXEC));
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800249 if (cg_fd == -1) {
250 int ret = errno;
251 ALOGE("Failed to open the cgroup directory: %s", strerror(ret));
252 return statusFromErrno(ret, "Open the cgroup directory failed");
253 }
254 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_EGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_EGRESS));
255 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_INGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_INGRESS));
Chenbo Fenga51f4fa2019-01-15 15:03:32 -0800256
257 // For the devices that support cgroup socket filter, the socket filter
258 // should be loaded successfully by bpfloader. So we attach the filter to
259 // cgroup if the program is pinned properly.
260 // TODO: delete the if statement once all devices should support cgroup
261 // socket filter (ie. the minimum kernel version required is 4.14).
262 if (!access(CGROUP_SOCKET_PROG_PATH, F_OK)) {
263 RETURN_IF_NOT_OK(
264 attachProgramToCgroup(CGROUP_SOCKET_PROG_PATH, cg_fd, BPF_CGROUP_INET_SOCK_CREATE));
265 }
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800266 return netdutils::status::ok;
267}
268
Chenbo Feng89c12f12018-03-21 10:29:18 -0700269Status TrafficController::start() {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800270 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800271 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700272 }
273
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900274 /* When netd restarts from a crash without total system reboot, the program
Chenbo Fengf2759682017-10-10 17:31:57 -0700275 * is still attached to the cgroup, detach it so the program can be freed
276 * and we can load and attach new program into the target cgroup.
277 *
278 * TODO: Scrape existing socket when run-time restart and clean up the map
279 * if the socket no longer exist
280 */
281
Chenbo Feng89c12f12018-03-21 10:29:18 -0700282 RETURN_IF_NOT_OK(initMaps());
Chenbo Feng7e974052018-02-28 22:57:21 -0800283
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800284 RETURN_IF_NOT_OK(initPrograms());
285
Chenbo Feng7e974052018-02-28 22:57:21 -0800286 // Fetch the list of currently-existing interfaces. At this point NetlinkHandler is
287 // already running, so it will call addInterface() when any new interface appears.
288 std::map<std::string, uint32_t> ifacePairs;
289 ASSIGN_OR_RETURN(ifacePairs, InterfaceController::getIfaceList());
290 for (const auto& ifacePair:ifacePairs) {
291 addInterface(ifacePair.first.c_str(), ifacePair.second);
292 }
293
Chenbo Feng116d0552017-12-04 17:25:19 -0800294 auto result = makeSkDestroyListener();
295 if (!isOk(result)) {
296 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
297 } else {
298 mSkDestroyListener = std::move(result.value());
299 }
300 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
301 const auto rxHandler = [this](const nlmsghdr&, const Slice msg) {
302 inet_diag_msg diagmsg = {};
303 if (extract(msg, diagmsg) < sizeof(inet_diag_msg)) {
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900304 ALOGE("Unrecognized netlink message: %s", toString(msg).c_str());
Chenbo Feng116d0552017-12-04 17:25:19 -0800305 return;
306 }
307 uint64_t sock_cookie = static_cast<uint64_t>(diagmsg.id.idiag_cookie[0]) |
308 (static_cast<uint64_t>(diagmsg.id.idiag_cookie[1]) << 32);
309
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900310 Status s = mCookieTagMap.deleteValue(sock_cookie);
Chenbo Feng1d4c5db2018-10-18 15:50:46 -0700311 if (!isOk(s) && s.code() != ENOENT) {
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900312 ALOGE("Failed to delete cookie %" PRIx64 ": %s", sock_cookie, toString(s).c_str());
313 return;
314 }
Chenbo Feng116d0552017-12-04 17:25:19 -0800315 };
316 expectOk(mSkDestroyListener->subscribe(kSockDiagMsgType, rxHandler));
317
318 // In case multiple netlink message comes in as a stream, we need to handle the rxDone message
319 // properly.
320 const auto rxDoneHandler = [](const nlmsghdr&, const Slice msg) {
321 // Ignore NLMSG_DONE messages
322 inet_diag_msg diagmsg = {};
323 extract(msg, diagmsg);
324 };
325 expectOk(mSkDestroyListener->subscribe(kSockDiagDoneMsgType, rxDoneHandler));
326
Chenbo Feng05393d82018-01-09 15:18:43 -0800327 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700328}
329
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800330int TrafficController::tagSocket(int sockFd, uint32_t tag, uid_t uid, uid_t callingUid) {
331 if (uid != callingUid && !hasUpdateDeviceStatsPermission(callingUid)) {
332 return -EPERM;
333 }
334
Chenbo Feng47dd0732018-12-11 12:23:24 -0800335 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700336 if (legacy_tagSocket(sockFd, tag, uid)) return -errno;
337 return 0;
338 }
Chenbo Feng33cc1032017-10-23 15:16:37 -0700339
Chenbo Fengf2759682017-10-10 17:31:57 -0700340 uint64_t sock_cookie = getSocketCookie(sockFd);
Chenbo Fengef1cab32018-04-13 19:50:49 -0700341 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
Chenbo Fengf2759682017-10-10 17:31:57 -0700342 UidTag newKey = {.uid = (uint32_t)uid, .tag = tag};
343
344 // Update the tag information of a socket to the cookieUidMap. Use BPF_ANY
345 // flag so it will insert a new entry to the map if that value doesn't exist
346 // yet. And update the tag if there is already a tag stored. Since the eBPF
347 // program in kernel only read this map, and is protected by rcu read lock. It
348 // should be fine to cocurrently update the map while eBPF program is running.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700349 Status res = mCookieTagMap.writeValue(sock_cookie, newKey, BPF_ANY);
350 if (!isOk(res)) {
351 ALOGE("Failed to tag the socket: %s, fd: %d", strerror(res.code()),
352 mCookieTagMap.getMap().get());
Chenbo Fengf2759682017-10-10 17:31:57 -0700353 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700354 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700355}
356
357int TrafficController::untagSocket(int sockFd) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800358 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700359 if (legacy_untagSocket(sockFd)) return -errno;
360 return 0;
361 }
Chenbo Fengf2759682017-10-10 17:31:57 -0700362 uint64_t sock_cookie = getSocketCookie(sockFd);
363
Chenbo Fengef1cab32018-04-13 19:50:49 -0700364 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700365 Status res = mCookieTagMap.deleteValue(sock_cookie);
366 if (!isOk(res)) {
367 ALOGE("Failed to untag socket: %s\n", strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700368 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700369 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700370}
371
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800372int TrafficController::setCounterSet(int counterSetNum, uid_t uid, uid_t callingUid) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700373 if (counterSetNum < 0 || counterSetNum >= OVERFLOW_COUNTERSET) return -EINVAL;
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800374
375 if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
376
Chenbo Feng47dd0732018-12-11 12:23:24 -0800377 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700378 if (legacy_setCounterSet(counterSetNum, uid)) return -errno;
379 return 0;
380 }
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800381
382 // The default counter set for all uid is 0, so deleting the current counterset for that uid
383 // will automatically set it to 0.
Chenbo Fengf2759682017-10-10 17:31:57 -0700384 if (counterSetNum == 0) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700385 Status res = mUidCounterSetMap.deleteValue(uid);
386 if (isOk(res) || (!isOk(res) && res.code() == ENOENT)) {
Chenbo Fengf2759682017-10-10 17:31:57 -0700387 return 0;
388 } else {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700389 ALOGE("Failed to delete the counterSet: %s\n", strerror(res.code()));
390 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700391 }
392 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700393 uint8_t tmpCounterSetNum = (uint8_t)counterSetNum;
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800394 Status res = mUidCounterSetMap.writeValue(uid, tmpCounterSetNum, BPF_ANY);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700395 if (!isOk(res)) {
396 ALOGE("Failed to set the counterSet: %s, fd: %d", strerror(res.code()),
397 mUidCounterSetMap.getMap().get());
398 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700399 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700400 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700401}
402
Chenbo Fengf434e862018-06-27 14:08:39 -0700403// This method only get called by system_server when an app get uinstalled, it
404// is called inside removeUidsLocked() while holding mStatsLock. So it is safe
405// to iterate and modify the stats maps.
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800406int TrafficController::deleteTagData(uint32_t tag, uid_t uid, uid_t callingUid) {
407 if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
408
Chenbo Feng47dd0732018-12-11 12:23:24 -0800409 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700410 if (legacy_deleteTagData(tag, uid)) return -errno;
411 return 0;
412 }
Chenbo Feng33cc1032017-10-23 15:16:37 -0700413
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800414 // First we go through the cookieTagMap to delete the target uid tag combination. Or delete all
Chenbo Fengef1cab32018-04-13 19:50:49 -0700415 // the tags related to the uid if the tag is 0.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700416 const auto deleteMatchedCookieEntries = [uid, tag](const uint64_t& key, const UidTag& value,
417 BpfMap<uint64_t, UidTag>& map) {
418 if (value.uid == uid && (value.tag == tag || tag == 0)) {
419 Status res = map.deleteValue(key);
420 if (isOk(res) || (res.code() == ENOENT)) {
421 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700422 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700423 ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s\n", key, strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700424 }
Chenbo Fengef1cab32018-04-13 19:50:49 -0700425 // Move forward to next cookie in the map.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700426 return netdutils::status::ok;
Chenbo Fengef1cab32018-04-13 19:50:49 -0700427 };
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900428 mCookieTagMap.iterateWithValue(deleteMatchedCookieEntries).ignoreError();
Chenbo Fengf2759682017-10-10 17:31:57 -0700429 // 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 -0700430 // combination. Or all tag stats under that uid if the target tag is 0.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700431 const auto deleteMatchedUidTagEntries = [uid, tag](const StatsKey& key,
432 BpfMap<StatsKey, StatsValue>& map) {
433 if (key.uid == uid && (key.tag == tag || tag == 0)) {
434 Status res = map.deleteValue(key);
435 if (isOk(res) || (res.code() == ENOENT)) {
Chenbo Fengef1cab32018-04-13 19:50:49 -0700436 //Entry is deleted, use the current key to get a new nextKey;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700437 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700438 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700439 ALOGE("Failed to delete data(uid=%u, tag=%u): %s\n", key.uid, key.tag,
440 strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700441 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700442 return netdutils::status::ok;
Chenbo Fengef1cab32018-04-13 19:50:49 -0700443 };
Chenbo Fengf434e862018-06-27 14:08:39 -0700444 mStatsMapB.iterate(deleteMatchedUidTagEntries).ignoreError();
445 mStatsMapA.iterate(deleteMatchedUidTagEntries).ignoreError();
Chenbo Fengf2759682017-10-10 17:31:57 -0700446 // 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 -0800447 // need to delete the stats stored in uidStatsMap and counterSet map.
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800448 if (tag != 0) return 0;
449
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700450 Status res = mUidCounterSetMap.deleteValue(uid);
451 if (!isOk(res) && res.code() != ENOENT) {
452 ALOGE("Failed to delete counterSet data(uid=%u, tag=%u): %s\n", uid, tag,
453 strerror(res.code()));
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800454 }
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700455
456 auto deleteAppUidStatsEntry = [uid](const uint32_t& key, BpfMap<uint32_t, StatsValue>& map) {
457 if (key == uid) {
458 Status res = map.deleteValue(key);
459 if (isOk(res) || (res.code() == ENOENT)) {
460 return netdutils::status::ok;
461 }
462 ALOGE("Failed to delete data(uid=%u): %s", key, strerror(res.code()));
463 }
464 return netdutils::status::ok;
465 };
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900466 mAppUidStatsMap.iterate(deleteAppUidStatsEntry).ignoreError();
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700467 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700468}
469
Chenbo Feng7e974052018-02-28 22:57:21 -0800470int TrafficController::addInterface(const char* name, uint32_t ifaceIndex) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800471 if (mBpfLevel == BpfLevel::NONE) return 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800472
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700473 IfaceValue iface;
Chenbo Feng7e974052018-02-28 22:57:21 -0800474 if (ifaceIndex == 0) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700475 ALOGE("Unknown interface %s(%d)", name, ifaceIndex);
Chenbo Feng7e974052018-02-28 22:57:21 -0800476 return -1;
477 }
478
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700479 strlcpy(iface.name, name, sizeof(IfaceValue));
480 Status res = mIfaceIndexNameMap.writeValue(ifaceIndex, iface, BPF_ANY);
481 if (!isOk(res)) {
482 ALOGE("Failed to add iface %s(%d): %s", name, ifaceIndex, strerror(res.code()));
483 return -res.code();
Chenbo Feng7e974052018-02-28 22:57:21 -0800484 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700485 return 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800486}
487
Chenbo Feng703798e2018-06-15 17:07:59 -0700488Status TrafficController::updateOwnerMapEntry(UidOwnerMatchType match, uid_t uid, FirewallRule rule,
489 FirewallType type) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900490 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700491 if ((rule == ALLOW && type == WHITELIST) || (rule == DENY && type == BLACKLIST)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700492 RETURN_IF_NOT_OK(addMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700493 } else if ((rule == ALLOW && type == BLACKLIST) || (rule == DENY && type == WHITELIST)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700494 RETURN_IF_NOT_OK(removeMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700495 } else {
496 //Cannot happen.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700497 return statusFromErrno(-EINVAL, "");
Chenbo Feng89c12f12018-03-21 10:29:18 -0700498 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700499 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700500}
501
Chenbo Feng703798e2018-06-15 17:07:59 -0700502UidOwnerMatchType TrafficController::jumpOpToMatch(BandwidthController::IptJumpOp jumpHandling) {
Chenbo Feng95892f32018-06-07 14:52:02 -0700503 switch (jumpHandling) {
504 case BandwidthController::IptJumpReject:
Chenbo Feng703798e2018-06-15 17:07:59 -0700505 return PENALTY_BOX_MATCH;
Chenbo Feng95892f32018-06-07 14:52:02 -0700506 case BandwidthController::IptJumpReturn:
Chenbo Feng703798e2018-06-15 17:07:59 -0700507 return HAPPY_BOX_MATCH;
Chenbo Feng95892f32018-06-07 14:52:02 -0700508 case BandwidthController::IptJumpNoAdd:
509 return NO_MATCH;
510 }
511}
512
Chenbo Feng703798e2018-06-15 17:07:59 -0700513Status TrafficController::removeMatch(BpfMap<uint32_t, uint8_t>& map, uint32_t uid,
514 UidOwnerMatchType match) {
515 auto oldMatch = map.readValue(uid);
516 if (isOk(oldMatch)) {
517 uint8_t newMatch = oldMatch.value() & ~match;
518 if (newMatch == 0) {
519 RETURN_IF_NOT_OK(map.deleteValue(uid));
520 } else {
521 RETURN_IF_NOT_OK(map.writeValue(uid, newMatch, BPF_ANY));
522 }
523 } else {
524 return statusFromErrno(ENOENT, StringPrintf("uid: %u does not exist in map", uid));
525 }
526 return netdutils::status::ok;
527}
528
529Status TrafficController::addMatch(BpfMap<uint32_t, uint8_t>& map, uint32_t uid,
530 UidOwnerMatchType match) {
531 auto oldMatch = map.readValue(uid);
532 if (isOk(oldMatch)) {
533 uint8_t newMatch = oldMatch.value() | match;
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900534 RETURN_IF_NOT_OK(map.writeValue((uint32_t) uid, newMatch, BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700535 } else {
536 RETURN_IF_NOT_OK(map.writeValue(uid, match, BPF_ANY));
537 }
538 return netdutils::status::ok;
539}
540
541Status TrafficController::updateUidOwnerMap(const std::vector<std::string>& appStrUids,
542 BandwidthController::IptJumpOp jumpHandling,
543 BandwidthController::IptOp op) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900544 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Feng703798e2018-06-15 17:07:59 -0700545 UidOwnerMatchType match = jumpOpToMatch(jumpHandling);
546 if (match == NO_MATCH) {
547 return statusFromErrno(
548 EINVAL, StringPrintf("invalid IptJumpOp: %d, command: %d", jumpHandling, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700549 }
550 for (const auto& appStrUid : appStrUids) {
551 char* endPtr;
552 long uid = strtol(appStrUid.c_str(), &endPtr, 10);
553 if ((errno == ERANGE && (uid == LONG_MAX || uid == LONG_MIN)) ||
554 (endPtr == appStrUid.c_str()) || (*endPtr != '\0')) {
555 return statusFromErrno(errno, "invalid uid string:" + appStrUid);
556 }
557
Chenbo Feng95892f32018-06-07 14:52:02 -0700558 if (op == BandwidthController::IptOpDelete) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700559 RETURN_IF_NOT_OK(removeMatch(mUidOwnerMap, uid, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700560 } else if (op == BandwidthController::IptOpInsert) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700561 RETURN_IF_NOT_OK(addMatch(mUidOwnerMap, uid, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700562 } else {
563 // Cannot happen.
Chenbo Feng703798e2018-06-15 17:07:59 -0700564 return statusFromErrno(EINVAL, StringPrintf("invalid IptOp: %d, %d", op, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700565 }
566 }
567 return netdutils::status::ok;
568}
569
Chenbo Feng89c12f12018-03-21 10:29:18 -0700570int TrafficController::changeUidOwnerRule(ChildChain chain, uid_t uid, FirewallRule rule,
571 FirewallType type) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800572 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Feng89c12f12018-03-21 10:29:18 -0700573 ALOGE("bpf is not set up, should use iptables rule");
574 return -ENOSYS;
575 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700576 Status res;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700577 switch (chain) {
578 case DOZABLE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700579 res = updateOwnerMapEntry(DOZABLE_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700580 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700581 case STANDBY:
Chenbo Feng703798e2018-06-15 17:07:59 -0700582 res = updateOwnerMapEntry(STANDBY_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700583 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700584 case POWERSAVE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700585 res = updateOwnerMapEntry(POWERSAVE_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700586 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700587 case NONE:
588 default:
589 return -EINVAL;
590 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700591 if (!isOk(res)) {
592 ALOGE("change uid(%u) rule of %d failed: %s, rule: %d, type: %d", uid, chain,
593 res.msg().c_str(), rule, type);
594 return -res.code();
595 }
596 return 0;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700597}
598
Chenbo Feng703798e2018-06-15 17:07:59 -0700599Status TrafficController::replaceUidsInMap(const UidOwnerMatchType match,
600 const std::vector<int32_t>& uids) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900601 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700602 std::set<int32_t> uidSet(uids.begin(), uids.end());
603 std::vector<uint32_t> uidsToDelete;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700604 auto getUidsToDelete = [&uidsToDelete, &uidSet](const uint32_t& key,
605 const BpfMap<uint32_t, uint8_t>&) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700606 if (uidSet.find((int32_t) key) == uidSet.end()) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700607 uidsToDelete.push_back(key);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700608 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700609 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700610 };
Chenbo Feng703798e2018-06-15 17:07:59 -0700611 RETURN_IF_NOT_OK(mUidOwnerMap.iterate(getUidsToDelete));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700612
613 for(auto uid : uidsToDelete) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700614 RETURN_IF_NOT_OK(removeMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700615 }
616
617 for (auto uid : uids) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700618 RETURN_IF_NOT_OK(addMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700619 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700620 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700621}
622
623int TrafficController::replaceUidOwnerMap(const std::string& name, bool isWhitelist,
624 const std::vector<int32_t>& uids) {
Chenbo Feng89c12f12018-03-21 10:29:18 -0700625 FirewallRule rule;
626 FirewallType type;
627 if (isWhitelist) {
628 type = WHITELIST;
629 rule = ALLOW;
630 } else {
631 type = BLACKLIST;
632 rule = DENY;
633 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700634 Status res;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700635 if (!name.compare(FirewallController::LOCAL_DOZABLE)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700636 res = replaceUidsInMap(DOZABLE_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700637 } else if (!name.compare(FirewallController::LOCAL_STANDBY)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700638 res = replaceUidsInMap(STANDBY_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700639 } else if (!name.compare(FirewallController::LOCAL_POWERSAVE)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700640 res = replaceUidsInMap(POWERSAVE_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700641 } else {
642 ALOGE("unknown chain name: %s", name.c_str());
643 return -EINVAL;
644 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700645 if (!isOk(res)) {
646 ALOGE("Failed to clean up chain: %s: %s", name.c_str(), res.msg().c_str());
647 return -res.code();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700648 }
649 return 0;
650}
651
652int TrafficController::toggleUidOwnerMap(ChildChain chain, bool enable) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900653 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Fengf434e862018-06-27 14:08:39 -0700654 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Chenbo Feng703798e2018-06-15 17:07:59 -0700655 auto oldConfiguration = mConfigurationMap.readValue(key);
656 if (!isOk(oldConfiguration)) {
657 ALOGE("Cannot read the old configuration from map: %s",
658 oldConfiguration.status().msg().c_str());
659 return -oldConfiguration.status().code();
660 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700661 Status res;
Chenbo Feng703798e2018-06-15 17:07:59 -0700662 BpfConfig newConfiguration;
663 uint8_t match;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700664 switch (chain) {
665 case DOZABLE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700666 match = DOZABLE_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700667 break;
668 case STANDBY:
Chenbo Feng703798e2018-06-15 17:07:59 -0700669 match = STANDBY_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700670 break;
671 case POWERSAVE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700672 match = POWERSAVE_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700673 break;
674 default:
675 return -EINVAL;
676 }
Chenbo Feng703798e2018-06-15 17:07:59 -0700677 newConfiguration =
678 enable ? (oldConfiguration.value() | match) : (oldConfiguration.value() & (~match));
679 res = mConfigurationMap.writeValue(key, newConfiguration, BPF_EXIST);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700680 if (!isOk(res)) {
681 ALOGE("Failed to toggleUidOwnerMap(%d): %s", chain, res.msg().c_str());
Chenbo Feng89c12f12018-03-21 10:29:18 -0700682 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700683 return -res.code();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700684}
685
Chenbo Feng47dd0732018-12-11 12:23:24 -0800686BpfLevel TrafficController::getBpfLevel() {
687 return mBpfLevel;
Chenbo Feng07d43fe2017-12-21 14:38:51 -0800688}
689
Chenbo Feng48eaed32018-12-26 17:40:21 -0800690void TrafficController::setPermissionForUids(int permission, const std::vector<uid_t>& uids) {
Chenbo Fengbf660aa2019-02-26 16:12:27 -0800691 if (permission == INetd::PERMISSION_UNINSTALLED) {
692 for (uid_t uid : uids) {
693 // Clean up all permission information for the related uid if all the
694 // packages related to it are uninstalled.
695 mPrivilegedUser.erase(uid);
696 Status ret = mUidPermissionMap.deleteValue(uid);
697 }
698 return;
699 }
700
Chenbo Feng48eaed32018-12-26 17:40:21 -0800701 bool privileged = (permission & INetd::PERMISSION_UPDATE_DEVICE_STATS);
702
703 for (uid_t uid : uids) {
Chenbo Feng527908a2019-04-02 20:14:11 -0700704 // The map stores all the permissions that the UID has, except if the only permission
705 // the UID has is the INTERNET permission, then the UID should not appear in the map.
706 if (permission != INetd::PERMISSION_INTERNET) {
Chenbo Fengbf660aa2019-02-26 16:12:27 -0800707 Status ret = mUidPermissionMap.writeValue(uid, permission, BPF_ANY);
Chenbo Feng48eaed32018-12-26 17:40:21 -0800708 if (!isOk(ret)) {
Chenbo Feng527908a2019-04-02 20:14:11 -0700709 ALOGE("Failed to set permission: %s of uid(%u) to permission map: %s",
710 UidPermissionTypeToString(permission).c_str(), uid, strerror(ret.code()));
Chenbo Feng48eaed32018-12-26 17:40:21 -0800711 }
712 } else {
713 Status ret = mUidPermissionMap.deleteValue(uid);
714 if (!isOk(ret) && ret.code() != ENOENT) {
Chenbo Feng527908a2019-04-02 20:14:11 -0700715 ALOGE("Failed to remove uid %u from permission map: %s", uid, strerror(ret.code()));
Chenbo Feng48eaed32018-12-26 17:40:21 -0800716 }
717 }
718
719 if (privileged) {
720 mPrivilegedUser.insert(uid);
721 } else {
722 mPrivilegedUser.erase(uid);
723 }
724 }
725}
726
Chenbo Fengef297172018-03-26 10:53:33 -0700727std::string getProgramStatus(const char *path) {
728 int ret = access(path, R_OK);
729 if (ret == 0) {
730 return StringPrintf("OK");
731 }
732 if (ret != 0 && errno == ENOENT) {
733 return StringPrintf("program is missing at: %s", path);
734 }
735 return StringPrintf("check Program %s error: %s", path, strerror(errno));
736}
737
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700738std::string getMapStatus(const base::unique_fd& map_fd, const char* path) {
Chenbo Fengef297172018-03-26 10:53:33 -0700739 if (map_fd.get() < 0) {
740 return StringPrintf("map fd lost");
741 }
742 if (access(path, F_OK) != 0) {
743 return StringPrintf("map not pinned to location: %s", path);
744 }
745 return StringPrintf("OK");
746}
747
Bernie Innocentia5161a02019-01-30 22:40:53 +0900748// NOLINTNEXTLINE(google-runtime-references): grandfathered pass by non-const reference
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900749void dumpBpfMap(const std::string& mapName, DumpWriter& dw, const std::string& header) {
Chenbo Fengef297172018-03-26 10:53:33 -0700750 dw.blankline();
751 dw.println("%s:", mapName.c_str());
Erik Klineb31fd692018-06-06 20:50:11 +0900752 if (!header.empty()) {
753 dw.println(header);
Chenbo Fengef297172018-03-26 10:53:33 -0700754 }
755}
756
757const String16 TrafficController::DUMP_KEYWORD = String16("trafficcontroller");
758
759void TrafficController::dump(DumpWriter& dw, bool verbose) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900760 std::lock_guard ownerMapGuard(mOwnerMatchMutex);
Erik Klineb31fd692018-06-06 20:50:11 +0900761 ScopedIndent indentTop(dw);
Chenbo Fengef297172018-03-26 10:53:33 -0700762 dw.println("TrafficController");
763
Erik Klineb31fd692018-06-06 20:50:11 +0900764 ScopedIndent indentPreBpfModule(dw);
Chenbo Feng47dd0732018-12-11 12:23:24 -0800765 dw.println("BPF module status: %s", BpfLevelToString(mBpfLevel).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700766
Chenbo Feng47dd0732018-12-11 12:23:24 -0800767 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengef297172018-03-26 10:53:33 -0700768 return;
Erik Klineb31fd692018-06-06 20:50:11 +0900769 }
Chenbo Fengef297172018-03-26 10:53:33 -0700770
771 dw.blankline();
772 dw.println("mCookieTagMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700773 getMapStatus(mCookieTagMap.getMap(), COOKIE_TAG_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700774 dw.println("mUidCounterSetMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700775 getMapStatus(mUidCounterSetMap.getMap(), UID_COUNTERSET_MAP_PATH).c_str());
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700776 dw.println("mAppUidStatsMap status: %s",
777 getMapStatus(mAppUidStatsMap.getMap(), APP_UID_STATS_MAP_PATH).c_str());
Chenbo Fengf434e862018-06-27 14:08:39 -0700778 dw.println("mStatsMapA status: %s",
779 getMapStatus(mStatsMapA.getMap(), STATS_MAP_A_PATH).c_str());
780 dw.println("mStatsMapB status: %s",
781 getMapStatus(mStatsMapB.getMap(), STATS_MAP_B_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700782 dw.println("mIfaceIndexNameMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700783 getMapStatus(mIfaceIndexNameMap.getMap(), IFACE_INDEX_NAME_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700784 dw.println("mIfaceStatsMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700785 getMapStatus(mIfaceStatsMap.getMap(), IFACE_STATS_MAP_PATH).c_str());
Chenbo Feng703798e2018-06-15 17:07:59 -0700786 dw.println("mConfigurationMap status: %s",
787 getMapStatus(mConfigurationMap.getMap(), CONFIGURATION_MAP_PATH).c_str());
788 dw.println("mUidOwnerMap status: %s",
789 getMapStatus(mUidOwnerMap.getMap(), UID_OWNER_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700790
791 dw.blankline();
792 dw.println("Cgroup ingress program status: %s",
793 getProgramStatus(BPF_INGRESS_PROG_PATH).c_str());
794 dw.println("Cgroup egress program status: %s", getProgramStatus(BPF_EGRESS_PROG_PATH).c_str());
795 dw.println("xt_bpf ingress program status: %s",
796 getProgramStatus(XT_BPF_INGRESS_PROG_PATH).c_str());
797 dw.println("xt_bpf egress program status: %s",
798 getProgramStatus(XT_BPF_EGRESS_PROG_PATH).c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700799 dw.println("xt_bpf bandwidth whitelist program status: %s",
800 getProgramStatus(XT_BPF_WHITELIST_PROG_PATH).c_str());
801 dw.println("xt_bpf bandwidth blacklist program status: %s",
802 getProgramStatus(XT_BPF_BLACKLIST_PROG_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700803
Erik Klineb31fd692018-06-06 20:50:11 +0900804 if (!verbose) {
805 return;
806 }
Chenbo Fengef297172018-03-26 10:53:33 -0700807
808 dw.blankline();
809 dw.println("BPF map content:");
810
Erik Klineb31fd692018-06-06 20:50:11 +0900811 ScopedIndent indentForMapContent(dw);
Chenbo Fengef297172018-03-26 10:53:33 -0700812
813 // Print CookieTagMap content.
814 dumpBpfMap("mCookieTagMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700815 const auto printCookieTagInfo = [&dw](const uint64_t& key, const UidTag& value,
816 const BpfMap<uint64_t, UidTag>&) {
817 dw.println("cookie=%" PRIu64 " tag=0x%x uid=%u", key, value.tag, value.uid);
818 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700819 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700820 Status res = mCookieTagMap.iterateWithValue(printCookieTagInfo);
821 if (!isOk(res)) {
822 dw.println("mCookieTagMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700823 }
824
825 // Print UidCounterSetMap Content
826 dumpBpfMap("mUidCounterSetMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700827 const auto printUidInfo = [&dw](const uint32_t& key, const uint8_t& value,
828 const BpfMap<uint32_t, uint8_t>&) {
829 dw.println("%u %u", key, value);
830 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700831 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700832 res = mUidCounterSetMap.iterateWithValue(printUidInfo);
833 if (!isOk(res)) {
834 dw.println("mUidCounterSetMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700835 }
836
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700837 // Print AppUidStatsMap content
838 std::string appUidStatsHeader = StringPrintf("uid rxBytes rxPackets txBytes txPackets");
839 dumpBpfMap("mAppUidStatsMap:", dw, appUidStatsHeader);
840 auto printAppUidStatsInfo = [&dw](const uint32_t& key, const StatsValue& value,
841 const BpfMap<uint32_t, StatsValue>&) {
842 dw.println("%u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, value.rxBytes,
843 value.rxPackets, value.txBytes, value.txPackets);
844 return netdutils::status::ok;
845 };
846 res = mAppUidStatsMap.iterateWithValue(printAppUidStatsInfo);
847 if (!res.ok()) {
848 dw.println("mAppUidStatsMap print end with error: %s", res.msg().c_str());
849 }
850
Chenbo Fengef297172018-03-26 10:53:33 -0700851 // Print uidStatsMap content
852 std::string statsHeader = StringPrintf("ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes"
853 " rxPackets txBytes txPackets");
Chenbo Fengf434e862018-06-27 14:08:39 -0700854 dumpBpfMap("mStatsMapA", dw, statsHeader);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700855 const auto printStatsInfo = [&dw, this](const StatsKey& key, const StatsValue& value,
856 const BpfMap<StatsKey, StatsValue>&) {
857 uint32_t ifIndex = key.ifaceIndex;
858 auto ifname = mIfaceIndexNameMap.readValue(ifIndex);
859 if (!isOk(ifname)) {
860 strlcpy(ifname.value().name, "unknown", sizeof(IfaceValue));
Chenbo Fengef297172018-03-26 10:53:33 -0700861 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700862 dw.println("%u %s 0x%x %u %u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, ifIndex,
863 ifname.value().name, key.tag, key.uid, key.counterSet, value.rxBytes,
864 value.rxPackets, value.txBytes, value.txPackets);
865 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700866 };
Chenbo Fengf434e862018-06-27 14:08:39 -0700867 res = mStatsMapA.iterateWithValue(printStatsInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700868 if (!isOk(res)) {
Chenbo Fengf434e862018-06-27 14:08:39 -0700869 dw.println("mStatsMapA print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700870 }
871
872 // Print TagStatsMap content.
Chenbo Fengf434e862018-06-27 14:08:39 -0700873 dumpBpfMap("mStatsMapB", dw, statsHeader);
874 res = mStatsMapB.iterateWithValue(printStatsInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700875 if (!isOk(res)) {
Chenbo Fengf434e862018-06-27 14:08:39 -0700876 dw.println("mStatsMapB print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700877 }
878
879 // Print ifaceIndexToNameMap content.
880 dumpBpfMap("mIfaceIndexNameMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700881 const auto printIfaceNameInfo = [&dw](const uint32_t& key, const IfaceValue& value,
882 const BpfMap<uint32_t, IfaceValue>&) {
883 const char* ifname = value.name;
884 dw.println("ifaceIndex=%u ifaceName=%s", key, ifname);
885 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700886 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700887 res = mIfaceIndexNameMap.iterateWithValue(printIfaceNameInfo);
888 if (!isOk(res)) {
889 dw.println("mIfaceIndexNameMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700890 }
891
892 // Print ifaceStatsMap content
893 std::string ifaceStatsHeader = StringPrintf("ifaceIndex ifaceName rxBytes rxPackets txBytes"
894 " txPackets");
895 dumpBpfMap("mIfaceStatsMap:", dw, ifaceStatsHeader);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700896 const auto printIfaceStatsInfo = [&dw, this](const uint32_t& key, const StatsValue& value,
897 const BpfMap<uint32_t, StatsValue>&) {
898 auto ifname = mIfaceIndexNameMap.readValue(key);
899 if (!isOk(ifname)) {
900 strlcpy(ifname.value().name, "unknown", sizeof(IfaceValue));
Chenbo Fengef297172018-03-26 10:53:33 -0700901 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700902 dw.println("%u %s %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, ifname.value().name,
903 value.rxBytes, value.rxPackets, value.txBytes, value.txPackets);
904 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700905 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700906 res = mIfaceStatsMap.iterateWithValue(printIfaceStatsInfo);
907 if (!isOk(res)) {
908 dw.println("mIfaceStatsMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700909 }
910
Chenbo Feng703798e2018-06-15 17:07:59 -0700911 dw.blankline();
Chenbo Fengef297172018-03-26 10:53:33 -0700912
Chenbo Fengf434e862018-06-27 14:08:39 -0700913 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Chenbo Feng703798e2018-06-15 17:07:59 -0700914 auto configuration = mConfigurationMap.readValue(key);
915 if (isOk(configuration)) {
Chenbo Fengf434e862018-06-27 14:08:39 -0700916 dw.println("current ownerMatch configuration: %d", configuration.value());
Chenbo Feng703798e2018-06-15 17:07:59 -0700917 } else {
Chenbo Fengf434e862018-06-27 14:08:39 -0700918 dw.println("mConfigurationMap read ownerMatch configure failed with error: %s",
919 configuration.status().msg().c_str());
920 }
921 key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
922 configuration = mConfigurationMap.readValue(key);
923 if (isOk(configuration)) {
924 dw.println("current statsMap configuration: %d", configuration.value());
925 } else {
926 dw.println("mConfigurationMap read stats map configure failed with error: %s",
927 configuration.status().msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700928 }
Chenbo Feng703798e2018-06-15 17:07:59 -0700929 dumpBpfMap("mUidOwnerMap", dw, "");
930 const auto printUidMatchInfo = [&dw](const uint32_t& key, const uint8_t& value,
931 const BpfMap<uint32_t, uint8_t>&) {
932 dw.println("%u %s", key, uidMatchTypeToString(value).c_str());
933 return netdutils::status::ok;
934 };
935 res = mUidOwnerMap.iterateWithValue(printUidMatchInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700936 if (!isOk(res)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700937 dw.println("mUidOwnerMap print end with error: %s", res.msg().c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700938 }
Chenbo Feng48eaed32018-12-26 17:40:21 -0800939 dumpBpfMap("mUidPermissionMap", dw, "");
940 const auto printUidPermissionInfo = [&dw](const uint32_t& key, const uint8_t& value,
941 const BpfMap<uint32_t, uint8_t>&) {
942 dw.println("%u %s", key, UidPermissionTypeToString(value).c_str());
943 return netdutils::status::ok;
944 };
945 res = mUidPermissionMap.iterateWithValue(printUidPermissionInfo);
946 if (!isOk(res)) {
947 dw.println("mUidPermissionMap print end with error: %s", res.msg().c_str());
948 }
949
950 dumpBpfMap("mPrivilegedUser", dw, "");
951 for (uid_t uid : mPrivilegedUser) {
952 dw.println("%u ALLOW_UPDATE_DEVICE_STATS", (uint32_t)uid);
953 }
Chenbo Fengef297172018-03-26 10:53:33 -0700954}
955
Chenbo Fengf2759682017-10-10 17:31:57 -0700956} // namespace net
957} // namespace android