blob: 74a80feeab658bdc628a0f572b6072110951a312 [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 Feng2142a2b2019-03-14 20:04:02 -070098 return ((uid == AID_ROOT) || (uid == AID_SYSTEM) ||
99 mPrivilegedUser.find(uid) != mPrivilegedUser.end());
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800100}
101
Chenbo Feng48eaed32018-12-26 17:40:21 -0800102const std::string UidPermissionTypeToString(uint8_t permission) {
103 std::string permissionType;
104 FLAG_MSG_TRANS(permissionType, ALLOW_SOCK_CREATE, permission);
105 FLAG_MSG_TRANS(permissionType, ALLOW_UPDATE_DEVICE_STATS, permission);
106 if (permission) {
107 return StringPrintf("Unknown permission: %u", permission);
108 }
109 return permissionType;
110}
111
Chenbo Feng49586642018-08-30 18:01:53 -0700112StatusOr<std::unique_ptr<NetlinkListenerInterface>> TrafficController::makeSkDestroyListener() {
Chenbo Feng116d0552017-12-04 17:25:19 -0800113 const auto& sys = sSyscalls.get();
114 ASSIGN_OR_RETURN(auto event, sys.eventfd(0, EFD_CLOEXEC));
115 const int domain = AF_NETLINK;
116 const int type = SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK;
117 const int protocol = NETLINK_INET_DIAG;
118 ASSIGN_OR_RETURN(auto sock, sys.socket(domain, type, protocol));
119
Lorenzo Colitti436efdb2018-07-26 17:20:57 +0900120 // TODO: if too many sockets are closed too quickly, we can overflow the socket buffer, and
121 // some entries in mCookieTagMap will not be freed. In order to fix this we would need to
122 // periodically dump all sockets and remove the tag entries for sockets that have been closed.
123 // For now, set a large-enough buffer that we can close hundreds of sockets without getting
124 // ENOBUFS and leaking mCookieTagMap entries.
125 int rcvbuf = 512 * 1024;
126 auto ret = sys.setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf));
127 if (!ret.ok()) {
128 ALOGW("Failed to set SkDestroyListener buffer size to %d: %s", rcvbuf, ret.msg().c_str());
129 }
130
Chenbo Feng116d0552017-12-04 17:25:19 -0800131 sockaddr_nl addr = {
132 .nl_family = AF_NETLINK,
133 .nl_groups = 1 << (SKNLGRP_INET_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET_UDP_DESTROY - 1) |
134 1 << (SKNLGRP_INET6_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET6_UDP_DESTROY - 1)};
135 RETURN_IF_NOT_OK(sys.bind(sock, addr));
136
137 const sockaddr_nl kernel = {.nl_family = AF_NETLINK};
138 RETURN_IF_NOT_OK(sys.connect(sock, kernel));
139
140 std::unique_ptr<NetlinkListenerInterface> listener =
Chenbo Feng46296702018-08-23 12:20:22 -0700141 std::make_unique<NetlinkListener>(std::move(event), std::move(sock), "SkDestroyListen");
Chenbo Feng116d0552017-12-04 17:25:19 -0800142
143 return listener;
144}
145
Chenbo Feng89c12f12018-03-21 10:29:18 -0700146Status changeOwnerAndMode(const char* path, gid_t group, const char* debugName, bool netdOnly) {
147 int ret = chown(path, AID_ROOT, group);
148 if (ret != 0) return statusFromErrno(errno, StringPrintf("change %s group failed", debugName));
149
150 if (netdOnly) {
151 ret = chmod(path, S_IRWXU);
152 } else {
153 // Allow both netd and system server to obtain map fd from the path.
154 // chmod doesn't grant permission to all processes in that group to
155 // read/write the bpf map. They still need correct sepolicy to
156 // read/write the map.
Chenbo Fengf434e862018-06-27 14:08:39 -0700157 ret = chmod(path, S_IRWXU | S_IRGRP | S_IWGRP);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700158 }
159 if (ret != 0) return statusFromErrno(errno, StringPrintf("change %s mode failed", debugName));
160 return netdutils::status::ok;
161}
162
Chenbo Feng47dd0732018-12-11 12:23:24 -0800163TrafficController::TrafficController() : mBpfLevel(getBpfSupportLevel()) {}
Chenbo Feng89c12f12018-03-21 10:29:18 -0700164
Chenbo Feng89c12f12018-03-21 10:29:18 -0700165Status TrafficController::initMaps() {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900166 std::lock_guard ownerMapGuard(mOwnerMatchMutex);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700167 RETURN_IF_NOT_OK(
168 mCookieTagMap.getOrCreate(COOKIE_UID_MAP_SIZE, COOKIE_TAG_MAP_PATH, BPF_MAP_TYPE_HASH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700169
170 RETURN_IF_NOT_OK(changeOwnerAndMode(COOKIE_TAG_MAP_PATH, AID_NET_BW_ACCT, "CookieTagMap",
171 false));
172
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700173 RETURN_IF_NOT_OK(mUidCounterSetMap.getOrCreate(UID_COUNTERSET_MAP_SIZE, UID_COUNTERSET_MAP_PATH,
174 BPF_MAP_TYPE_HASH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700175 RETURN_IF_NOT_OK(changeOwnerAndMode(UID_COUNTERSET_MAP_PATH, AID_NET_BW_ACCT,
176 "UidCounterSetMap", false));
177
Chenbo Fengf434e862018-06-27 14:08:39 -0700178 RETURN_IF_NOT_OK(mAppUidStatsMap.getOrCreate(APP_STATS_MAP_SIZE, APP_UID_STATS_MAP_PATH,
179 BPF_MAP_TYPE_HASH));
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700180 RETURN_IF_NOT_OK(
181 changeOwnerAndMode(APP_UID_STATS_MAP_PATH, AID_NET_BW_STATS, "AppUidStatsMap", false));
182
Chenbo Fengf434e862018-06-27 14:08:39 -0700183 RETURN_IF_NOT_OK(mStatsMapA.getOrCreate(STATS_MAP_SIZE, STATS_MAP_A_PATH, BPF_MAP_TYPE_HASH));
184 RETURN_IF_NOT_OK(changeOwnerAndMode(STATS_MAP_A_PATH, AID_NET_BW_STATS, "StatsMapA", false));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700185
Chenbo Fengf434e862018-06-27 14:08:39 -0700186 RETURN_IF_NOT_OK(mStatsMapB.getOrCreate(STATS_MAP_SIZE, STATS_MAP_B_PATH, BPF_MAP_TYPE_HASH));
187 RETURN_IF_NOT_OK(changeOwnerAndMode(STATS_MAP_B_PATH, AID_NET_BW_STATS, "StatsMapB", false));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700188
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700189 RETURN_IF_NOT_OK(mIfaceIndexNameMap.getOrCreate(IFACE_INDEX_NAME_MAP_SIZE,
190 IFACE_INDEX_NAME_MAP_PATH, BPF_MAP_TYPE_HASH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700191 RETURN_IF_NOT_OK(changeOwnerAndMode(IFACE_INDEX_NAME_MAP_PATH, AID_NET_BW_STATS,
192 "IfaceIndexNameMap", false));
193
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700194 RETURN_IF_NOT_OK(
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700195 mIfaceStatsMap.getOrCreate(IFACE_STATS_MAP_SIZE, IFACE_STATS_MAP_PATH, BPF_MAP_TYPE_HASH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700196 RETURN_IF_NOT_OK(changeOwnerAndMode(IFACE_STATS_MAP_PATH, AID_NET_BW_STATS, "IfaceStatsMap",
197 false));
Chenbo Feng95892f32018-06-07 14:52:02 -0700198
Chenbo Feng703798e2018-06-15 17:07:59 -0700199 RETURN_IF_NOT_OK(mConfigurationMap.getOrCreate(CONFIGURATION_MAP_SIZE, CONFIGURATION_MAP_PATH,
200 BPF_MAP_TYPE_HASH));
Chenbo Fengf434e862018-06-27 14:08:39 -0700201 RETURN_IF_NOT_OK(changeOwnerAndMode(CONFIGURATION_MAP_PATH, AID_NET_BW_STATS,
202 "ConfigurationMap", false));
Chenbo Feng703798e2018-06-15 17:07:59 -0700203 RETURN_IF_NOT_OK(
Chenbo Fengf434e862018-06-27 14:08:39 -0700204 mConfigurationMap.writeValue(UID_RULES_CONFIGURATION_KEY, DEFAULT_CONFIG, BPF_ANY));
205 RETURN_IF_NOT_OK(mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, SELECT_MAP_A,
206 BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700207
208 RETURN_IF_NOT_OK(
209 mUidOwnerMap.getOrCreate(UID_OWNER_MAP_SIZE, UID_OWNER_MAP_PATH, BPF_MAP_TYPE_HASH));
210 RETURN_IF_NOT_OK(changeOwnerAndMode(UID_OWNER_MAP_PATH, AID_ROOT, "UidOwnerMap", true));
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900211 RETURN_IF_NOT_OK(mUidOwnerMap.clear());
Chenbo Feng48eaed32018-12-26 17:40:21 -0800212 RETURN_IF_NOT_OK(mUidPermissionMap.getOrCreate(UID_OWNER_MAP_SIZE, UID_PERMISSION_MAP_PATH,
213 BPF_MAP_TYPE_HASH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700214 return netdutils::status::ok;
215}
216
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800217static Status attachProgramToCgroup(const char* programPath, const int cgroupFd,
218 bpf_attach_type type) {
219 unique_fd cgroupProg(bpfFdGet(programPath, 0));
220 if (cgroupProg == -1) {
221 int ret = errno;
222 ALOGE("Failed to get program from %s: %s", programPath, strerror(ret));
223 return statusFromErrno(ret, "cgroup program get failed");
224 }
225 if (android::bpf::attachProgram(type, cgroupProg, cgroupFd)) {
226 int ret = errno;
227 ALOGE("Program from %s attach failed: %s", programPath, strerror(ret));
228 return statusFromErrno(ret, "program attach failed");
229 }
230 return netdutils::status::ok;
231}
232
233static Status initPrograms() {
Suren Baghdasaryane072a3c2019-01-16 14:36:07 -0800234 std::string cg2_path;
235
236 if (!CgroupGetControllerPath(CGROUPV2_CONTROLLER_NAME, &cg2_path)) {
237 int ret = errno;
238 ALOGE("Failed to find cgroup v2 root");
239 return statusFromErrno(ret, "Failed to find cgroup v2 root");
240 }
241
242 unique_fd cg_fd(open(cg2_path.c_str(), O_DIRECTORY | O_RDONLY | O_CLOEXEC));
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800243 if (cg_fd == -1) {
244 int ret = errno;
245 ALOGE("Failed to open the cgroup directory: %s", strerror(ret));
246 return statusFromErrno(ret, "Open the cgroup directory failed");
247 }
248 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_EGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_EGRESS));
249 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_INGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_INGRESS));
Chenbo Fenga51f4fa2019-01-15 15:03:32 -0800250
251 // For the devices that support cgroup socket filter, the socket filter
252 // should be loaded successfully by bpfloader. So we attach the filter to
253 // cgroup if the program is pinned properly.
254 // TODO: delete the if statement once all devices should support cgroup
255 // socket filter (ie. the minimum kernel version required is 4.14).
256 if (!access(CGROUP_SOCKET_PROG_PATH, F_OK)) {
257 RETURN_IF_NOT_OK(
258 attachProgramToCgroup(CGROUP_SOCKET_PROG_PATH, cg_fd, BPF_CGROUP_INET_SOCK_CREATE));
259 }
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800260 return netdutils::status::ok;
261}
262
Chenbo Feng89c12f12018-03-21 10:29:18 -0700263Status TrafficController::start() {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800264 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800265 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700266 }
267
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900268 /* When netd restarts from a crash without total system reboot, the program
Chenbo Fengf2759682017-10-10 17:31:57 -0700269 * is still attached to the cgroup, detach it so the program can be freed
270 * and we can load and attach new program into the target cgroup.
271 *
272 * TODO: Scrape existing socket when run-time restart and clean up the map
273 * if the socket no longer exist
274 */
275
Chenbo Feng89c12f12018-03-21 10:29:18 -0700276 RETURN_IF_NOT_OK(initMaps());
Chenbo Feng7e974052018-02-28 22:57:21 -0800277
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800278 RETURN_IF_NOT_OK(initPrograms());
279
Chenbo Feng7e974052018-02-28 22:57:21 -0800280 // Fetch the list of currently-existing interfaces. At this point NetlinkHandler is
281 // already running, so it will call addInterface() when any new interface appears.
282 std::map<std::string, uint32_t> ifacePairs;
283 ASSIGN_OR_RETURN(ifacePairs, InterfaceController::getIfaceList());
284 for (const auto& ifacePair:ifacePairs) {
285 addInterface(ifacePair.first.c_str(), ifacePair.second);
286 }
287
Chenbo Feng116d0552017-12-04 17:25:19 -0800288 auto result = makeSkDestroyListener();
289 if (!isOk(result)) {
290 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
291 } else {
292 mSkDestroyListener = std::move(result.value());
293 }
294 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
295 const auto rxHandler = [this](const nlmsghdr&, const Slice msg) {
296 inet_diag_msg diagmsg = {};
297 if (extract(msg, diagmsg) < sizeof(inet_diag_msg)) {
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900298 ALOGE("Unrecognized netlink message: %s", toString(msg).c_str());
Chenbo Feng116d0552017-12-04 17:25:19 -0800299 return;
300 }
301 uint64_t sock_cookie = static_cast<uint64_t>(diagmsg.id.idiag_cookie[0]) |
302 (static_cast<uint64_t>(diagmsg.id.idiag_cookie[1]) << 32);
303
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900304 Status s = mCookieTagMap.deleteValue(sock_cookie);
Chenbo Feng1d4c5db2018-10-18 15:50:46 -0700305 if (!isOk(s) && s.code() != ENOENT) {
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900306 ALOGE("Failed to delete cookie %" PRIx64 ": %s", sock_cookie, toString(s).c_str());
307 return;
308 }
Chenbo Feng116d0552017-12-04 17:25:19 -0800309 };
310 expectOk(mSkDestroyListener->subscribe(kSockDiagMsgType, rxHandler));
311
312 // In case multiple netlink message comes in as a stream, we need to handle the rxDone message
313 // properly.
314 const auto rxDoneHandler = [](const nlmsghdr&, const Slice msg) {
315 // Ignore NLMSG_DONE messages
316 inet_diag_msg diagmsg = {};
317 extract(msg, diagmsg);
318 };
319 expectOk(mSkDestroyListener->subscribe(kSockDiagDoneMsgType, rxDoneHandler));
320
Chenbo Feng05393d82018-01-09 15:18:43 -0800321 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700322}
323
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800324int TrafficController::tagSocket(int sockFd, uint32_t tag, uid_t uid, uid_t callingUid) {
325 if (uid != callingUid && !hasUpdateDeviceStatsPermission(callingUid)) {
326 return -EPERM;
327 }
328
Chenbo Feng47dd0732018-12-11 12:23:24 -0800329 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700330 if (legacy_tagSocket(sockFd, tag, uid)) return -errno;
331 return 0;
332 }
Chenbo Feng33cc1032017-10-23 15:16:37 -0700333
Chenbo Fengf2759682017-10-10 17:31:57 -0700334 uint64_t sock_cookie = getSocketCookie(sockFd);
Chenbo Fengef1cab32018-04-13 19:50:49 -0700335 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
Chenbo Fengf2759682017-10-10 17:31:57 -0700336 UidTag newKey = {.uid = (uint32_t)uid, .tag = tag};
337
338 // Update the tag information of a socket to the cookieUidMap. Use BPF_ANY
339 // flag so it will insert a new entry to the map if that value doesn't exist
340 // yet. And update the tag if there is already a tag stored. Since the eBPF
341 // program in kernel only read this map, and is protected by rcu read lock. It
342 // should be fine to cocurrently update the map while eBPF program is running.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700343 Status res = mCookieTagMap.writeValue(sock_cookie, newKey, BPF_ANY);
344 if (!isOk(res)) {
345 ALOGE("Failed to tag the socket: %s, fd: %d", strerror(res.code()),
346 mCookieTagMap.getMap().get());
Chenbo Fengf2759682017-10-10 17:31:57 -0700347 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700348 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700349}
350
351int TrafficController::untagSocket(int sockFd) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800352 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700353 if (legacy_untagSocket(sockFd)) return -errno;
354 return 0;
355 }
Chenbo Fengf2759682017-10-10 17:31:57 -0700356 uint64_t sock_cookie = getSocketCookie(sockFd);
357
Chenbo Fengef1cab32018-04-13 19:50:49 -0700358 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700359 Status res = mCookieTagMap.deleteValue(sock_cookie);
360 if (!isOk(res)) {
361 ALOGE("Failed to untag socket: %s\n", strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700362 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700363 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700364}
365
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800366int TrafficController::setCounterSet(int counterSetNum, uid_t uid, uid_t callingUid) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700367 if (counterSetNum < 0 || counterSetNum >= OVERFLOW_COUNTERSET) return -EINVAL;
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800368
369 if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
370
Chenbo Feng47dd0732018-12-11 12:23:24 -0800371 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700372 if (legacy_setCounterSet(counterSetNum, uid)) return -errno;
373 return 0;
374 }
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800375
376 // The default counter set for all uid is 0, so deleting the current counterset for that uid
377 // will automatically set it to 0.
Chenbo Fengf2759682017-10-10 17:31:57 -0700378 if (counterSetNum == 0) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700379 Status res = mUidCounterSetMap.deleteValue(uid);
380 if (isOk(res) || (!isOk(res) && res.code() == ENOENT)) {
Chenbo Fengf2759682017-10-10 17:31:57 -0700381 return 0;
382 } else {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700383 ALOGE("Failed to delete the counterSet: %s\n", strerror(res.code()));
384 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700385 }
386 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700387 uint8_t tmpCounterSetNum = (uint8_t)counterSetNum;
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800388 Status res = mUidCounterSetMap.writeValue(uid, tmpCounterSetNum, BPF_ANY);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700389 if (!isOk(res)) {
390 ALOGE("Failed to set the counterSet: %s, fd: %d", strerror(res.code()),
391 mUidCounterSetMap.getMap().get());
392 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700393 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700394 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700395}
396
Chenbo Fengf434e862018-06-27 14:08:39 -0700397// This method only get called by system_server when an app get uinstalled, it
398// is called inside removeUidsLocked() while holding mStatsLock. So it is safe
399// to iterate and modify the stats maps.
Chenbo Fengb4a4fa12019-01-09 17:20:45 -0800400int TrafficController::deleteTagData(uint32_t tag, uid_t uid, uid_t callingUid) {
401 if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
402
Chenbo Feng47dd0732018-12-11 12:23:24 -0800403 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700404 if (legacy_deleteTagData(tag, uid)) return -errno;
405 return 0;
406 }
Chenbo Feng33cc1032017-10-23 15:16:37 -0700407
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800408 // First we go through the cookieTagMap to delete the target uid tag combination. Or delete all
Chenbo Fengef1cab32018-04-13 19:50:49 -0700409 // the tags related to the uid if the tag is 0.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700410 const auto deleteMatchedCookieEntries = [uid, tag](const uint64_t& key, const UidTag& value,
411 BpfMap<uint64_t, UidTag>& map) {
412 if (value.uid == uid && (value.tag == tag || tag == 0)) {
413 Status res = map.deleteValue(key);
414 if (isOk(res) || (res.code() == ENOENT)) {
415 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700416 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700417 ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s\n", key, strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700418 }
Chenbo Fengef1cab32018-04-13 19:50:49 -0700419 // Move forward to next cookie in the map.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700420 return netdutils::status::ok;
Chenbo Fengef1cab32018-04-13 19:50:49 -0700421 };
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900422 mCookieTagMap.iterateWithValue(deleteMatchedCookieEntries).ignoreError();
Chenbo Fengf2759682017-10-10 17:31:57 -0700423 // 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 -0700424 // combination. Or all tag stats under that uid if the target tag is 0.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700425 const auto deleteMatchedUidTagEntries = [uid, tag](const StatsKey& key,
426 BpfMap<StatsKey, StatsValue>& map) {
427 if (key.uid == uid && (key.tag == tag || tag == 0)) {
428 Status res = map.deleteValue(key);
429 if (isOk(res) || (res.code() == ENOENT)) {
Chenbo Fengef1cab32018-04-13 19:50:49 -0700430 //Entry is deleted, use the current key to get a new nextKey;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700431 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700432 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700433 ALOGE("Failed to delete data(uid=%u, tag=%u): %s\n", key.uid, key.tag,
434 strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700435 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700436 return netdutils::status::ok;
Chenbo Fengef1cab32018-04-13 19:50:49 -0700437 };
Chenbo Fengf434e862018-06-27 14:08:39 -0700438 mStatsMapB.iterate(deleteMatchedUidTagEntries).ignoreError();
439 mStatsMapA.iterate(deleteMatchedUidTagEntries).ignoreError();
Chenbo Fengf2759682017-10-10 17:31:57 -0700440 // 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 -0800441 // need to delete the stats stored in uidStatsMap and counterSet map.
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800442 if (tag != 0) return 0;
443
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700444 Status res = mUidCounterSetMap.deleteValue(uid);
445 if (!isOk(res) && res.code() != ENOENT) {
446 ALOGE("Failed to delete counterSet data(uid=%u, tag=%u): %s\n", uid, tag,
447 strerror(res.code()));
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800448 }
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700449
450 auto deleteAppUidStatsEntry = [uid](const uint32_t& key, BpfMap<uint32_t, StatsValue>& map) {
451 if (key == uid) {
452 Status res = map.deleteValue(key);
453 if (isOk(res) || (res.code() == ENOENT)) {
454 return netdutils::status::ok;
455 }
456 ALOGE("Failed to delete data(uid=%u): %s", key, strerror(res.code()));
457 }
458 return netdutils::status::ok;
459 };
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900460 mAppUidStatsMap.iterate(deleteAppUidStatsEntry).ignoreError();
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700461 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700462}
463
Chenbo Feng7e974052018-02-28 22:57:21 -0800464int TrafficController::addInterface(const char* name, uint32_t ifaceIndex) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800465 if (mBpfLevel == BpfLevel::NONE) return 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800466
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700467 IfaceValue iface;
Chenbo Feng7e974052018-02-28 22:57:21 -0800468 if (ifaceIndex == 0) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700469 ALOGE("Unknown interface %s(%d)", name, ifaceIndex);
Chenbo Feng7e974052018-02-28 22:57:21 -0800470 return -1;
471 }
472
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700473 strlcpy(iface.name, name, sizeof(IfaceValue));
474 Status res = mIfaceIndexNameMap.writeValue(ifaceIndex, iface, BPF_ANY);
475 if (!isOk(res)) {
476 ALOGE("Failed to add iface %s(%d): %s", name, ifaceIndex, strerror(res.code()));
477 return -res.code();
Chenbo Feng7e974052018-02-28 22:57:21 -0800478 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700479 return 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800480}
481
Chenbo Feng703798e2018-06-15 17:07:59 -0700482Status TrafficController::updateOwnerMapEntry(UidOwnerMatchType match, uid_t uid, FirewallRule rule,
483 FirewallType type) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900484 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700485 if ((rule == ALLOW && type == WHITELIST) || (rule == DENY && type == BLACKLIST)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700486 RETURN_IF_NOT_OK(addMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700487 } else if ((rule == ALLOW && type == BLACKLIST) || (rule == DENY && type == WHITELIST)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700488 RETURN_IF_NOT_OK(removeMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700489 } else {
490 //Cannot happen.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700491 return statusFromErrno(-EINVAL, "");
Chenbo Feng89c12f12018-03-21 10:29:18 -0700492 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700493 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700494}
495
Chenbo Feng703798e2018-06-15 17:07:59 -0700496UidOwnerMatchType TrafficController::jumpOpToMatch(BandwidthController::IptJumpOp jumpHandling) {
Chenbo Feng95892f32018-06-07 14:52:02 -0700497 switch (jumpHandling) {
498 case BandwidthController::IptJumpReject:
Chenbo Feng703798e2018-06-15 17:07:59 -0700499 return PENALTY_BOX_MATCH;
Chenbo Feng95892f32018-06-07 14:52:02 -0700500 case BandwidthController::IptJumpReturn:
Chenbo Feng703798e2018-06-15 17:07:59 -0700501 return HAPPY_BOX_MATCH;
Chenbo Feng95892f32018-06-07 14:52:02 -0700502 case BandwidthController::IptJumpNoAdd:
503 return NO_MATCH;
504 }
505}
506
Chenbo Feng703798e2018-06-15 17:07:59 -0700507Status TrafficController::removeMatch(BpfMap<uint32_t, uint8_t>& map, uint32_t uid,
508 UidOwnerMatchType match) {
509 auto oldMatch = map.readValue(uid);
510 if (isOk(oldMatch)) {
511 uint8_t newMatch = oldMatch.value() & ~match;
512 if (newMatch == 0) {
513 RETURN_IF_NOT_OK(map.deleteValue(uid));
514 } else {
515 RETURN_IF_NOT_OK(map.writeValue(uid, newMatch, BPF_ANY));
516 }
517 } else {
518 return statusFromErrno(ENOENT, StringPrintf("uid: %u does not exist in map", uid));
519 }
520 return netdutils::status::ok;
521}
522
523Status TrafficController::addMatch(BpfMap<uint32_t, uint8_t>& map, uint32_t uid,
524 UidOwnerMatchType match) {
525 auto oldMatch = map.readValue(uid);
526 if (isOk(oldMatch)) {
527 uint8_t newMatch = oldMatch.value() | match;
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900528 RETURN_IF_NOT_OK(map.writeValue((uint32_t) uid, newMatch, BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700529 } else {
530 RETURN_IF_NOT_OK(map.writeValue(uid, match, BPF_ANY));
531 }
532 return netdutils::status::ok;
533}
534
535Status TrafficController::updateUidOwnerMap(const std::vector<std::string>& appStrUids,
536 BandwidthController::IptJumpOp jumpHandling,
537 BandwidthController::IptOp op) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900538 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Feng703798e2018-06-15 17:07:59 -0700539 UidOwnerMatchType match = jumpOpToMatch(jumpHandling);
540 if (match == NO_MATCH) {
541 return statusFromErrno(
542 EINVAL, StringPrintf("invalid IptJumpOp: %d, command: %d", jumpHandling, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700543 }
544 for (const auto& appStrUid : appStrUids) {
545 char* endPtr;
546 long uid = strtol(appStrUid.c_str(), &endPtr, 10);
547 if ((errno == ERANGE && (uid == LONG_MAX || uid == LONG_MIN)) ||
548 (endPtr == appStrUid.c_str()) || (*endPtr != '\0')) {
549 return statusFromErrno(errno, "invalid uid string:" + appStrUid);
550 }
551
Chenbo Feng95892f32018-06-07 14:52:02 -0700552 if (op == BandwidthController::IptOpDelete) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700553 RETURN_IF_NOT_OK(removeMatch(mUidOwnerMap, uid, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700554 } else if (op == BandwidthController::IptOpInsert) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700555 RETURN_IF_NOT_OK(addMatch(mUidOwnerMap, uid, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700556 } else {
557 // Cannot happen.
Chenbo Feng703798e2018-06-15 17:07:59 -0700558 return statusFromErrno(EINVAL, StringPrintf("invalid IptOp: %d, %d", op, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700559 }
560 }
561 return netdutils::status::ok;
562}
563
Chenbo Feng89c12f12018-03-21 10:29:18 -0700564int TrafficController::changeUidOwnerRule(ChildChain chain, uid_t uid, FirewallRule rule,
565 FirewallType type) {
Chenbo Feng47dd0732018-12-11 12:23:24 -0800566 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Feng89c12f12018-03-21 10:29:18 -0700567 ALOGE("bpf is not set up, should use iptables rule");
568 return -ENOSYS;
569 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700570 Status res;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700571 switch (chain) {
572 case DOZABLE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700573 res = updateOwnerMapEntry(DOZABLE_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700574 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700575 case STANDBY:
Chenbo Feng703798e2018-06-15 17:07:59 -0700576 res = updateOwnerMapEntry(STANDBY_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700577 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700578 case POWERSAVE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700579 res = updateOwnerMapEntry(POWERSAVE_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700580 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700581 case NONE:
582 default:
583 return -EINVAL;
584 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700585 if (!isOk(res)) {
586 ALOGE("change uid(%u) rule of %d failed: %s, rule: %d, type: %d", uid, chain,
587 res.msg().c_str(), rule, type);
588 return -res.code();
589 }
590 return 0;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700591}
592
Chenbo Feng703798e2018-06-15 17:07:59 -0700593Status TrafficController::replaceUidsInMap(const UidOwnerMatchType match,
594 const std::vector<int32_t>& uids) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900595 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700596 std::set<int32_t> uidSet(uids.begin(), uids.end());
597 std::vector<uint32_t> uidsToDelete;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700598 auto getUidsToDelete = [&uidsToDelete, &uidSet](const uint32_t& key,
599 const BpfMap<uint32_t, uint8_t>&) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700600 if (uidSet.find((int32_t) key) == uidSet.end()) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700601 uidsToDelete.push_back(key);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700602 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700603 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700604 };
Chenbo Feng703798e2018-06-15 17:07:59 -0700605 RETURN_IF_NOT_OK(mUidOwnerMap.iterate(getUidsToDelete));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700606
607 for(auto uid : uidsToDelete) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700608 RETURN_IF_NOT_OK(removeMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700609 }
610
611 for (auto uid : uids) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700612 RETURN_IF_NOT_OK(addMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700613 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700614 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700615}
616
617int TrafficController::replaceUidOwnerMap(const std::string& name, bool isWhitelist,
618 const std::vector<int32_t>& uids) {
Chenbo Feng89c12f12018-03-21 10:29:18 -0700619 FirewallRule rule;
620 FirewallType type;
621 if (isWhitelist) {
622 type = WHITELIST;
623 rule = ALLOW;
624 } else {
625 type = BLACKLIST;
626 rule = DENY;
627 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700628 Status res;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700629 if (!name.compare(FirewallController::LOCAL_DOZABLE)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700630 res = replaceUidsInMap(DOZABLE_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700631 } else if (!name.compare(FirewallController::LOCAL_STANDBY)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700632 res = replaceUidsInMap(STANDBY_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700633 } else if (!name.compare(FirewallController::LOCAL_POWERSAVE)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700634 res = replaceUidsInMap(POWERSAVE_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700635 } else {
636 ALOGE("unknown chain name: %s", name.c_str());
637 return -EINVAL;
638 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700639 if (!isOk(res)) {
640 ALOGE("Failed to clean up chain: %s: %s", name.c_str(), res.msg().c_str());
641 return -res.code();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700642 }
643 return 0;
644}
645
646int TrafficController::toggleUidOwnerMap(ChildChain chain, bool enable) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900647 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Fengf434e862018-06-27 14:08:39 -0700648 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Chenbo Feng703798e2018-06-15 17:07:59 -0700649 auto oldConfiguration = mConfigurationMap.readValue(key);
650 if (!isOk(oldConfiguration)) {
651 ALOGE("Cannot read the old configuration from map: %s",
652 oldConfiguration.status().msg().c_str());
653 return -oldConfiguration.status().code();
654 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700655 Status res;
Chenbo Feng703798e2018-06-15 17:07:59 -0700656 BpfConfig newConfiguration;
657 uint8_t match;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700658 switch (chain) {
659 case DOZABLE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700660 match = DOZABLE_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700661 break;
662 case STANDBY:
Chenbo Feng703798e2018-06-15 17:07:59 -0700663 match = STANDBY_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700664 break;
665 case POWERSAVE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700666 match = POWERSAVE_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700667 break;
668 default:
669 return -EINVAL;
670 }
Chenbo Feng703798e2018-06-15 17:07:59 -0700671 newConfiguration =
672 enable ? (oldConfiguration.value() | match) : (oldConfiguration.value() & (~match));
673 res = mConfigurationMap.writeValue(key, newConfiguration, BPF_EXIST);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700674 if (!isOk(res)) {
675 ALOGE("Failed to toggleUidOwnerMap(%d): %s", chain, res.msg().c_str());
Chenbo Feng89c12f12018-03-21 10:29:18 -0700676 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700677 return -res.code();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700678}
679
Chenbo Feng47dd0732018-12-11 12:23:24 -0800680BpfLevel TrafficController::getBpfLevel() {
681 return mBpfLevel;
Chenbo Feng07d43fe2017-12-21 14:38:51 -0800682}
683
Chenbo Feng48eaed32018-12-26 17:40:21 -0800684void TrafficController::setPermissionForUids(int permission, const std::vector<uid_t>& uids) {
685 bool internet = (permission & INetd::PERMISSION_INTERNET);
686 bool privileged = (permission & INetd::PERMISSION_UPDATE_DEVICE_STATS);
687
688 for (uid_t uid : uids) {
689 if (internet) {
690 Status ret = mUidPermissionMap.writeValue(uid, ALLOW_SOCK_CREATE, BPF_ANY);
691 if (!isOk(ret)) {
692 ALOGE("Failed to grant INTERNET permission to uid: %u: %s", uid,
693 strerror(ret.code()));
694 }
695 } else {
696 Status ret = mUidPermissionMap.deleteValue(uid);
697 if (!isOk(ret) && ret.code() != ENOENT) {
698 ALOGE("Failed to revoke permission INTERNET from uid: %u: %s", uid,
699 strerror(ret.code()));
700 }
701 }
702
703 if (privileged) {
704 mPrivilegedUser.insert(uid);
705 } else {
706 mPrivilegedUser.erase(uid);
707 }
708 }
709}
710
Chenbo Fengef297172018-03-26 10:53:33 -0700711std::string getProgramStatus(const char *path) {
712 int ret = access(path, R_OK);
713 if (ret == 0) {
714 return StringPrintf("OK");
715 }
716 if (ret != 0 && errno == ENOENT) {
717 return StringPrintf("program is missing at: %s", path);
718 }
719 return StringPrintf("check Program %s error: %s", path, strerror(errno));
720}
721
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700722std::string getMapStatus(const base::unique_fd& map_fd, const char* path) {
Chenbo Fengef297172018-03-26 10:53:33 -0700723 if (map_fd.get() < 0) {
724 return StringPrintf("map fd lost");
725 }
726 if (access(path, F_OK) != 0) {
727 return StringPrintf("map not pinned to location: %s", path);
728 }
729 return StringPrintf("OK");
730}
731
Bernie Innocentia5161a02019-01-30 22:40:53 +0900732// NOLINTNEXTLINE(google-runtime-references): grandfathered pass by non-const reference
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900733void dumpBpfMap(const std::string& mapName, DumpWriter& dw, const std::string& header) {
Chenbo Fengef297172018-03-26 10:53:33 -0700734 dw.blankline();
735 dw.println("%s:", mapName.c_str());
Erik Klineb31fd692018-06-06 20:50:11 +0900736 if (!header.empty()) {
737 dw.println(header);
Chenbo Fengef297172018-03-26 10:53:33 -0700738 }
739}
740
741const String16 TrafficController::DUMP_KEYWORD = String16("trafficcontroller");
742
743void TrafficController::dump(DumpWriter& dw, bool verbose) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900744 std::lock_guard ownerMapGuard(mOwnerMatchMutex);
Erik Klineb31fd692018-06-06 20:50:11 +0900745 ScopedIndent indentTop(dw);
Chenbo Fengef297172018-03-26 10:53:33 -0700746 dw.println("TrafficController");
747
Erik Klineb31fd692018-06-06 20:50:11 +0900748 ScopedIndent indentPreBpfModule(dw);
Chenbo Feng47dd0732018-12-11 12:23:24 -0800749 dw.println("BPF module status: %s", BpfLevelToString(mBpfLevel).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700750
Chenbo Feng47dd0732018-12-11 12:23:24 -0800751 if (mBpfLevel == BpfLevel::NONE) {
Chenbo Fengef297172018-03-26 10:53:33 -0700752 return;
Erik Klineb31fd692018-06-06 20:50:11 +0900753 }
Chenbo Fengef297172018-03-26 10:53:33 -0700754
755 dw.blankline();
756 dw.println("mCookieTagMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700757 getMapStatus(mCookieTagMap.getMap(), COOKIE_TAG_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700758 dw.println("mUidCounterSetMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700759 getMapStatus(mUidCounterSetMap.getMap(), UID_COUNTERSET_MAP_PATH).c_str());
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700760 dw.println("mAppUidStatsMap status: %s",
761 getMapStatus(mAppUidStatsMap.getMap(), APP_UID_STATS_MAP_PATH).c_str());
Chenbo Fengf434e862018-06-27 14:08:39 -0700762 dw.println("mStatsMapA status: %s",
763 getMapStatus(mStatsMapA.getMap(), STATS_MAP_A_PATH).c_str());
764 dw.println("mStatsMapB status: %s",
765 getMapStatus(mStatsMapB.getMap(), STATS_MAP_B_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700766 dw.println("mIfaceIndexNameMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700767 getMapStatus(mIfaceIndexNameMap.getMap(), IFACE_INDEX_NAME_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700768 dw.println("mIfaceStatsMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700769 getMapStatus(mIfaceStatsMap.getMap(), IFACE_STATS_MAP_PATH).c_str());
Chenbo Feng703798e2018-06-15 17:07:59 -0700770 dw.println("mConfigurationMap status: %s",
771 getMapStatus(mConfigurationMap.getMap(), CONFIGURATION_MAP_PATH).c_str());
772 dw.println("mUidOwnerMap status: %s",
773 getMapStatus(mUidOwnerMap.getMap(), UID_OWNER_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700774
775 dw.blankline();
776 dw.println("Cgroup ingress program status: %s",
777 getProgramStatus(BPF_INGRESS_PROG_PATH).c_str());
778 dw.println("Cgroup egress program status: %s", getProgramStatus(BPF_EGRESS_PROG_PATH).c_str());
779 dw.println("xt_bpf ingress program status: %s",
780 getProgramStatus(XT_BPF_INGRESS_PROG_PATH).c_str());
781 dw.println("xt_bpf egress program status: %s",
782 getProgramStatus(XT_BPF_EGRESS_PROG_PATH).c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700783 dw.println("xt_bpf bandwidth whitelist program status: %s",
784 getProgramStatus(XT_BPF_WHITELIST_PROG_PATH).c_str());
785 dw.println("xt_bpf bandwidth blacklist program status: %s",
786 getProgramStatus(XT_BPF_BLACKLIST_PROG_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700787
Erik Klineb31fd692018-06-06 20:50:11 +0900788 if (!verbose) {
789 return;
790 }
Chenbo Fengef297172018-03-26 10:53:33 -0700791
792 dw.blankline();
793 dw.println("BPF map content:");
794
Erik Klineb31fd692018-06-06 20:50:11 +0900795 ScopedIndent indentForMapContent(dw);
Chenbo Fengef297172018-03-26 10:53:33 -0700796
797 // Print CookieTagMap content.
798 dumpBpfMap("mCookieTagMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700799 const auto printCookieTagInfo = [&dw](const uint64_t& key, const UidTag& value,
800 const BpfMap<uint64_t, UidTag>&) {
801 dw.println("cookie=%" PRIu64 " tag=0x%x uid=%u", key, value.tag, value.uid);
802 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700803 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700804 Status res = mCookieTagMap.iterateWithValue(printCookieTagInfo);
805 if (!isOk(res)) {
806 dw.println("mCookieTagMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700807 }
808
809 // Print UidCounterSetMap Content
810 dumpBpfMap("mUidCounterSetMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700811 const auto printUidInfo = [&dw](const uint32_t& key, const uint8_t& value,
812 const BpfMap<uint32_t, uint8_t>&) {
813 dw.println("%u %u", key, value);
814 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700815 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700816 res = mUidCounterSetMap.iterateWithValue(printUidInfo);
817 if (!isOk(res)) {
818 dw.println("mUidCounterSetMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700819 }
820
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700821 // Print AppUidStatsMap content
822 std::string appUidStatsHeader = StringPrintf("uid rxBytes rxPackets txBytes txPackets");
823 dumpBpfMap("mAppUidStatsMap:", dw, appUidStatsHeader);
824 auto printAppUidStatsInfo = [&dw](const uint32_t& key, const StatsValue& value,
825 const BpfMap<uint32_t, StatsValue>&) {
826 dw.println("%u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, value.rxBytes,
827 value.rxPackets, value.txBytes, value.txPackets);
828 return netdutils::status::ok;
829 };
830 res = mAppUidStatsMap.iterateWithValue(printAppUidStatsInfo);
831 if (!res.ok()) {
832 dw.println("mAppUidStatsMap print end with error: %s", res.msg().c_str());
833 }
834
Chenbo Fengef297172018-03-26 10:53:33 -0700835 // Print uidStatsMap content
836 std::string statsHeader = StringPrintf("ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes"
837 " rxPackets txBytes txPackets");
Chenbo Fengf434e862018-06-27 14:08:39 -0700838 dumpBpfMap("mStatsMapA", dw, statsHeader);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700839 const auto printStatsInfo = [&dw, this](const StatsKey& key, const StatsValue& value,
840 const BpfMap<StatsKey, StatsValue>&) {
841 uint32_t ifIndex = key.ifaceIndex;
842 auto ifname = mIfaceIndexNameMap.readValue(ifIndex);
843 if (!isOk(ifname)) {
844 strlcpy(ifname.value().name, "unknown", sizeof(IfaceValue));
Chenbo Fengef297172018-03-26 10:53:33 -0700845 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700846 dw.println("%u %s 0x%x %u %u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, ifIndex,
847 ifname.value().name, key.tag, key.uid, key.counterSet, value.rxBytes,
848 value.rxPackets, value.txBytes, value.txPackets);
849 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700850 };
Chenbo Fengf434e862018-06-27 14:08:39 -0700851 res = mStatsMapA.iterateWithValue(printStatsInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700852 if (!isOk(res)) {
Chenbo Fengf434e862018-06-27 14:08:39 -0700853 dw.println("mStatsMapA print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700854 }
855
856 // Print TagStatsMap content.
Chenbo Fengf434e862018-06-27 14:08:39 -0700857 dumpBpfMap("mStatsMapB", dw, statsHeader);
858 res = mStatsMapB.iterateWithValue(printStatsInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700859 if (!isOk(res)) {
Chenbo Fengf434e862018-06-27 14:08:39 -0700860 dw.println("mStatsMapB print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700861 }
862
863 // Print ifaceIndexToNameMap content.
864 dumpBpfMap("mIfaceIndexNameMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700865 const auto printIfaceNameInfo = [&dw](const uint32_t& key, const IfaceValue& value,
866 const BpfMap<uint32_t, IfaceValue>&) {
867 const char* ifname = value.name;
868 dw.println("ifaceIndex=%u ifaceName=%s", key, ifname);
869 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700870 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700871 res = mIfaceIndexNameMap.iterateWithValue(printIfaceNameInfo);
872 if (!isOk(res)) {
873 dw.println("mIfaceIndexNameMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700874 }
875
876 // Print ifaceStatsMap content
877 std::string ifaceStatsHeader = StringPrintf("ifaceIndex ifaceName rxBytes rxPackets txBytes"
878 " txPackets");
879 dumpBpfMap("mIfaceStatsMap:", dw, ifaceStatsHeader);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700880 const auto printIfaceStatsInfo = [&dw, this](const uint32_t& key, const StatsValue& value,
881 const BpfMap<uint32_t, StatsValue>&) {
882 auto ifname = mIfaceIndexNameMap.readValue(key);
883 if (!isOk(ifname)) {
884 strlcpy(ifname.value().name, "unknown", sizeof(IfaceValue));
Chenbo Fengef297172018-03-26 10:53:33 -0700885 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700886 dw.println("%u %s %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, ifname.value().name,
887 value.rxBytes, value.rxPackets, value.txBytes, value.txPackets);
888 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700889 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700890 res = mIfaceStatsMap.iterateWithValue(printIfaceStatsInfo);
891 if (!isOk(res)) {
892 dw.println("mIfaceStatsMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700893 }
894
Chenbo Feng703798e2018-06-15 17:07:59 -0700895 dw.blankline();
Chenbo Fengef297172018-03-26 10:53:33 -0700896
Chenbo Fengf434e862018-06-27 14:08:39 -0700897 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Chenbo Feng703798e2018-06-15 17:07:59 -0700898 auto configuration = mConfigurationMap.readValue(key);
899 if (isOk(configuration)) {
Chenbo Fengf434e862018-06-27 14:08:39 -0700900 dw.println("current ownerMatch configuration: %d", configuration.value());
Chenbo Feng703798e2018-06-15 17:07:59 -0700901 } else {
Chenbo Fengf434e862018-06-27 14:08:39 -0700902 dw.println("mConfigurationMap read ownerMatch configure failed with error: %s",
903 configuration.status().msg().c_str());
904 }
905 key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
906 configuration = mConfigurationMap.readValue(key);
907 if (isOk(configuration)) {
908 dw.println("current statsMap configuration: %d", configuration.value());
909 } else {
910 dw.println("mConfigurationMap read stats map configure failed with error: %s",
911 configuration.status().msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700912 }
Chenbo Feng703798e2018-06-15 17:07:59 -0700913 dumpBpfMap("mUidOwnerMap", dw, "");
914 const auto printUidMatchInfo = [&dw](const uint32_t& key, const uint8_t& value,
915 const BpfMap<uint32_t, uint8_t>&) {
916 dw.println("%u %s", key, uidMatchTypeToString(value).c_str());
917 return netdutils::status::ok;
918 };
919 res = mUidOwnerMap.iterateWithValue(printUidMatchInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700920 if (!isOk(res)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700921 dw.println("mUidOwnerMap print end with error: %s", res.msg().c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700922 }
Chenbo Feng48eaed32018-12-26 17:40:21 -0800923 dumpBpfMap("mUidPermissionMap", dw, "");
924 const auto printUidPermissionInfo = [&dw](const uint32_t& key, const uint8_t& value,
925 const BpfMap<uint32_t, uint8_t>&) {
926 dw.println("%u %s", key, UidPermissionTypeToString(value).c_str());
927 return netdutils::status::ok;
928 };
929 res = mUidPermissionMap.iterateWithValue(printUidPermissionInfo);
930 if (!isOk(res)) {
931 dw.println("mUidPermissionMap print end with error: %s", res.msg().c_str());
932 }
933
934 dumpBpfMap("mPrivilegedUser", dw, "");
935 for (uid_t uid : mPrivilegedUser) {
936 dw.println("%u ALLOW_UPDATE_DEVICE_STATS", (uint32_t)uid);
937 }
Chenbo Fengef297172018-03-26 10:53:33 -0700938}
939
Chenbo Fengf2759682017-10-10 17:31:57 -0700940} // namespace net
941} // namespace android