blob: 990287418338c699a673a6fdbb8c39987f406d08 [file] [log] [blame]
Chenbo Fengf2759682017-10-10 17:31:57 -07001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Chenbo Fengc10a8a42017-12-15 13:56:33 -080017#define LOG_TAG "TrafficController"
Chenbo Feng33cc1032017-10-23 15:16:37 -070018#include <inttypes.h>
Chenbo Fengf2759682017-10-10 17:31:57 -070019#include <linux/bpf.h>
20#include <linux/if_ether.h>
21#include <linux/in.h>
22#include <linux/inet_diag.h>
Chenbo Feng116d0552017-12-04 17:25:19 -080023#include <linux/netlink.h>
24#include <linux/sock_diag.h>
Chenbo Fengf2759682017-10-10 17:31:57 -070025#include <linux/unistd.h>
Chenbo Fengc10a8a42017-12-15 13:56:33 -080026#include <net/if.h>
Chenbo Fengf2759682017-10-10 17:31:57 -070027#include <stdlib.h>
28#include <string.h>
29#include <sys/socket.h>
Chenbo Fengc10a8a42017-12-15 13:56:33 -080030#include <sys/stat.h>
Chenbo Feng05393d82018-01-09 15:18:43 -080031#include <sys/types.h>
Chenbo Feng33cc1032017-10-23 15:16:37 -070032#include <sys/utsname.h>
Chenbo Feng05393d82018-01-09 15:18:43 -080033#include <sys/wait.h>
Chenbo Feng89c12f12018-03-21 10:29:18 -070034#include <mutex>
Chenbo Fengc10a8a42017-12-15 13:56:33 -080035#include <unordered_set>
36#include <vector>
37
38#include <android-base/stringprintf.h>
Chenbo Fengef297172018-03-26 10:53:33 -070039#include <android-base/strings.h>
Chenbo Fengc10a8a42017-12-15 13:56:33 -080040#include <android-base/unique_fd.h>
Chenbo Feng05393d82018-01-09 15:18:43 -080041#include <logwrap/logwrap.h>
Chenbo Fengc10a8a42017-12-15 13:56:33 -080042#include <netdutils/StatusOr.h>
Chenbo Fengf2759682017-10-10 17:31:57 -070043
Chenbo Feng116d0552017-12-04 17:25:19 -080044#include <netdutils/Misc.h>
45#include <netdutils/Syscalls.h>
Suren Baghdasaryane072a3c2019-01-16 14:36:07 -080046#include <processgroup/processgroup.h>
Chenbo Fengf2759682017-10-10 17:31:57 -070047#include "TrafficController.h"
Chenbo Feng4f6c2372018-04-26 10:37:55 -070048#include "bpf/BpfMap.h"
Chenbo Feng116d0552017-12-04 17:25:19 -080049
Chenbo Feng89c12f12018-03-21 10:29:18 -070050#include "FirewallController.h"
Chenbo Feng7e974052018-02-28 22:57:21 -080051#include "InterfaceController.h"
Chenbo Feng116d0552017-12-04 17:25:19 -080052#include "NetlinkListener.h"
Luke Huangb257d612019-03-14 21:19:13 +080053#include "netdutils/DumpWriter.h"
Chenbo Feng33cc1032017-10-23 15:16:37 -070054#include "qtaguid/qtaguid.h"
Chenbo Fengf2759682017-10-10 17:31:57 -070055
Bernie Innocenti7e25ec02018-07-02 19:32:17 +090056using namespace android::bpf; // NOLINT(google-build-using-namespace): grandfathered
Chenbo Fengf2759682017-10-10 17:31:57 -070057
58namespace android {
59namespace net {
60
Chenbo Fengc10a8a42017-12-15 13:56:33 -080061using base::StringPrintf;
62using base::unique_fd;
Luke Huangb257d612019-03-14 21:19:13 +080063using netdutils::DumpWriter;
Chenbo Feng116d0552017-12-04 17:25:19 -080064using netdutils::extract;
Luke Huangb257d612019-03-14 21:19:13 +080065using netdutils::ScopedIndent;
Chenbo Feng116d0552017-12-04 17:25:19 -080066using netdutils::Slice;
67using netdutils::sSyscalls;
Chenbo Fengc10a8a42017-12-15 13:56:33 -080068using netdutils::Status;
69using netdutils::statusFromErrno;
70using netdutils::StatusOr;
Chenbo Feng116d0552017-12-04 17:25:19 -080071using netdutils::status::ok;
Chenbo Fengc10a8a42017-12-15 13:56:33 -080072
Chenbo Feng116d0552017-12-04 17:25:19 -080073constexpr int kSockDiagMsgType = SOCK_DIAG_BY_FAMILY;
74constexpr int kSockDiagDoneMsgType = NLMSG_DONE;
75
Chenbo Feng48eaed32018-12-26 17:40:21 -080076#define FLAG_MSG_TRANS(result, flag, value) \
77 do { \
78 if (value & flag) { \
79 result.append(StringPrintf(" %s", #flag)); \
80 value &= ~flag; \
81 } \
Chenbo Feng703798e2018-06-15 17:07:59 -070082 } while (0)
83
84const std::string uidMatchTypeToString(uint8_t match) {
85 std::string matchType;
Chenbo Feng48eaed32018-12-26 17:40:21 -080086 FLAG_MSG_TRANS(matchType, HAPPY_BOX_MATCH, match);
87 FLAG_MSG_TRANS(matchType, PENALTY_BOX_MATCH, match);
88 FLAG_MSG_TRANS(matchType, DOZABLE_MATCH, match);
89 FLAG_MSG_TRANS(matchType, STANDBY_MATCH, match);
90 FLAG_MSG_TRANS(matchType, POWERSAVE_MATCH, match);
Chenbo Feng703798e2018-06-15 17:07:59 -070091 if (match) {
92 return StringPrintf("Unknown match: %u", match);
93 }
94 return matchType;
95}
96
Chenbo Fengb4a4fa12019-01-09 17:20:45 -080097bool TrafficController::hasUpdateDeviceStatsPermission(uid_t uid) {
Chenbo Feng3969c262019-03-19 14:53:57 -070098 // This implementation is the same logic as method ActivityManager#checkComponentPermission.
99 // It implies that the calling uid can never be the same as PER_USER_RANGE.
100 uint32_t appId = uid % PER_USER_RANGE;
101 return ((appId == AID_ROOT) || (appId == AID_SYSTEM) ||
102 mPrivilegedUser.find(appId) != mPrivilegedUser.end());
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800103}
104
Chenbo Feng48eaed32018-12-26 17:40:21 -0800105const std::string UidPermissionTypeToString(uint8_t permission) {
106 std::string permissionType;
107 FLAG_MSG_TRANS(permissionType, ALLOW_SOCK_CREATE, permission);
108 FLAG_MSG_TRANS(permissionType, ALLOW_UPDATE_DEVICE_STATS, permission);
109 if (permission) {
110 return StringPrintf("Unknown permission: %u", permission);
111 }
112 return permissionType;
113}
114
Chenbo Feng49586642018-08-30 18:01:53 -0700115StatusOr<std::unique_ptr<NetlinkListenerInterface>> TrafficController::makeSkDestroyListener() {
Chenbo Feng116d0552017-12-04 17:25:19 -0800116 const auto& sys = sSyscalls.get();
117 ASSIGN_OR_RETURN(auto event, sys.eventfd(0, EFD_CLOEXEC));
118 const int domain = AF_NETLINK;
119 const int type = SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK;
120 const int protocol = NETLINK_INET_DIAG;
121 ASSIGN_OR_RETURN(auto sock, sys.socket(domain, type, protocol));
122
Lorenzo Colitti436efdb2018-07-26 17:20:57 +0900123 // TODO: if too many sockets are closed too quickly, we can overflow the socket buffer, and
124 // some entries in mCookieTagMap will not be freed. In order to fix this we would need to
125 // periodically dump all sockets and remove the tag entries for sockets that have been closed.
126 // For now, set a large-enough buffer that we can close hundreds of sockets without getting
127 // ENOBUFS and leaking mCookieTagMap entries.
128 int rcvbuf = 512 * 1024;
129 auto ret = sys.setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf));
130 if (!ret.ok()) {
131 ALOGW("Failed to set SkDestroyListener buffer size to %d: %s", rcvbuf, ret.msg().c_str());
132 }
133
Chenbo Feng116d0552017-12-04 17:25:19 -0800134 sockaddr_nl addr = {
135 .nl_family = AF_NETLINK,
136 .nl_groups = 1 << (SKNLGRP_INET_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET_UDP_DESTROY - 1) |
137 1 << (SKNLGRP_INET6_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET6_UDP_DESTROY - 1)};
138 RETURN_IF_NOT_OK(sys.bind(sock, addr));
139
140 const sockaddr_nl kernel = {.nl_family = AF_NETLINK};
141 RETURN_IF_NOT_OK(sys.connect(sock, kernel));
142
143 std::unique_ptr<NetlinkListenerInterface> listener =
Chenbo Feng46296702018-08-23 12:20:22 -0700144 std::make_unique<NetlinkListener>(std::move(event), std::move(sock), "SkDestroyListen");
Chenbo Feng116d0552017-12-04 17:25:19 -0800145
146 return listener;
147}
148
Chenbo Feng89c12f12018-03-21 10:29:18 -0700149Status changeOwnerAndMode(const char* path, gid_t group, const char* debugName, bool netdOnly) {
150 int ret = chown(path, AID_ROOT, group);
151 if (ret != 0) return statusFromErrno(errno, StringPrintf("change %s group failed", debugName));
152
153 if (netdOnly) {
154 ret = chmod(path, S_IRWXU);
155 } else {
156 // Allow both netd and system server to obtain map fd from the path.
157 // chmod doesn't grant permission to all processes in that group to
158 // read/write the bpf map. They still need correct sepolicy to
159 // read/write the map.
Chenbo Fengf434e862018-06-27 14:08:39 -0700160 ret = chmod(path, S_IRWXU | S_IRGRP | S_IWGRP);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700161 }
162 if (ret != 0) return statusFromErrno(errno, StringPrintf("change %s mode failed", debugName));
163 return netdutils::status::ok;
164}
165
Chenbo Feng47dd0732018-12-11 12:23:24 -0800166TrafficController::TrafficController() : mBpfLevel(getBpfSupportLevel()) {}
Chenbo Feng89c12f12018-03-21 10:29:18 -0700167
Chenbo Feng89c12f12018-03-21 10:29:18 -0700168Status TrafficController::initMaps() {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900169 std::lock_guard ownerMapGuard(mOwnerMatchMutex);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700170 RETURN_IF_NOT_OK(
171 mCookieTagMap.getOrCreate(COOKIE_UID_MAP_SIZE, COOKIE_TAG_MAP_PATH, BPF_MAP_TYPE_HASH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700172
173 RETURN_IF_NOT_OK(changeOwnerAndMode(COOKIE_TAG_MAP_PATH, AID_NET_BW_ACCT, "CookieTagMap",
174 false));
175
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700176 RETURN_IF_NOT_OK(mUidCounterSetMap.getOrCreate(UID_COUNTERSET_MAP_SIZE, UID_COUNTERSET_MAP_PATH,
177 BPF_MAP_TYPE_HASH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700178 RETURN_IF_NOT_OK(changeOwnerAndMode(UID_COUNTERSET_MAP_PATH, AID_NET_BW_ACCT,
179 "UidCounterSetMap", false));
180
Chenbo Fengf434e862018-06-27 14:08:39 -0700181 RETURN_IF_NOT_OK(mAppUidStatsMap.getOrCreate(APP_STATS_MAP_SIZE, APP_UID_STATS_MAP_PATH,
182 BPF_MAP_TYPE_HASH));
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700183 RETURN_IF_NOT_OK(
184 changeOwnerAndMode(APP_UID_STATS_MAP_PATH, AID_NET_BW_STATS, "AppUidStatsMap", false));
185
Chenbo Fengf434e862018-06-27 14:08:39 -0700186 RETURN_IF_NOT_OK(mStatsMapA.getOrCreate(STATS_MAP_SIZE, STATS_MAP_A_PATH, BPF_MAP_TYPE_HASH));
187 RETURN_IF_NOT_OK(changeOwnerAndMode(STATS_MAP_A_PATH, AID_NET_BW_STATS, "StatsMapA", false));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700188
Chenbo Fengf434e862018-06-27 14:08:39 -0700189 RETURN_IF_NOT_OK(mStatsMapB.getOrCreate(STATS_MAP_SIZE, STATS_MAP_B_PATH, BPF_MAP_TYPE_HASH));
190 RETURN_IF_NOT_OK(changeOwnerAndMode(STATS_MAP_B_PATH, AID_NET_BW_STATS, "StatsMapB", false));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700191
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700192 RETURN_IF_NOT_OK(mIfaceIndexNameMap.getOrCreate(IFACE_INDEX_NAME_MAP_SIZE,
193 IFACE_INDEX_NAME_MAP_PATH, BPF_MAP_TYPE_HASH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700194 RETURN_IF_NOT_OK(changeOwnerAndMode(IFACE_INDEX_NAME_MAP_PATH, AID_NET_BW_STATS,
195 "IfaceIndexNameMap", false));
196
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700197 RETURN_IF_NOT_OK(
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700198 mIfaceStatsMap.getOrCreate(IFACE_STATS_MAP_SIZE, IFACE_STATS_MAP_PATH, BPF_MAP_TYPE_HASH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700199 RETURN_IF_NOT_OK(changeOwnerAndMode(IFACE_STATS_MAP_PATH, AID_NET_BW_STATS, "IfaceStatsMap",
200 false));
Chenbo Feng95892f32018-06-07 14:52:02 -0700201
Chenbo Feng703798e2018-06-15 17:07:59 -0700202 RETURN_IF_NOT_OK(mConfigurationMap.getOrCreate(CONFIGURATION_MAP_SIZE, CONFIGURATION_MAP_PATH,
203 BPF_MAP_TYPE_HASH));
Chenbo Fengf434e862018-06-27 14:08:39 -0700204 RETURN_IF_NOT_OK(changeOwnerAndMode(CONFIGURATION_MAP_PATH, AID_NET_BW_STATS,
205 "ConfigurationMap", false));
Chenbo Feng703798e2018-06-15 17:07:59 -0700206 RETURN_IF_NOT_OK(
Chenbo Fengf434e862018-06-27 14:08:39 -0700207 mConfigurationMap.writeValue(UID_RULES_CONFIGURATION_KEY, DEFAULT_CONFIG, BPF_ANY));
208 RETURN_IF_NOT_OK(mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, SELECT_MAP_A,
209 BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700210
211 RETURN_IF_NOT_OK(
212 mUidOwnerMap.getOrCreate(UID_OWNER_MAP_SIZE, UID_OWNER_MAP_PATH, BPF_MAP_TYPE_HASH));
213 RETURN_IF_NOT_OK(changeOwnerAndMode(UID_OWNER_MAP_PATH, AID_ROOT, "UidOwnerMap", true));
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900214 RETURN_IF_NOT_OK(mUidOwnerMap.clear());
Chenbo Feng48eaed32018-12-26 17:40:21 -0800215 RETURN_IF_NOT_OK(mUidPermissionMap.getOrCreate(UID_OWNER_MAP_SIZE, UID_PERMISSION_MAP_PATH,
216 BPF_MAP_TYPE_HASH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700217 return netdutils::status::ok;
218}
219
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800220static Status attachProgramToCgroup(const char* programPath, const int cgroupFd,
221 bpf_attach_type type) {
222 unique_fd cgroupProg(bpfFdGet(programPath, 0));
223 if (cgroupProg == -1) {
224 int ret = errno;
225 ALOGE("Failed to get program from %s: %s", programPath, strerror(ret));
226 return statusFromErrno(ret, "cgroup program get failed");
227 }
228 if (android::bpf::attachProgram(type, cgroupProg, cgroupFd)) {
229 int ret = errno;
230 ALOGE("Program from %s attach failed: %s", programPath, strerror(ret));
231 return statusFromErrno(ret, "program attach failed");
232 }
233 return netdutils::status::ok;
234}
235
236static Status initPrograms() {
Suren Baghdasaryane072a3c2019-01-16 14:36:07 -0800237 std::string cg2_path;
238
239 if (!CgroupGetControllerPath(CGROUPV2_CONTROLLER_NAME, &cg2_path)) {
240 int ret = errno;
241 ALOGE("Failed to find cgroup v2 root");
242 return statusFromErrno(ret, "Failed to find cgroup v2 root");
243 }
244
245 unique_fd cg_fd(open(cg2_path.c_str(), O_DIRECTORY | O_RDONLY | O_CLOEXEC));
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800246 if (cg_fd == -1) {
247 int ret = errno;
248 ALOGE("Failed to open the cgroup directory: %s", strerror(ret));
249 return statusFromErrno(ret, "Open the cgroup directory failed");
250 }
251 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_EGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_EGRESS));
252 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_INGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_INGRESS));
Chenbo Fenga51f4fa2019-01-15 15:03:32 -0800253
254 // For the devices that support cgroup socket filter, the socket filter
255 // should be loaded successfully by bpfloader. So we attach the filter to
256 // cgroup if the program is pinned properly.
257 // TODO: delete the if statement once all devices should support cgroup
258 // socket filter (ie. the minimum kernel version required is 4.14).
259 if (!access(CGROUP_SOCKET_PROG_PATH, F_OK)) {
260 RETURN_IF_NOT_OK(
261 attachProgramToCgroup(CGROUP_SOCKET_PROG_PATH, cg_fd, BPF_CGROUP_INET_SOCK_CREATE));
262 }
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800263 return netdutils::status::ok;
264}
265
Chenbo Feng89c12f12018-03-21 10:29:18 -0700266Status TrafficController::start() {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800267 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800268 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700269 }
270
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900271 /* When netd restarts from a crash without total system reboot, the program
Chenbo Fengf2759682017-10-10 17:31:57 -0700272 * is still attached to the cgroup, detach it so the program can be freed
273 * and we can load and attach new program into the target cgroup.
274 *
275 * TODO: Scrape existing socket when run-time restart and clean up the map
276 * if the socket no longer exist
277 */
278
Chenbo Feng89c12f12018-03-21 10:29:18 -0700279 RETURN_IF_NOT_OK(initMaps());
Chenbo Feng7e974052018-02-28 22:57:21 -0800280
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800281 RETURN_IF_NOT_OK(initPrograms());
282
Chenbo Feng7e974052018-02-28 22:57:21 -0800283 // Fetch the list of currently-existing interfaces. At this point NetlinkHandler is
284 // already running, so it will call addInterface() when any new interface appears.
285 std::map<std::string, uint32_t> ifacePairs;
286 ASSIGN_OR_RETURN(ifacePairs, InterfaceController::getIfaceList());
287 for (const auto& ifacePair:ifacePairs) {
288 addInterface(ifacePair.first.c_str(), ifacePair.second);
289 }
290
Chenbo Feng116d0552017-12-04 17:25:19 -0800291 auto result = makeSkDestroyListener();
292 if (!isOk(result)) {
293 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
294 } else {
295 mSkDestroyListener = std::move(result.value());
296 }
297 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
298 const auto rxHandler = [this](const nlmsghdr&, const Slice msg) {
299 inet_diag_msg diagmsg = {};
300 if (extract(msg, diagmsg) < sizeof(inet_diag_msg)) {
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900301 ALOGE("Unrecognized netlink message: %s", toString(msg).c_str());
Chenbo Feng116d0552017-12-04 17:25:19 -0800302 return;
303 }
304 uint64_t sock_cookie = static_cast<uint64_t>(diagmsg.id.idiag_cookie[0]) |
305 (static_cast<uint64_t>(diagmsg.id.idiag_cookie[1]) << 32);
306
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900307 Status s = mCookieTagMap.deleteValue(sock_cookie);
Chenbo Feng1d4c5db2018-10-18 15:50:46 -0700308 if (!isOk(s) && s.code() != ENOENT) {
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900309 ALOGE("Failed to delete cookie %" PRIx64 ": %s", sock_cookie, toString(s).c_str());
310 return;
311 }
Chenbo Feng116d0552017-12-04 17:25:19 -0800312 };
313 expectOk(mSkDestroyListener->subscribe(kSockDiagMsgType, rxHandler));
314
315 // In case multiple netlink message comes in as a stream, we need to handle the rxDone message
316 // properly.
317 const auto rxDoneHandler = [](const nlmsghdr&, const Slice msg) {
318 // Ignore NLMSG_DONE messages
319 inet_diag_msg diagmsg = {};
320 extract(msg, diagmsg);
321 };
322 expectOk(mSkDestroyListener->subscribe(kSockDiagDoneMsgType, rxDoneHandler));
323
Chenbo Feng05393d82018-01-09 15:18:43 -0800324 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700325}
326
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800327int TrafficController::tagSocket(int sockFd, uint32_t tag, uid_t uid, uid_t callingUid) {
328 if (uid != callingUid && !hasUpdateDeviceStatsPermission(callingUid)) {
329 return -EPERM;
330 }
331
Chenbo Feng47dd0732018-12-11 12:23:24 -0800332 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700333 if (legacy_tagSocket(sockFd, tag, uid)) return -errno;
334 return 0;
335 }
Chenbo Feng33cc1032017-10-23 15:16:37 -0700336
Chenbo Fengf2759682017-10-10 17:31:57 -0700337 uint64_t sock_cookie = getSocketCookie(sockFd);
Chenbo Fengef1cab32018-04-13 19:50:49 -0700338 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
Chenbo Fengf2759682017-10-10 17:31:57 -0700339 UidTag newKey = {.uid = (uint32_t)uid, .tag = tag};
340
341 // Update the tag information of a socket to the cookieUidMap. Use BPF_ANY
342 // flag so it will insert a new entry to the map if that value doesn't exist
343 // yet. And update the tag if there is already a tag stored. Since the eBPF
344 // program in kernel only read this map, and is protected by rcu read lock. It
345 // should be fine to cocurrently update the map while eBPF program is running.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700346 Status res = mCookieTagMap.writeValue(sock_cookie, newKey, BPF_ANY);
347 if (!isOk(res)) {
348 ALOGE("Failed to tag the socket: %s, fd: %d", strerror(res.code()),
349 mCookieTagMap.getMap().get());
Chenbo Fengf2759682017-10-10 17:31:57 -0700350 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700351 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700352}
353
354int TrafficController::untagSocket(int sockFd) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800355 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700356 if (legacy_untagSocket(sockFd)) return -errno;
357 return 0;
358 }
Chenbo Fengf2759682017-10-10 17:31:57 -0700359 uint64_t sock_cookie = getSocketCookie(sockFd);
360
Chenbo Fengef1cab32018-04-13 19:50:49 -0700361 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700362 Status res = mCookieTagMap.deleteValue(sock_cookie);
363 if (!isOk(res)) {
364 ALOGE("Failed to untag socket: %s\n", strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700365 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700366 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700367}
368
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800369int TrafficController::setCounterSet(int counterSetNum, uid_t uid, uid_t callingUid) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700370 if (counterSetNum < 0 || counterSetNum >= OVERFLOW_COUNTERSET) return -EINVAL;
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800371
372 if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
373
Chenbo Feng47dd0732018-12-11 12:23:24 -0800374 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700375 if (legacy_setCounterSet(counterSetNum, uid)) return -errno;
376 return 0;
377 }
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800378
379 // The default counter set for all uid is 0, so deleting the current counterset for that uid
380 // will automatically set it to 0.
Chenbo Fengf2759682017-10-10 17:31:57 -0700381 if (counterSetNum == 0) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700382 Status res = mUidCounterSetMap.deleteValue(uid);
383 if (isOk(res) || (!isOk(res) && res.code() == ENOENT)) {
Chenbo Fengf2759682017-10-10 17:31:57 -0700384 return 0;
385 } else {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700386 ALOGE("Failed to delete the counterSet: %s\n", strerror(res.code()));
387 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700388 }
389 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700390 uint8_t tmpCounterSetNum = (uint8_t)counterSetNum;
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800391 Status res = mUidCounterSetMap.writeValue(uid, tmpCounterSetNum, BPF_ANY);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700392 if (!isOk(res)) {
393 ALOGE("Failed to set the counterSet: %s, fd: %d", strerror(res.code()),
394 mUidCounterSetMap.getMap().get());
395 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700396 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700397 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700398}
399
Chenbo Fengf434e862018-06-27 14:08:39 -0700400// This method only get called by system_server when an app get uinstalled, it
401// is called inside removeUidsLocked() while holding mStatsLock. So it is safe
402// to iterate and modify the stats maps.
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800403int TrafficController::deleteTagData(uint32_t tag, uid_t uid, uid_t callingUid) {
404 if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
405
Chenbo Feng47dd0732018-12-11 12:23:24 -0800406 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700407 if (legacy_deleteTagData(tag, uid)) return -errno;
408 return 0;
409 }
Chenbo Feng33cc1032017-10-23 15:16:37 -0700410
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800411 // First we go through the cookieTagMap to delete the target uid tag combination. Or delete all
Chenbo Fengef1cab32018-04-13 19:50:49 -0700412 // the tags related to the uid if the tag is 0.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700413 const auto deleteMatchedCookieEntries = [uid, tag](const uint64_t& key, const UidTag& value,
414 BpfMap<uint64_t, UidTag>& map) {
415 if (value.uid == uid && (value.tag == tag || tag == 0)) {
416 Status res = map.deleteValue(key);
417 if (isOk(res) || (res.code() == ENOENT)) {
418 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700419 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700420 ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s\n", key, strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700421 }
Chenbo Fengef1cab32018-04-13 19:50:49 -0700422 // Move forward to next cookie in the map.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700423 return netdutils::status::ok;
Chenbo Fengef1cab32018-04-13 19:50:49 -0700424 };
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900425 mCookieTagMap.iterateWithValue(deleteMatchedCookieEntries).ignoreError();
Chenbo Fengf2759682017-10-10 17:31:57 -0700426 // 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 -0700427 // combination. Or all tag stats under that uid if the target tag is 0.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700428 const auto deleteMatchedUidTagEntries = [uid, tag](const StatsKey& key,
429 BpfMap<StatsKey, StatsValue>& map) {
430 if (key.uid == uid && (key.tag == tag || tag == 0)) {
431 Status res = map.deleteValue(key);
432 if (isOk(res) || (res.code() == ENOENT)) {
Chenbo Fengef1cab32018-04-13 19:50:49 -0700433 //Entry is deleted, use the current key to get a new nextKey;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700434 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700435 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700436 ALOGE("Failed to delete data(uid=%u, tag=%u): %s\n", key.uid, key.tag,
437 strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700438 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700439 return netdutils::status::ok;
Chenbo Fengef1cab32018-04-13 19:50:49 -0700440 };
Chenbo Fengf434e862018-06-27 14:08:39 -0700441 mStatsMapB.iterate(deleteMatchedUidTagEntries).ignoreError();
442 mStatsMapA.iterate(deleteMatchedUidTagEntries).ignoreError();
Chenbo Fengf2759682017-10-10 17:31:57 -0700443 // 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 -0800444 // need to delete the stats stored in uidStatsMap and counterSet map.
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800445 if (tag != 0) return 0;
446
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700447 Status res = mUidCounterSetMap.deleteValue(uid);
448 if (!isOk(res) && res.code() != ENOENT) {
449 ALOGE("Failed to delete counterSet data(uid=%u, tag=%u): %s\n", uid, tag,
450 strerror(res.code()));
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800451 }
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700452
453 auto deleteAppUidStatsEntry = [uid](const uint32_t& key, BpfMap<uint32_t, StatsValue>& map) {
454 if (key == uid) {
455 Status res = map.deleteValue(key);
456 if (isOk(res) || (res.code() == ENOENT)) {
457 return netdutils::status::ok;
458 }
459 ALOGE("Failed to delete data(uid=%u): %s", key, strerror(res.code()));
460 }
461 return netdutils::status::ok;
462 };
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900463 mAppUidStatsMap.iterate(deleteAppUidStatsEntry).ignoreError();
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700464 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700465}
466
Chenbo Feng7e974052018-02-28 22:57:21 -0800467int TrafficController::addInterface(const char* name, uint32_t ifaceIndex) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800468 if (mBpfLevel == BpfLevel::NONE) return 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800469
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700470 IfaceValue iface;
Chenbo Feng7e974052018-02-28 22:57:21 -0800471 if (ifaceIndex == 0) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700472 ALOGE("Unknown interface %s(%d)", name, ifaceIndex);
Chenbo Feng7e974052018-02-28 22:57:21 -0800473 return -1;
474 }
475
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700476 strlcpy(iface.name, name, sizeof(IfaceValue));
477 Status res = mIfaceIndexNameMap.writeValue(ifaceIndex, iface, BPF_ANY);
478 if (!isOk(res)) {
479 ALOGE("Failed to add iface %s(%d): %s", name, ifaceIndex, strerror(res.code()));
480 return -res.code();
Chenbo Feng7e974052018-02-28 22:57:21 -0800481 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700482 return 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800483}
484
Chenbo Feng703798e2018-06-15 17:07:59 -0700485Status TrafficController::updateOwnerMapEntry(UidOwnerMatchType match, uid_t uid, FirewallRule rule,
486 FirewallType type) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900487 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700488 if ((rule == ALLOW && type == WHITELIST) || (rule == DENY && type == BLACKLIST)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700489 RETURN_IF_NOT_OK(addMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700490 } else if ((rule == ALLOW && type == BLACKLIST) || (rule == DENY && type == WHITELIST)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700491 RETURN_IF_NOT_OK(removeMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700492 } else {
493 //Cannot happen.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700494 return statusFromErrno(-EINVAL, "");
Chenbo Feng89c12f12018-03-21 10:29:18 -0700495 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700496 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700497}
498
Chenbo Feng703798e2018-06-15 17:07:59 -0700499UidOwnerMatchType TrafficController::jumpOpToMatch(BandwidthController::IptJumpOp jumpHandling) {
Chenbo Feng95892f32018-06-07 14:52:02 -0700500 switch (jumpHandling) {
501 case BandwidthController::IptJumpReject:
Chenbo Feng703798e2018-06-15 17:07:59 -0700502 return PENALTY_BOX_MATCH;
Chenbo Feng95892f32018-06-07 14:52:02 -0700503 case BandwidthController::IptJumpReturn:
Chenbo Feng703798e2018-06-15 17:07:59 -0700504 return HAPPY_BOX_MATCH;
Chenbo Feng95892f32018-06-07 14:52:02 -0700505 case BandwidthController::IptJumpNoAdd:
506 return NO_MATCH;
507 }
508}
509
Chenbo Feng703798e2018-06-15 17:07:59 -0700510Status TrafficController::removeMatch(BpfMap<uint32_t, uint8_t>& map, uint32_t uid,
511 UidOwnerMatchType match) {
512 auto oldMatch = map.readValue(uid);
513 if (isOk(oldMatch)) {
514 uint8_t newMatch = oldMatch.value() & ~match;
515 if (newMatch == 0) {
516 RETURN_IF_NOT_OK(map.deleteValue(uid));
517 } else {
518 RETURN_IF_NOT_OK(map.writeValue(uid, newMatch, BPF_ANY));
519 }
520 } else {
521 return statusFromErrno(ENOENT, StringPrintf("uid: %u does not exist in map", uid));
522 }
523 return netdutils::status::ok;
524}
525
526Status TrafficController::addMatch(BpfMap<uint32_t, uint8_t>& map, uint32_t uid,
527 UidOwnerMatchType match) {
528 auto oldMatch = map.readValue(uid);
529 if (isOk(oldMatch)) {
530 uint8_t newMatch = oldMatch.value() | match;
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900531 RETURN_IF_NOT_OK(map.writeValue((uint32_t) uid, newMatch, BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700532 } else {
533 RETURN_IF_NOT_OK(map.writeValue(uid, match, BPF_ANY));
534 }
535 return netdutils::status::ok;
536}
537
538Status TrafficController::updateUidOwnerMap(const std::vector<std::string>& appStrUids,
539 BandwidthController::IptJumpOp jumpHandling,
540 BandwidthController::IptOp op) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900541 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Feng703798e2018-06-15 17:07:59 -0700542 UidOwnerMatchType match = jumpOpToMatch(jumpHandling);
543 if (match == NO_MATCH) {
544 return statusFromErrno(
545 EINVAL, StringPrintf("invalid IptJumpOp: %d, command: %d", jumpHandling, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700546 }
547 for (const auto& appStrUid : appStrUids) {
548 char* endPtr;
549 long uid = strtol(appStrUid.c_str(), &endPtr, 10);
550 if ((errno == ERANGE && (uid == LONG_MAX || uid == LONG_MIN)) ||
551 (endPtr == appStrUid.c_str()) || (*endPtr != '\0')) {
552 return statusFromErrno(errno, "invalid uid string:" + appStrUid);
553 }
554
Chenbo Feng95892f32018-06-07 14:52:02 -0700555 if (op == BandwidthController::IptOpDelete) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700556 RETURN_IF_NOT_OK(removeMatch(mUidOwnerMap, uid, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700557 } else if (op == BandwidthController::IptOpInsert) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700558 RETURN_IF_NOT_OK(addMatch(mUidOwnerMap, uid, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700559 } else {
560 // Cannot happen.
Chenbo Feng703798e2018-06-15 17:07:59 -0700561 return statusFromErrno(EINVAL, StringPrintf("invalid IptOp: %d, %d", op, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700562 }
563 }
564 return netdutils::status::ok;
565}
566
Chenbo Feng89c12f12018-03-21 10:29:18 -0700567int TrafficController::changeUidOwnerRule(ChildChain chain, uid_t uid, FirewallRule rule,
568 FirewallType type) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800569 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Feng89c12f12018-03-21 10:29:18 -0700570 ALOGE("bpf is not set up, should use iptables rule");
571 return -ENOSYS;
572 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700573 Status res;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700574 switch (chain) {
575 case DOZABLE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700576 res = updateOwnerMapEntry(DOZABLE_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700577 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700578 case STANDBY:
Chenbo Feng703798e2018-06-15 17:07:59 -0700579 res = updateOwnerMapEntry(STANDBY_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700580 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700581 case POWERSAVE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700582 res = updateOwnerMapEntry(POWERSAVE_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700583 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700584 case NONE:
585 default:
586 return -EINVAL;
587 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700588 if (!isOk(res)) {
589 ALOGE("change uid(%u) rule of %d failed: %s, rule: %d, type: %d", uid, chain,
590 res.msg().c_str(), rule, type);
591 return -res.code();
592 }
593 return 0;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700594}
595
Chenbo Feng703798e2018-06-15 17:07:59 -0700596Status TrafficController::replaceUidsInMap(const UidOwnerMatchType match,
597 const std::vector<int32_t>& uids) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900598 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700599 std::set<int32_t> uidSet(uids.begin(), uids.end());
600 std::vector<uint32_t> uidsToDelete;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700601 auto getUidsToDelete = [&uidsToDelete, &uidSet](const uint32_t& key,
602 const BpfMap<uint32_t, uint8_t>&) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700603 if (uidSet.find((int32_t) key) == uidSet.end()) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700604 uidsToDelete.push_back(key);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700605 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700606 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700607 };
Chenbo Feng703798e2018-06-15 17:07:59 -0700608 RETURN_IF_NOT_OK(mUidOwnerMap.iterate(getUidsToDelete));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700609
610 for(auto uid : uidsToDelete) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700611 RETURN_IF_NOT_OK(removeMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700612 }
613
614 for (auto uid : uids) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700615 RETURN_IF_NOT_OK(addMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700616 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700617 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700618}
619
620int TrafficController::replaceUidOwnerMap(const std::string& name, bool isWhitelist,
621 const std::vector<int32_t>& uids) {
Chenbo Feng89c12f12018-03-21 10:29:18 -0700622 FirewallRule rule;
623 FirewallType type;
624 if (isWhitelist) {
625 type = WHITELIST;
626 rule = ALLOW;
627 } else {
628 type = BLACKLIST;
629 rule = DENY;
630 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700631 Status res;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700632 if (!name.compare(FirewallController::LOCAL_DOZABLE)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700633 res = replaceUidsInMap(DOZABLE_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700634 } else if (!name.compare(FirewallController::LOCAL_STANDBY)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700635 res = replaceUidsInMap(STANDBY_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700636 } else if (!name.compare(FirewallController::LOCAL_POWERSAVE)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700637 res = replaceUidsInMap(POWERSAVE_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700638 } else {
639 ALOGE("unknown chain name: %s", name.c_str());
640 return -EINVAL;
641 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700642 if (!isOk(res)) {
643 ALOGE("Failed to clean up chain: %s: %s", name.c_str(), res.msg().c_str());
644 return -res.code();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700645 }
646 return 0;
647}
648
649int TrafficController::toggleUidOwnerMap(ChildChain chain, bool enable) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900650 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Fengf434e862018-06-27 14:08:39 -0700651 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Chenbo Feng703798e2018-06-15 17:07:59 -0700652 auto oldConfiguration = mConfigurationMap.readValue(key);
653 if (!isOk(oldConfiguration)) {
654 ALOGE("Cannot read the old configuration from map: %s",
655 oldConfiguration.status().msg().c_str());
656 return -oldConfiguration.status().code();
657 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700658 Status res;
Chenbo Feng703798e2018-06-15 17:07:59 -0700659 BpfConfig newConfiguration;
660 uint8_t match;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700661 switch (chain) {
662 case DOZABLE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700663 match = DOZABLE_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700664 break;
665 case STANDBY:
Chenbo Feng703798e2018-06-15 17:07:59 -0700666 match = STANDBY_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700667 break;
668 case POWERSAVE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700669 match = POWERSAVE_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700670 break;
671 default:
672 return -EINVAL;
673 }
Chenbo Feng703798e2018-06-15 17:07:59 -0700674 newConfiguration =
675 enable ? (oldConfiguration.value() | match) : (oldConfiguration.value() & (~match));
676 res = mConfigurationMap.writeValue(key, newConfiguration, BPF_EXIST);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700677 if (!isOk(res)) {
678 ALOGE("Failed to toggleUidOwnerMap(%d): %s", chain, res.msg().c_str());
Chenbo Feng89c12f12018-03-21 10:29:18 -0700679 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700680 return -res.code();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700681}
682
Chenbo Feng47dd0732018-12-11 12:23:24 -0800683BpfLevel TrafficController::getBpfLevel() {
684 return mBpfLevel;
Chenbo Feng07d43fe2017-12-21 14:38:51 -0800685}
686
Chenbo Feng48eaed32018-12-26 17:40:21 -0800687void TrafficController::setPermissionForUids(int permission, const std::vector<uid_t>& uids) {
688 bool internet = (permission & INetd::PERMISSION_INTERNET);
689 bool privileged = (permission & INetd::PERMISSION_UPDATE_DEVICE_STATS);
690
691 for (uid_t uid : uids) {
692 if (internet) {
693 Status ret = mUidPermissionMap.writeValue(uid, ALLOW_SOCK_CREATE, BPF_ANY);
694 if (!isOk(ret)) {
695 ALOGE("Failed to grant INTERNET permission to uid: %u: %s", uid,
696 strerror(ret.code()));
697 }
698 } else {
699 Status ret = mUidPermissionMap.deleteValue(uid);
700 if (!isOk(ret) && ret.code() != ENOENT) {
701 ALOGE("Failed to revoke permission INTERNET from uid: %u: %s", uid,
702 strerror(ret.code()));
703 }
704 }
705
706 if (privileged) {
707 mPrivilegedUser.insert(uid);
708 } else {
709 mPrivilegedUser.erase(uid);
710 }
711 }
712}
713
Chenbo Fengef297172018-03-26 10:53:33 -0700714std::string getProgramStatus(const char *path) {
715 int ret = access(path, R_OK);
716 if (ret == 0) {
717 return StringPrintf("OK");
718 }
719 if (ret != 0 && errno == ENOENT) {
720 return StringPrintf("program is missing at: %s", path);
721 }
722 return StringPrintf("check Program %s error: %s", path, strerror(errno));
723}
724
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700725std::string getMapStatus(const base::unique_fd& map_fd, const char* path) {
Chenbo Fengef297172018-03-26 10:53:33 -0700726 if (map_fd.get() < 0) {
727 return StringPrintf("map fd lost");
728 }
729 if (access(path, F_OK) != 0) {
730 return StringPrintf("map not pinned to location: %s", path);
731 }
732 return StringPrintf("OK");
733}
734
Bernie Innocentia5161a02019-01-30 22:40:53 +0900735// NOLINTNEXTLINE(google-runtime-references): grandfathered pass by non-const reference
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900736void dumpBpfMap(const std::string& mapName, DumpWriter& dw, const std::string& header) {
Chenbo Fengef297172018-03-26 10:53:33 -0700737 dw.blankline();
738 dw.println("%s:", mapName.c_str());
Erik Klineb31fd692018-06-06 20:50:11 +0900739 if (!header.empty()) {
740 dw.println(header);
Chenbo Fengef297172018-03-26 10:53:33 -0700741 }
742}
743
744const String16 TrafficController::DUMP_KEYWORD = String16("trafficcontroller");
745
746void TrafficController::dump(DumpWriter& dw, bool verbose) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900747 std::lock_guard ownerMapGuard(mOwnerMatchMutex);
Erik Klineb31fd692018-06-06 20:50:11 +0900748 ScopedIndent indentTop(dw);
Chenbo Fengef297172018-03-26 10:53:33 -0700749 dw.println("TrafficController");
750
Erik Klineb31fd692018-06-06 20:50:11 +0900751 ScopedIndent indentPreBpfModule(dw);
Chenbo Feng47dd0732018-12-11 12:23:24 -0800752 dw.println("BPF module status: %s", BpfLevelToString(mBpfLevel).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700753
Chenbo Feng47dd0732018-12-11 12:23:24 -0800754 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengef297172018-03-26 10:53:33 -0700755 return;
Erik Klineb31fd692018-06-06 20:50:11 +0900756 }
Chenbo Fengef297172018-03-26 10:53:33 -0700757
758 dw.blankline();
759 dw.println("mCookieTagMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700760 getMapStatus(mCookieTagMap.getMap(), COOKIE_TAG_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700761 dw.println("mUidCounterSetMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700762 getMapStatus(mUidCounterSetMap.getMap(), UID_COUNTERSET_MAP_PATH).c_str());
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700763 dw.println("mAppUidStatsMap status: %s",
764 getMapStatus(mAppUidStatsMap.getMap(), APP_UID_STATS_MAP_PATH).c_str());
Chenbo Fengf434e862018-06-27 14:08:39 -0700765 dw.println("mStatsMapA status: %s",
766 getMapStatus(mStatsMapA.getMap(), STATS_MAP_A_PATH).c_str());
767 dw.println("mStatsMapB status: %s",
768 getMapStatus(mStatsMapB.getMap(), STATS_MAP_B_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700769 dw.println("mIfaceIndexNameMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700770 getMapStatus(mIfaceIndexNameMap.getMap(), IFACE_INDEX_NAME_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700771 dw.println("mIfaceStatsMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700772 getMapStatus(mIfaceStatsMap.getMap(), IFACE_STATS_MAP_PATH).c_str());
Chenbo Feng703798e2018-06-15 17:07:59 -0700773 dw.println("mConfigurationMap status: %s",
774 getMapStatus(mConfigurationMap.getMap(), CONFIGURATION_MAP_PATH).c_str());
775 dw.println("mUidOwnerMap status: %s",
776 getMapStatus(mUidOwnerMap.getMap(), UID_OWNER_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700777
778 dw.blankline();
779 dw.println("Cgroup ingress program status: %s",
780 getProgramStatus(BPF_INGRESS_PROG_PATH).c_str());
781 dw.println("Cgroup egress program status: %s", getProgramStatus(BPF_EGRESS_PROG_PATH).c_str());
782 dw.println("xt_bpf ingress program status: %s",
783 getProgramStatus(XT_BPF_INGRESS_PROG_PATH).c_str());
784 dw.println("xt_bpf egress program status: %s",
785 getProgramStatus(XT_BPF_EGRESS_PROG_PATH).c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700786 dw.println("xt_bpf bandwidth whitelist program status: %s",
787 getProgramStatus(XT_BPF_WHITELIST_PROG_PATH).c_str());
788 dw.println("xt_bpf bandwidth blacklist program status: %s",
789 getProgramStatus(XT_BPF_BLACKLIST_PROG_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700790
Erik Klineb31fd692018-06-06 20:50:11 +0900791 if (!verbose) {
792 return;
793 }
Chenbo Fengef297172018-03-26 10:53:33 -0700794
795 dw.blankline();
796 dw.println("BPF map content:");
797
Erik Klineb31fd692018-06-06 20:50:11 +0900798 ScopedIndent indentForMapContent(dw);
Chenbo Fengef297172018-03-26 10:53:33 -0700799
800 // Print CookieTagMap content.
801 dumpBpfMap("mCookieTagMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700802 const auto printCookieTagInfo = [&dw](const uint64_t& key, const UidTag& value,
803 const BpfMap<uint64_t, UidTag>&) {
804 dw.println("cookie=%" PRIu64 " tag=0x%x uid=%u", key, value.tag, value.uid);
805 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700806 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700807 Status res = mCookieTagMap.iterateWithValue(printCookieTagInfo);
808 if (!isOk(res)) {
809 dw.println("mCookieTagMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700810 }
811
812 // Print UidCounterSetMap Content
813 dumpBpfMap("mUidCounterSetMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700814 const auto printUidInfo = [&dw](const uint32_t& key, const uint8_t& value,
815 const BpfMap<uint32_t, uint8_t>&) {
816 dw.println("%u %u", key, value);
817 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700818 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700819 res = mUidCounterSetMap.iterateWithValue(printUidInfo);
820 if (!isOk(res)) {
821 dw.println("mUidCounterSetMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700822 }
823
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700824 // Print AppUidStatsMap content
825 std::string appUidStatsHeader = StringPrintf("uid rxBytes rxPackets txBytes txPackets");
826 dumpBpfMap("mAppUidStatsMap:", dw, appUidStatsHeader);
827 auto printAppUidStatsInfo = [&dw](const uint32_t& key, const StatsValue& value,
828 const BpfMap<uint32_t, StatsValue>&) {
829 dw.println("%u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, value.rxBytes,
830 value.rxPackets, value.txBytes, value.txPackets);
831 return netdutils::status::ok;
832 };
833 res = mAppUidStatsMap.iterateWithValue(printAppUidStatsInfo);
834 if (!res.ok()) {
835 dw.println("mAppUidStatsMap print end with error: %s", res.msg().c_str());
836 }
837
Chenbo Fengef297172018-03-26 10:53:33 -0700838 // Print uidStatsMap content
839 std::string statsHeader = StringPrintf("ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes"
840 " rxPackets txBytes txPackets");
Chenbo Fengf434e862018-06-27 14:08:39 -0700841 dumpBpfMap("mStatsMapA", dw, statsHeader);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700842 const auto printStatsInfo = [&dw, this](const StatsKey& key, const StatsValue& value,
843 const BpfMap<StatsKey, StatsValue>&) {
844 uint32_t ifIndex = key.ifaceIndex;
845 auto ifname = mIfaceIndexNameMap.readValue(ifIndex);
846 if (!isOk(ifname)) {
847 strlcpy(ifname.value().name, "unknown", sizeof(IfaceValue));
Chenbo Fengef297172018-03-26 10:53:33 -0700848 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700849 dw.println("%u %s 0x%x %u %u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, ifIndex,
850 ifname.value().name, key.tag, key.uid, key.counterSet, value.rxBytes,
851 value.rxPackets, value.txBytes, value.txPackets);
852 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700853 };
Chenbo Fengf434e862018-06-27 14:08:39 -0700854 res = mStatsMapA.iterateWithValue(printStatsInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700855 if (!isOk(res)) {
Chenbo Fengf434e862018-06-27 14:08:39 -0700856 dw.println("mStatsMapA print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700857 }
858
859 // Print TagStatsMap content.
Chenbo Fengf434e862018-06-27 14:08:39 -0700860 dumpBpfMap("mStatsMapB", dw, statsHeader);
861 res = mStatsMapB.iterateWithValue(printStatsInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700862 if (!isOk(res)) {
Chenbo Fengf434e862018-06-27 14:08:39 -0700863 dw.println("mStatsMapB print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700864 }
865
866 // Print ifaceIndexToNameMap content.
867 dumpBpfMap("mIfaceIndexNameMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700868 const auto printIfaceNameInfo = [&dw](const uint32_t& key, const IfaceValue& value,
869 const BpfMap<uint32_t, IfaceValue>&) {
870 const char* ifname = value.name;
871 dw.println("ifaceIndex=%u ifaceName=%s", key, ifname);
872 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700873 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700874 res = mIfaceIndexNameMap.iterateWithValue(printIfaceNameInfo);
875 if (!isOk(res)) {
876 dw.println("mIfaceIndexNameMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700877 }
878
879 // Print ifaceStatsMap content
880 std::string ifaceStatsHeader = StringPrintf("ifaceIndex ifaceName rxBytes rxPackets txBytes"
881 " txPackets");
882 dumpBpfMap("mIfaceStatsMap:", dw, ifaceStatsHeader);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700883 const auto printIfaceStatsInfo = [&dw, this](const uint32_t& key, const StatsValue& value,
884 const BpfMap<uint32_t, StatsValue>&) {
885 auto ifname = mIfaceIndexNameMap.readValue(key);
886 if (!isOk(ifname)) {
887 strlcpy(ifname.value().name, "unknown", sizeof(IfaceValue));
Chenbo Fengef297172018-03-26 10:53:33 -0700888 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700889 dw.println("%u %s %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, ifname.value().name,
890 value.rxBytes, value.rxPackets, value.txBytes, value.txPackets);
891 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700892 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700893 res = mIfaceStatsMap.iterateWithValue(printIfaceStatsInfo);
894 if (!isOk(res)) {
895 dw.println("mIfaceStatsMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700896 }
897
Chenbo Feng703798e2018-06-15 17:07:59 -0700898 dw.blankline();
Chenbo Fengef297172018-03-26 10:53:33 -0700899
Chenbo Fengf434e862018-06-27 14:08:39 -0700900 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Chenbo Feng703798e2018-06-15 17:07:59 -0700901 auto configuration = mConfigurationMap.readValue(key);
902 if (isOk(configuration)) {
Chenbo Fengf434e862018-06-27 14:08:39 -0700903 dw.println("current ownerMatch configuration: %d", configuration.value());
Chenbo Feng703798e2018-06-15 17:07:59 -0700904 } else {
Chenbo Fengf434e862018-06-27 14:08:39 -0700905 dw.println("mConfigurationMap read ownerMatch configure failed with error: %s",
906 configuration.status().msg().c_str());
907 }
908 key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
909 configuration = mConfigurationMap.readValue(key);
910 if (isOk(configuration)) {
911 dw.println("current statsMap configuration: %d", configuration.value());
912 } else {
913 dw.println("mConfigurationMap read stats map configure failed with error: %s",
914 configuration.status().msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700915 }
Chenbo Feng703798e2018-06-15 17:07:59 -0700916 dumpBpfMap("mUidOwnerMap", dw, "");
917 const auto printUidMatchInfo = [&dw](const uint32_t& key, const uint8_t& value,
918 const BpfMap<uint32_t, uint8_t>&) {
919 dw.println("%u %s", key, uidMatchTypeToString(value).c_str());
920 return netdutils::status::ok;
921 };
922 res = mUidOwnerMap.iterateWithValue(printUidMatchInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700923 if (!isOk(res)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700924 dw.println("mUidOwnerMap print end with error: %s", res.msg().c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700925 }
Chenbo Feng48eaed32018-12-26 17:40:21 -0800926 dumpBpfMap("mUidPermissionMap", dw, "");
927 const auto printUidPermissionInfo = [&dw](const uint32_t& key, const uint8_t& value,
928 const BpfMap<uint32_t, uint8_t>&) {
929 dw.println("%u %s", key, UidPermissionTypeToString(value).c_str());
930 return netdutils::status::ok;
931 };
932 res = mUidPermissionMap.iterateWithValue(printUidPermissionInfo);
933 if (!isOk(res)) {
934 dw.println("mUidPermissionMap print end with error: %s", res.msg().c_str());
935 }
936
937 dumpBpfMap("mPrivilegedUser", dw, "");
938 for (uid_t uid : mPrivilegedUser) {
939 dw.println("%u ALLOW_UPDATE_DEVICE_STATS", (uint32_t)uid);
940 }
Chenbo Fengef297172018-03-26 10:53:33 -0700941}
942
Chenbo Fengf2759682017-10-10 17:31:57 -0700943} // namespace net
944} // namespace android