blob: 9aaa9fa2b5d2110afc8e7422de47f5fc3e21613c [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>
Chenbo Fengf2759682017-10-10 17:31:57 -070046#include "TrafficController.h"
Chenbo Feng4f6c2372018-04-26 10:37:55 -070047#include "bpf/BpfMap.h"
Chenbo Feng116d0552017-12-04 17:25:19 -080048
Chenbo Fengef297172018-03-26 10:53:33 -070049#include "DumpWriter.h"
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"
Chenbo Feng33cc1032017-10-23 15:16:37 -070053#include "qtaguid/qtaguid.h"
Chenbo Fengf2759682017-10-10 17:31:57 -070054
Bernie Innocenti7e25ec02018-07-02 19:32:17 +090055using namespace android::bpf; // NOLINT(google-build-using-namespace): grandfathered
Chenbo Fengf2759682017-10-10 17:31:57 -070056
57namespace android {
58namespace net {
59
Chenbo Fengc10a8a42017-12-15 13:56:33 -080060using base::StringPrintf;
61using base::unique_fd;
Chenbo Fengef297172018-03-26 10:53:33 -070062using base::Join;
Chenbo Feng116d0552017-12-04 17:25:19 -080063using netdutils::extract;
64using netdutils::Slice;
65using netdutils::sSyscalls;
Chenbo Fengc10a8a42017-12-15 13:56:33 -080066using netdutils::Status;
67using netdutils::statusFromErrno;
68using netdutils::StatusOr;
Chenbo Feng116d0552017-12-04 17:25:19 -080069using netdutils::status::ok;
Chenbo Fengc10a8a42017-12-15 13:56:33 -080070
Chenbo Feng116d0552017-12-04 17:25:19 -080071constexpr int kSockDiagMsgType = SOCK_DIAG_BY_FAMILY;
72constexpr int kSockDiagDoneMsgType = NLMSG_DONE;
73
Chenbo Feng48eaed32018-12-26 17:40:21 -080074#define FLAG_MSG_TRANS(result, flag, value) \
75 do { \
76 if (value & flag) { \
77 result.append(StringPrintf(" %s", #flag)); \
78 value &= ~flag; \
79 } \
Chenbo Feng703798e2018-06-15 17:07:59 -070080 } while (0)
81
82const std::string uidMatchTypeToString(uint8_t match) {
83 std::string matchType;
Chenbo Feng48eaed32018-12-26 17:40:21 -080084 FLAG_MSG_TRANS(matchType, HAPPY_BOX_MATCH, match);
85 FLAG_MSG_TRANS(matchType, PENALTY_BOX_MATCH, match);
86 FLAG_MSG_TRANS(matchType, DOZABLE_MATCH, match);
87 FLAG_MSG_TRANS(matchType, STANDBY_MATCH, match);
88 FLAG_MSG_TRANS(matchType, POWERSAVE_MATCH, match);
Chenbo Feng703798e2018-06-15 17:07:59 -070089 if (match) {
90 return StringPrintf("Unknown match: %u", match);
91 }
92 return matchType;
93}
94
Chenbo Feng48eaed32018-12-26 17:40:21 -080095const std::string UidPermissionTypeToString(uint8_t permission) {
96 std::string permissionType;
97 FLAG_MSG_TRANS(permissionType, ALLOW_SOCK_CREATE, permission);
98 FLAG_MSG_TRANS(permissionType, ALLOW_UPDATE_DEVICE_STATS, permission);
99 if (permission) {
100 return StringPrintf("Unknown permission: %u", permission);
101 }
102 return permissionType;
103}
104
Chenbo Feng49586642018-08-30 18:01:53 -0700105StatusOr<std::unique_ptr<NetlinkListenerInterface>> TrafficController::makeSkDestroyListener() {
Chenbo Feng116d0552017-12-04 17:25:19 -0800106 const auto& sys = sSyscalls.get();
107 ASSIGN_OR_RETURN(auto event, sys.eventfd(0, EFD_CLOEXEC));
108 const int domain = AF_NETLINK;
109 const int type = SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK;
110 const int protocol = NETLINK_INET_DIAG;
111 ASSIGN_OR_RETURN(auto sock, sys.socket(domain, type, protocol));
112
Lorenzo Colitti436efdb2018-07-26 17:20:57 +0900113 // TODO: if too many sockets are closed too quickly, we can overflow the socket buffer, and
114 // some entries in mCookieTagMap will not be freed. In order to fix this we would need to
115 // periodically dump all sockets and remove the tag entries for sockets that have been closed.
116 // For now, set a large-enough buffer that we can close hundreds of sockets without getting
117 // ENOBUFS and leaking mCookieTagMap entries.
118 int rcvbuf = 512 * 1024;
119 auto ret = sys.setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf));
120 if (!ret.ok()) {
121 ALOGW("Failed to set SkDestroyListener buffer size to %d: %s", rcvbuf, ret.msg().c_str());
122 }
123
Chenbo Feng116d0552017-12-04 17:25:19 -0800124 sockaddr_nl addr = {
125 .nl_family = AF_NETLINK,
126 .nl_groups = 1 << (SKNLGRP_INET_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET_UDP_DESTROY - 1) |
127 1 << (SKNLGRP_INET6_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET6_UDP_DESTROY - 1)};
128 RETURN_IF_NOT_OK(sys.bind(sock, addr));
129
130 const sockaddr_nl kernel = {.nl_family = AF_NETLINK};
131 RETURN_IF_NOT_OK(sys.connect(sock, kernel));
132
133 std::unique_ptr<NetlinkListenerInterface> listener =
Chenbo Feng46296702018-08-23 12:20:22 -0700134 std::make_unique<NetlinkListener>(std::move(event), std::move(sock), "SkDestroyListen");
Chenbo Feng116d0552017-12-04 17:25:19 -0800135
136 return listener;
137}
138
Chenbo Feng89c12f12018-03-21 10:29:18 -0700139Status changeOwnerAndMode(const char* path, gid_t group, const char* debugName, bool netdOnly) {
140 int ret = chown(path, AID_ROOT, group);
141 if (ret != 0) return statusFromErrno(errno, StringPrintf("change %s group failed", debugName));
142
143 if (netdOnly) {
144 ret = chmod(path, S_IRWXU);
145 } else {
146 // Allow both netd and system server to obtain map fd from the path.
147 // chmod doesn't grant permission to all processes in that group to
148 // read/write the bpf map. They still need correct sepolicy to
149 // read/write the map.
Chenbo Fengf434e862018-06-27 14:08:39 -0700150 ret = chmod(path, S_IRWXU | S_IRGRP | S_IWGRP);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700151 }
152 if (ret != 0) return statusFromErrno(errno, StringPrintf("change %s mode failed", debugName));
153 return netdutils::status::ok;
154}
155
156TrafficController::TrafficController() {
Chenbo Fengf43bf812017-12-15 18:27:22 -0800157 ebpfSupported = hasBpfSupport();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700158}
159
Chenbo Feng89c12f12018-03-21 10:29:18 -0700160Status TrafficController::initMaps() {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900161 std::lock_guard ownerMapGuard(mOwnerMatchMutex);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700162 RETURN_IF_NOT_OK(
163 mCookieTagMap.getOrCreate(COOKIE_UID_MAP_SIZE, COOKIE_TAG_MAP_PATH, BPF_MAP_TYPE_HASH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700164
165 RETURN_IF_NOT_OK(changeOwnerAndMode(COOKIE_TAG_MAP_PATH, AID_NET_BW_ACCT, "CookieTagMap",
166 false));
167
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700168 RETURN_IF_NOT_OK(mUidCounterSetMap.getOrCreate(UID_COUNTERSET_MAP_SIZE, UID_COUNTERSET_MAP_PATH,
169 BPF_MAP_TYPE_HASH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700170 RETURN_IF_NOT_OK(changeOwnerAndMode(UID_COUNTERSET_MAP_PATH, AID_NET_BW_ACCT,
171 "UidCounterSetMap", false));
172
Chenbo Fengf434e862018-06-27 14:08:39 -0700173 RETURN_IF_NOT_OK(mAppUidStatsMap.getOrCreate(APP_STATS_MAP_SIZE, APP_UID_STATS_MAP_PATH,
174 BPF_MAP_TYPE_HASH));
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700175 RETURN_IF_NOT_OK(
176 changeOwnerAndMode(APP_UID_STATS_MAP_PATH, AID_NET_BW_STATS, "AppUidStatsMap", false));
177
Chenbo Fengf434e862018-06-27 14:08:39 -0700178 RETURN_IF_NOT_OK(mStatsMapA.getOrCreate(STATS_MAP_SIZE, STATS_MAP_A_PATH, BPF_MAP_TYPE_HASH));
179 RETURN_IF_NOT_OK(changeOwnerAndMode(STATS_MAP_A_PATH, AID_NET_BW_STATS, "StatsMapA", false));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700180
Chenbo Fengf434e862018-06-27 14:08:39 -0700181 RETURN_IF_NOT_OK(mStatsMapB.getOrCreate(STATS_MAP_SIZE, STATS_MAP_B_PATH, BPF_MAP_TYPE_HASH));
182 RETURN_IF_NOT_OK(changeOwnerAndMode(STATS_MAP_B_PATH, AID_NET_BW_STATS, "StatsMapB", false));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700183
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700184 RETURN_IF_NOT_OK(mIfaceIndexNameMap.getOrCreate(IFACE_INDEX_NAME_MAP_SIZE,
185 IFACE_INDEX_NAME_MAP_PATH, BPF_MAP_TYPE_HASH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700186 RETURN_IF_NOT_OK(changeOwnerAndMode(IFACE_INDEX_NAME_MAP_PATH, AID_NET_BW_STATS,
187 "IfaceIndexNameMap", false));
188
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700189 RETURN_IF_NOT_OK(
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700190 mIfaceStatsMap.getOrCreate(IFACE_STATS_MAP_SIZE, IFACE_STATS_MAP_PATH, BPF_MAP_TYPE_HASH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700191 RETURN_IF_NOT_OK(changeOwnerAndMode(IFACE_STATS_MAP_PATH, AID_NET_BW_STATS, "IfaceStatsMap",
192 false));
Chenbo Feng95892f32018-06-07 14:52:02 -0700193
Chenbo Feng703798e2018-06-15 17:07:59 -0700194 RETURN_IF_NOT_OK(mConfigurationMap.getOrCreate(CONFIGURATION_MAP_SIZE, CONFIGURATION_MAP_PATH,
195 BPF_MAP_TYPE_HASH));
Chenbo Fengf434e862018-06-27 14:08:39 -0700196 RETURN_IF_NOT_OK(changeOwnerAndMode(CONFIGURATION_MAP_PATH, AID_NET_BW_STATS,
197 "ConfigurationMap", false));
Chenbo Feng703798e2018-06-15 17:07:59 -0700198 RETURN_IF_NOT_OK(
Chenbo Fengf434e862018-06-27 14:08:39 -0700199 mConfigurationMap.writeValue(UID_RULES_CONFIGURATION_KEY, DEFAULT_CONFIG, BPF_ANY));
200 RETURN_IF_NOT_OK(mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, SELECT_MAP_A,
201 BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700202
203 RETURN_IF_NOT_OK(
204 mUidOwnerMap.getOrCreate(UID_OWNER_MAP_SIZE, UID_OWNER_MAP_PATH, BPF_MAP_TYPE_HASH));
205 RETURN_IF_NOT_OK(changeOwnerAndMode(UID_OWNER_MAP_PATH, AID_ROOT, "UidOwnerMap", true));
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900206 RETURN_IF_NOT_OK(mUidOwnerMap.clear());
Chenbo Feng48eaed32018-12-26 17:40:21 -0800207 RETURN_IF_NOT_OK(mUidPermissionMap.getOrCreate(UID_OWNER_MAP_SIZE, UID_PERMISSION_MAP_PATH,
208 BPF_MAP_TYPE_HASH));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700209 return netdutils::status::ok;
210}
211
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800212static Status attachProgramToCgroup(const char* programPath, const int cgroupFd,
213 bpf_attach_type type) {
214 unique_fd cgroupProg(bpfFdGet(programPath, 0));
215 if (cgroupProg == -1) {
216 int ret = errno;
217 ALOGE("Failed to get program from %s: %s", programPath, strerror(ret));
218 return statusFromErrno(ret, "cgroup program get failed");
219 }
220 if (android::bpf::attachProgram(type, cgroupProg, cgroupFd)) {
221 int ret = errno;
222 ALOGE("Program from %s attach failed: %s", programPath, strerror(ret));
223 return statusFromErrno(ret, "program attach failed");
224 }
225 return netdutils::status::ok;
226}
227
228static Status initPrograms() {
229 unique_fd cg_fd(open(CGROUP_ROOT_PATH, O_DIRECTORY | O_RDONLY | O_CLOEXEC));
230 if (cg_fd == -1) {
231 int ret = errno;
232 ALOGE("Failed to open the cgroup directory: %s", strerror(ret));
233 return statusFromErrno(ret, "Open the cgroup directory failed");
234 }
235 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_EGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_EGRESS));
236 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_INGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_INGRESS));
237 return netdutils::status::ok;
238}
239
Chenbo Feng89c12f12018-03-21 10:29:18 -0700240Status TrafficController::start() {
241
Chenbo Fengf43bf812017-12-15 18:27:22 -0800242 if (!ebpfSupported) {
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800243 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700244 }
245
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900246 /* When netd restarts from a crash without total system reboot, the program
Chenbo Fengf2759682017-10-10 17:31:57 -0700247 * is still attached to the cgroup, detach it so the program can be freed
248 * and we can load and attach new program into the target cgroup.
249 *
250 * TODO: Scrape existing socket when run-time restart and clean up the map
251 * if the socket no longer exist
252 */
253
Chenbo Feng89c12f12018-03-21 10:29:18 -0700254 RETURN_IF_NOT_OK(initMaps());
Chenbo Feng7e974052018-02-28 22:57:21 -0800255
Chenbo Fengb2d213d2018-12-04 11:31:00 -0800256 RETURN_IF_NOT_OK(initPrograms());
257
Chenbo Feng7e974052018-02-28 22:57:21 -0800258 // Fetch the list of currently-existing interfaces. At this point NetlinkHandler is
259 // already running, so it will call addInterface() when any new interface appears.
260 std::map<std::string, uint32_t> ifacePairs;
261 ASSIGN_OR_RETURN(ifacePairs, InterfaceController::getIfaceList());
262 for (const auto& ifacePair:ifacePairs) {
263 addInterface(ifacePair.first.c_str(), ifacePair.second);
264 }
265
Chenbo Feng116d0552017-12-04 17:25:19 -0800266 auto result = makeSkDestroyListener();
267 if (!isOk(result)) {
268 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
269 } else {
270 mSkDestroyListener = std::move(result.value());
271 }
272 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
273 const auto rxHandler = [this](const nlmsghdr&, const Slice msg) {
274 inet_diag_msg diagmsg = {};
275 if (extract(msg, diagmsg) < sizeof(inet_diag_msg)) {
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900276 ALOGE("Unrecognized netlink message: %s", toString(msg).c_str());
Chenbo Feng116d0552017-12-04 17:25:19 -0800277 return;
278 }
279 uint64_t sock_cookie = static_cast<uint64_t>(diagmsg.id.idiag_cookie[0]) |
280 (static_cast<uint64_t>(diagmsg.id.idiag_cookie[1]) << 32);
281
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900282 Status s = mCookieTagMap.deleteValue(sock_cookie);
Chenbo Feng1d4c5db2018-10-18 15:50:46 -0700283 if (!isOk(s) && s.code() != ENOENT) {
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900284 ALOGE("Failed to delete cookie %" PRIx64 ": %s", sock_cookie, toString(s).c_str());
285 return;
286 }
Chenbo Feng116d0552017-12-04 17:25:19 -0800287 };
288 expectOk(mSkDestroyListener->subscribe(kSockDiagMsgType, rxHandler));
289
290 // In case multiple netlink message comes in as a stream, we need to handle the rxDone message
291 // properly.
292 const auto rxDoneHandler = [](const nlmsghdr&, const Slice msg) {
293 // Ignore NLMSG_DONE messages
294 inet_diag_msg diagmsg = {};
295 extract(msg, diagmsg);
296 };
297 expectOk(mSkDestroyListener->subscribe(kSockDiagDoneMsgType, rxDoneHandler));
298
Chenbo Feng05393d82018-01-09 15:18:43 -0800299 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700300}
301
Chenbo Fengf2759682017-10-10 17:31:57 -0700302int TrafficController::tagSocket(int sockFd, uint32_t tag, uid_t uid) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700303 if (!ebpfSupported) {
304 if (legacy_tagSocket(sockFd, tag, uid)) return -errno;
305 return 0;
306 }
Chenbo Feng33cc1032017-10-23 15:16:37 -0700307
Chenbo Fengf2759682017-10-10 17:31:57 -0700308 uint64_t sock_cookie = getSocketCookie(sockFd);
Chenbo Fengef1cab32018-04-13 19:50:49 -0700309 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
Chenbo Fengf2759682017-10-10 17:31:57 -0700310 UidTag newKey = {.uid = (uint32_t)uid, .tag = tag};
311
312 // Update the tag information of a socket to the cookieUidMap. Use BPF_ANY
313 // flag so it will insert a new entry to the map if that value doesn't exist
314 // yet. And update the tag if there is already a tag stored. Since the eBPF
315 // program in kernel only read this map, and is protected by rcu read lock. It
316 // should be fine to cocurrently update the map while eBPF program is running.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700317 Status res = mCookieTagMap.writeValue(sock_cookie, newKey, BPF_ANY);
318 if (!isOk(res)) {
319 ALOGE("Failed to tag the socket: %s, fd: %d", strerror(res.code()),
320 mCookieTagMap.getMap().get());
Chenbo Fengf2759682017-10-10 17:31:57 -0700321 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700322 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700323}
324
325int TrafficController::untagSocket(int sockFd) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700326 if (!ebpfSupported) {
327 if (legacy_untagSocket(sockFd)) return -errno;
328 return 0;
329 }
Chenbo Fengf2759682017-10-10 17:31:57 -0700330 uint64_t sock_cookie = getSocketCookie(sockFd);
331
Chenbo Fengef1cab32018-04-13 19:50:49 -0700332 if (sock_cookie == NONEXISTENT_COOKIE) return -errno;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700333 Status res = mCookieTagMap.deleteValue(sock_cookie);
334 if (!isOk(res)) {
335 ALOGE("Failed to untag socket: %s\n", strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700336 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700337 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700338}
339
340int TrafficController::setCounterSet(int counterSetNum, uid_t uid) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700341 if (counterSetNum < 0 || counterSetNum >= OVERFLOW_COUNTERSET) return -EINVAL;
342 Status res;
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700343 if (!ebpfSupported) {
344 if (legacy_setCounterSet(counterSetNum, uid)) return -errno;
345 return 0;
346 }
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800347
348 // The default counter set for all uid is 0, so deleting the current counterset for that uid
349 // will automatically set it to 0.
Chenbo Fengf2759682017-10-10 17:31:57 -0700350 if (counterSetNum == 0) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700351 Status res = mUidCounterSetMap.deleteValue(uid);
352 if (isOk(res) || (!isOk(res) && res.code() == ENOENT)) {
Chenbo Fengf2759682017-10-10 17:31:57 -0700353 return 0;
354 } else {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700355 ALOGE("Failed to delete the counterSet: %s\n", strerror(res.code()));
356 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700357 }
358 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700359 uint8_t tmpCounterSetNum = (uint8_t)counterSetNum;
360 res = mUidCounterSetMap.writeValue(uid, tmpCounterSetNum, BPF_ANY);
361 if (!isOk(res)) {
362 ALOGE("Failed to set the counterSet: %s, fd: %d", strerror(res.code()),
363 mUidCounterSetMap.getMap().get());
364 return -res.code();
Chenbo Fengf2759682017-10-10 17:31:57 -0700365 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700366 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700367}
368
Chenbo Fengf434e862018-06-27 14:08:39 -0700369// This method only get called by system_server when an app get uinstalled, it
370// is called inside removeUidsLocked() while holding mStatsLock. So it is safe
371// to iterate and modify the stats maps.
Chenbo Fengf2759682017-10-10 17:31:57 -0700372int TrafficController::deleteTagData(uint32_t tag, uid_t uid) {
Chenbo Fengbc6d4702018-04-11 18:27:19 -0700373 if (!ebpfSupported) {
374 if (legacy_deleteTagData(tag, uid)) return -errno;
375 return 0;
376 }
Chenbo Feng33cc1032017-10-23 15:16:37 -0700377
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800378 // First we go through the cookieTagMap to delete the target uid tag combination. Or delete all
Chenbo Fengef1cab32018-04-13 19:50:49 -0700379 // the tags related to the uid if the tag is 0.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700380 const auto deleteMatchedCookieEntries = [uid, tag](const uint64_t& key, const UidTag& value,
381 BpfMap<uint64_t, UidTag>& map) {
382 if (value.uid == uid && (value.tag == tag || tag == 0)) {
383 Status res = map.deleteValue(key);
384 if (isOk(res) || (res.code() == ENOENT)) {
385 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700386 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700387 ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s\n", key, strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700388 }
Chenbo Fengef1cab32018-04-13 19:50:49 -0700389 // Move forward to next cookie in the map.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700390 return netdutils::status::ok;
Chenbo Fengef1cab32018-04-13 19:50:49 -0700391 };
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900392 mCookieTagMap.iterateWithValue(deleteMatchedCookieEntries).ignoreError();
Chenbo Fengf2759682017-10-10 17:31:57 -0700393 // 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 -0700394 // combination. Or all tag stats under that uid if the target tag is 0.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700395 const auto deleteMatchedUidTagEntries = [uid, tag](const StatsKey& key,
396 BpfMap<StatsKey, StatsValue>& map) {
397 if (key.uid == uid && (key.tag == tag || tag == 0)) {
398 Status res = map.deleteValue(key);
399 if (isOk(res) || (res.code() == ENOENT)) {
Chenbo Fengef1cab32018-04-13 19:50:49 -0700400 //Entry is deleted, use the current key to get a new nextKey;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700401 return netdutils::status::ok;
Chenbo Fengf2759682017-10-10 17:31:57 -0700402 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700403 ALOGE("Failed to delete data(uid=%u, tag=%u): %s\n", key.uid, key.tag,
404 strerror(res.code()));
Chenbo Fengf2759682017-10-10 17:31:57 -0700405 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700406 return netdutils::status::ok;
Chenbo Fengef1cab32018-04-13 19:50:49 -0700407 };
Chenbo Fengf434e862018-06-27 14:08:39 -0700408 mStatsMapB.iterate(deleteMatchedUidTagEntries).ignoreError();
409 mStatsMapA.iterate(deleteMatchedUidTagEntries).ignoreError();
Chenbo Fengf2759682017-10-10 17:31:57 -0700410 // 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 -0800411 // need to delete the stats stored in uidStatsMap and counterSet map.
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800412 if (tag != 0) return 0;
413
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700414 Status res = mUidCounterSetMap.deleteValue(uid);
415 if (!isOk(res) && res.code() != ENOENT) {
416 ALOGE("Failed to delete counterSet data(uid=%u, tag=%u): %s\n", uid, tag,
417 strerror(res.code()));
Chenbo Fengc10a8a42017-12-15 13:56:33 -0800418 }
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700419
420 auto deleteAppUidStatsEntry = [uid](const uint32_t& key, BpfMap<uint32_t, StatsValue>& map) {
421 if (key == uid) {
422 Status res = map.deleteValue(key);
423 if (isOk(res) || (res.code() == ENOENT)) {
424 return netdutils::status::ok;
425 }
426 ALOGE("Failed to delete data(uid=%u): %s", key, strerror(res.code()));
427 }
428 return netdutils::status::ok;
429 };
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900430 mAppUidStatsMap.iterate(deleteAppUidStatsEntry).ignoreError();
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700431 return 0;
Chenbo Fengf2759682017-10-10 17:31:57 -0700432}
433
Chenbo Feng7e974052018-02-28 22:57:21 -0800434int TrafficController::addInterface(const char* name, uint32_t ifaceIndex) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700435 if (!ebpfSupported) return 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800436
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700437 IfaceValue iface;
Chenbo Feng7e974052018-02-28 22:57:21 -0800438 if (ifaceIndex == 0) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700439 ALOGE("Unknown interface %s(%d)", name, ifaceIndex);
Chenbo Feng7e974052018-02-28 22:57:21 -0800440 return -1;
441 }
442
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700443 strlcpy(iface.name, name, sizeof(IfaceValue));
444 Status res = mIfaceIndexNameMap.writeValue(ifaceIndex, iface, BPF_ANY);
445 if (!isOk(res)) {
446 ALOGE("Failed to add iface %s(%d): %s", name, ifaceIndex, strerror(res.code()));
447 return -res.code();
Chenbo Feng7e974052018-02-28 22:57:21 -0800448 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700449 return 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800450}
451
Chenbo Feng703798e2018-06-15 17:07:59 -0700452Status TrafficController::updateOwnerMapEntry(UidOwnerMatchType match, uid_t uid, FirewallRule rule,
453 FirewallType type) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900454 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700455 if ((rule == ALLOW && type == WHITELIST) || (rule == DENY && type == BLACKLIST)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700456 RETURN_IF_NOT_OK(addMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700457 } else if ((rule == ALLOW && type == BLACKLIST) || (rule == DENY && type == WHITELIST)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700458 RETURN_IF_NOT_OK(removeMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700459 } else {
460 //Cannot happen.
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700461 return statusFromErrno(-EINVAL, "");
Chenbo Feng89c12f12018-03-21 10:29:18 -0700462 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700463 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700464}
465
Chenbo Feng703798e2018-06-15 17:07:59 -0700466UidOwnerMatchType TrafficController::jumpOpToMatch(BandwidthController::IptJumpOp jumpHandling) {
Chenbo Feng95892f32018-06-07 14:52:02 -0700467 switch (jumpHandling) {
468 case BandwidthController::IptJumpReject:
Chenbo Feng703798e2018-06-15 17:07:59 -0700469 return PENALTY_BOX_MATCH;
Chenbo Feng95892f32018-06-07 14:52:02 -0700470 case BandwidthController::IptJumpReturn:
Chenbo Feng703798e2018-06-15 17:07:59 -0700471 return HAPPY_BOX_MATCH;
Chenbo Feng95892f32018-06-07 14:52:02 -0700472 case BandwidthController::IptJumpNoAdd:
473 return NO_MATCH;
474 }
475}
476
Chenbo Feng703798e2018-06-15 17:07:59 -0700477Status TrafficController::removeMatch(BpfMap<uint32_t, uint8_t>& map, uint32_t uid,
478 UidOwnerMatchType match) {
479 auto oldMatch = map.readValue(uid);
480 if (isOk(oldMatch)) {
481 uint8_t newMatch = oldMatch.value() & ~match;
482 if (newMatch == 0) {
483 RETURN_IF_NOT_OK(map.deleteValue(uid));
484 } else {
485 RETURN_IF_NOT_OK(map.writeValue(uid, newMatch, BPF_ANY));
486 }
487 } else {
488 return statusFromErrno(ENOENT, StringPrintf("uid: %u does not exist in map", uid));
489 }
490 return netdutils::status::ok;
491}
492
493Status TrafficController::addMatch(BpfMap<uint32_t, uint8_t>& map, uint32_t uid,
494 UidOwnerMatchType match) {
495 auto oldMatch = map.readValue(uid);
496 if (isOk(oldMatch)) {
497 uint8_t newMatch = oldMatch.value() | match;
Bernie Innocenti6f9fd902018-10-11 20:50:23 +0900498 RETURN_IF_NOT_OK(map.writeValue((uint32_t) uid, newMatch, BPF_ANY));
Chenbo Feng703798e2018-06-15 17:07:59 -0700499 } else {
500 RETURN_IF_NOT_OK(map.writeValue(uid, match, BPF_ANY));
501 }
502 return netdutils::status::ok;
503}
504
505Status TrafficController::updateUidOwnerMap(const std::vector<std::string>& appStrUids,
506 BandwidthController::IptJumpOp jumpHandling,
507 BandwidthController::IptOp op) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900508 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Feng703798e2018-06-15 17:07:59 -0700509 UidOwnerMatchType match = jumpOpToMatch(jumpHandling);
510 if (match == NO_MATCH) {
511 return statusFromErrno(
512 EINVAL, StringPrintf("invalid IptJumpOp: %d, command: %d", jumpHandling, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700513 }
514 for (const auto& appStrUid : appStrUids) {
515 char* endPtr;
516 long uid = strtol(appStrUid.c_str(), &endPtr, 10);
517 if ((errno == ERANGE && (uid == LONG_MAX || uid == LONG_MIN)) ||
518 (endPtr == appStrUid.c_str()) || (*endPtr != '\0')) {
519 return statusFromErrno(errno, "invalid uid string:" + appStrUid);
520 }
521
Chenbo Feng95892f32018-06-07 14:52:02 -0700522 if (op == BandwidthController::IptOpDelete) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700523 RETURN_IF_NOT_OK(removeMatch(mUidOwnerMap, uid, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700524 } else if (op == BandwidthController::IptOpInsert) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700525 RETURN_IF_NOT_OK(addMatch(mUidOwnerMap, uid, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700526 } else {
527 // Cannot happen.
Chenbo Feng703798e2018-06-15 17:07:59 -0700528 return statusFromErrno(EINVAL, StringPrintf("invalid IptOp: %d, %d", op, match));
Chenbo Feng95892f32018-06-07 14:52:02 -0700529 }
530 }
531 return netdutils::status::ok;
532}
533
Chenbo Feng89c12f12018-03-21 10:29:18 -0700534int TrafficController::changeUidOwnerRule(ChildChain chain, uid_t uid, FirewallRule rule,
535 FirewallType type) {
Chenbo Feng89c12f12018-03-21 10:29:18 -0700536 if (!ebpfSupported) {
537 ALOGE("bpf is not set up, should use iptables rule");
538 return -ENOSYS;
539 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700540 Status res;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700541 switch (chain) {
542 case DOZABLE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700543 res = updateOwnerMapEntry(DOZABLE_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700544 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700545 case STANDBY:
Chenbo Feng703798e2018-06-15 17:07:59 -0700546 res = updateOwnerMapEntry(STANDBY_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700547 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700548 case POWERSAVE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700549 res = updateOwnerMapEntry(POWERSAVE_MATCH, uid, rule, type);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700550 break;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700551 case NONE:
552 default:
553 return -EINVAL;
554 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700555 if (!isOk(res)) {
556 ALOGE("change uid(%u) rule of %d failed: %s, rule: %d, type: %d", uid, chain,
557 res.msg().c_str(), rule, type);
558 return -res.code();
559 }
560 return 0;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700561}
562
Chenbo Feng703798e2018-06-15 17:07:59 -0700563Status TrafficController::replaceUidsInMap(const UidOwnerMatchType match,
564 const std::vector<int32_t>& uids) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900565 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700566 std::set<int32_t> uidSet(uids.begin(), uids.end());
567 std::vector<uint32_t> uidsToDelete;
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700568 auto getUidsToDelete = [&uidsToDelete, &uidSet](const uint32_t& key,
569 const BpfMap<uint32_t, uint8_t>&) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700570 if (uidSet.find((int32_t) key) == uidSet.end()) {
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700571 uidsToDelete.push_back(key);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700572 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700573 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700574 };
Chenbo Feng703798e2018-06-15 17:07:59 -0700575 RETURN_IF_NOT_OK(mUidOwnerMap.iterate(getUidsToDelete));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700576
577 for(auto uid : uidsToDelete) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700578 RETURN_IF_NOT_OK(removeMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700579 }
580
581 for (auto uid : uids) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700582 RETURN_IF_NOT_OK(addMatch(mUidOwnerMap, uid, match));
Chenbo Feng89c12f12018-03-21 10:29:18 -0700583 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700584 return netdutils::status::ok;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700585}
586
587int TrafficController::replaceUidOwnerMap(const std::string& name, bool isWhitelist,
588 const std::vector<int32_t>& uids) {
Chenbo Feng89c12f12018-03-21 10:29:18 -0700589 FirewallRule rule;
590 FirewallType type;
591 if (isWhitelist) {
592 type = WHITELIST;
593 rule = ALLOW;
594 } else {
595 type = BLACKLIST;
596 rule = DENY;
597 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700598 Status res;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700599 if (!name.compare(FirewallController::LOCAL_DOZABLE)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700600 res = replaceUidsInMap(DOZABLE_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700601 } else if (!name.compare(FirewallController::LOCAL_STANDBY)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700602 res = replaceUidsInMap(STANDBY_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700603 } else if (!name.compare(FirewallController::LOCAL_POWERSAVE)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700604 res = replaceUidsInMap(POWERSAVE_MATCH, uids);
Chenbo Feng89c12f12018-03-21 10:29:18 -0700605 } else {
606 ALOGE("unknown chain name: %s", name.c_str());
607 return -EINVAL;
608 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700609 if (!isOk(res)) {
610 ALOGE("Failed to clean up chain: %s: %s", name.c_str(), res.msg().c_str());
611 return -res.code();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700612 }
613 return 0;
614}
615
616int TrafficController::toggleUidOwnerMap(ChildChain chain, bool enable) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900617 std::lock_guard guard(mOwnerMatchMutex);
Chenbo Fengf434e862018-06-27 14:08:39 -0700618 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Chenbo Feng703798e2018-06-15 17:07:59 -0700619 auto oldConfiguration = mConfigurationMap.readValue(key);
620 if (!isOk(oldConfiguration)) {
621 ALOGE("Cannot read the old configuration from map: %s",
622 oldConfiguration.status().msg().c_str());
623 return -oldConfiguration.status().code();
624 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700625 Status res;
Chenbo Feng703798e2018-06-15 17:07:59 -0700626 BpfConfig newConfiguration;
627 uint8_t match;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700628 switch (chain) {
629 case DOZABLE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700630 match = DOZABLE_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700631 break;
632 case STANDBY:
Chenbo Feng703798e2018-06-15 17:07:59 -0700633 match = STANDBY_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700634 break;
635 case POWERSAVE:
Chenbo Feng703798e2018-06-15 17:07:59 -0700636 match = POWERSAVE_MATCH;
Chenbo Feng89c12f12018-03-21 10:29:18 -0700637 break;
638 default:
639 return -EINVAL;
640 }
Chenbo Feng703798e2018-06-15 17:07:59 -0700641 newConfiguration =
642 enable ? (oldConfiguration.value() | match) : (oldConfiguration.value() & (~match));
643 res = mConfigurationMap.writeValue(key, newConfiguration, BPF_EXIST);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700644 if (!isOk(res)) {
645 ALOGE("Failed to toggleUidOwnerMap(%d): %s", chain, res.msg().c_str());
Chenbo Feng89c12f12018-03-21 10:29:18 -0700646 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700647 return -res.code();
Chenbo Feng89c12f12018-03-21 10:29:18 -0700648}
649
Chenbo Feng07d43fe2017-12-21 14:38:51 -0800650bool TrafficController::checkBpfStatsEnable() {
651 return ebpfSupported;
652}
653
Chenbo Feng48eaed32018-12-26 17:40:21 -0800654void TrafficController::setPermissionForUids(int permission, const std::vector<uid_t>& uids) {
655 bool internet = (permission & INetd::PERMISSION_INTERNET);
656 bool privileged = (permission & INetd::PERMISSION_UPDATE_DEVICE_STATS);
657
658 for (uid_t uid : uids) {
659 if (internet) {
660 Status ret = mUidPermissionMap.writeValue(uid, ALLOW_SOCK_CREATE, BPF_ANY);
661 if (!isOk(ret)) {
662 ALOGE("Failed to grant INTERNET permission to uid: %u: %s", uid,
663 strerror(ret.code()));
664 }
665 } else {
666 Status ret = mUidPermissionMap.deleteValue(uid);
667 if (!isOk(ret) && ret.code() != ENOENT) {
668 ALOGE("Failed to revoke permission INTERNET from uid: %u: %s", uid,
669 strerror(ret.code()));
670 }
671 }
672
673 if (privileged) {
674 mPrivilegedUser.insert(uid);
675 } else {
676 mPrivilegedUser.erase(uid);
677 }
678 }
679}
680
Chenbo Fengef297172018-03-26 10:53:33 -0700681std::string getProgramStatus(const char *path) {
682 int ret = access(path, R_OK);
683 if (ret == 0) {
684 return StringPrintf("OK");
685 }
686 if (ret != 0 && errno == ENOENT) {
687 return StringPrintf("program is missing at: %s", path);
688 }
689 return StringPrintf("check Program %s error: %s", path, strerror(errno));
690}
691
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700692std::string getMapStatus(const base::unique_fd& map_fd, const char* path) {
Chenbo Fengef297172018-03-26 10:53:33 -0700693 if (map_fd.get() < 0) {
694 return StringPrintf("map fd lost");
695 }
696 if (access(path, F_OK) != 0) {
697 return StringPrintf("map not pinned to location: %s", path);
698 }
699 return StringPrintf("OK");
700}
701
Bernie Innocenti15bb55c2018-06-03 16:19:51 +0900702void dumpBpfMap(const std::string& mapName, DumpWriter& dw, const std::string& header) {
Chenbo Fengef297172018-03-26 10:53:33 -0700703 dw.blankline();
704 dw.println("%s:", mapName.c_str());
Erik Klineb31fd692018-06-06 20:50:11 +0900705 if (!header.empty()) {
706 dw.println(header);
Chenbo Fengef297172018-03-26 10:53:33 -0700707 }
708}
709
710const String16 TrafficController::DUMP_KEYWORD = String16("trafficcontroller");
711
712void TrafficController::dump(DumpWriter& dw, bool verbose) {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900713 std::lock_guard ownerMapGuard(mOwnerMatchMutex);
Erik Klineb31fd692018-06-06 20:50:11 +0900714 ScopedIndent indentTop(dw);
Chenbo Fengef297172018-03-26 10:53:33 -0700715 dw.println("TrafficController");
716
Erik Klineb31fd692018-06-06 20:50:11 +0900717 ScopedIndent indentPreBpfModule(dw);
Chenbo Fengef297172018-03-26 10:53:33 -0700718 dw.println("BPF module status: %s", ebpfSupported? "ON" : "OFF");
719
Erik Klineb31fd692018-06-06 20:50:11 +0900720 if (!ebpfSupported) {
Chenbo Fengef297172018-03-26 10:53:33 -0700721 return;
Erik Klineb31fd692018-06-06 20:50:11 +0900722 }
Chenbo Fengef297172018-03-26 10:53:33 -0700723
724 dw.blankline();
725 dw.println("mCookieTagMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700726 getMapStatus(mCookieTagMap.getMap(), COOKIE_TAG_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700727 dw.println("mUidCounterSetMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700728 getMapStatus(mUidCounterSetMap.getMap(), UID_COUNTERSET_MAP_PATH).c_str());
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700729 dw.println("mAppUidStatsMap status: %s",
730 getMapStatus(mAppUidStatsMap.getMap(), APP_UID_STATS_MAP_PATH).c_str());
Chenbo Fengf434e862018-06-27 14:08:39 -0700731 dw.println("mStatsMapA status: %s",
732 getMapStatus(mStatsMapA.getMap(), STATS_MAP_A_PATH).c_str());
733 dw.println("mStatsMapB status: %s",
734 getMapStatus(mStatsMapB.getMap(), STATS_MAP_B_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700735 dw.println("mIfaceIndexNameMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700736 getMapStatus(mIfaceIndexNameMap.getMap(), IFACE_INDEX_NAME_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700737 dw.println("mIfaceStatsMap status: %s",
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700738 getMapStatus(mIfaceStatsMap.getMap(), IFACE_STATS_MAP_PATH).c_str());
Chenbo Feng703798e2018-06-15 17:07:59 -0700739 dw.println("mConfigurationMap status: %s",
740 getMapStatus(mConfigurationMap.getMap(), CONFIGURATION_MAP_PATH).c_str());
741 dw.println("mUidOwnerMap status: %s",
742 getMapStatus(mUidOwnerMap.getMap(), UID_OWNER_MAP_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700743
744 dw.blankline();
745 dw.println("Cgroup ingress program status: %s",
746 getProgramStatus(BPF_INGRESS_PROG_PATH).c_str());
747 dw.println("Cgroup egress program status: %s", getProgramStatus(BPF_EGRESS_PROG_PATH).c_str());
748 dw.println("xt_bpf ingress program status: %s",
749 getProgramStatus(XT_BPF_INGRESS_PROG_PATH).c_str());
750 dw.println("xt_bpf egress program status: %s",
751 getProgramStatus(XT_BPF_EGRESS_PROG_PATH).c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700752 dw.println("xt_bpf bandwidth whitelist program status: %s",
753 getProgramStatus(XT_BPF_WHITELIST_PROG_PATH).c_str());
754 dw.println("xt_bpf bandwidth blacklist program status: %s",
755 getProgramStatus(XT_BPF_BLACKLIST_PROG_PATH).c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700756
Erik Klineb31fd692018-06-06 20:50:11 +0900757 if (!verbose) {
758 return;
759 }
Chenbo Fengef297172018-03-26 10:53:33 -0700760
761 dw.blankline();
762 dw.println("BPF map content:");
763
Erik Klineb31fd692018-06-06 20:50:11 +0900764 ScopedIndent indentForMapContent(dw);
Chenbo Fengef297172018-03-26 10:53:33 -0700765
766 // Print CookieTagMap content.
767 dumpBpfMap("mCookieTagMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700768 const auto printCookieTagInfo = [&dw](const uint64_t& key, const UidTag& value,
769 const BpfMap<uint64_t, UidTag>&) {
770 dw.println("cookie=%" PRIu64 " tag=0x%x uid=%u", key, value.tag, value.uid);
771 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700772 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700773 Status res = mCookieTagMap.iterateWithValue(printCookieTagInfo);
774 if (!isOk(res)) {
775 dw.println("mCookieTagMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700776 }
777
778 // Print UidCounterSetMap Content
779 dumpBpfMap("mUidCounterSetMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700780 const auto printUidInfo = [&dw](const uint32_t& key, const uint8_t& value,
781 const BpfMap<uint32_t, uint8_t>&) {
782 dw.println("%u %u", key, value);
783 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700784 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700785 res = mUidCounterSetMap.iterateWithValue(printUidInfo);
786 if (!isOk(res)) {
787 dw.println("mUidCounterSetMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700788 }
789
Chenbo Fengbc4a15f2018-05-11 19:15:15 -0700790 // Print AppUidStatsMap content
791 std::string appUidStatsHeader = StringPrintf("uid rxBytes rxPackets txBytes txPackets");
792 dumpBpfMap("mAppUidStatsMap:", dw, appUidStatsHeader);
793 auto printAppUidStatsInfo = [&dw](const uint32_t& key, const StatsValue& value,
794 const BpfMap<uint32_t, StatsValue>&) {
795 dw.println("%u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, value.rxBytes,
796 value.rxPackets, value.txBytes, value.txPackets);
797 return netdutils::status::ok;
798 };
799 res = mAppUidStatsMap.iterateWithValue(printAppUidStatsInfo);
800 if (!res.ok()) {
801 dw.println("mAppUidStatsMap print end with error: %s", res.msg().c_str());
802 }
803
Chenbo Fengef297172018-03-26 10:53:33 -0700804 // Print uidStatsMap content
805 std::string statsHeader = StringPrintf("ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes"
806 " rxPackets txBytes txPackets");
Chenbo Fengf434e862018-06-27 14:08:39 -0700807 dumpBpfMap("mStatsMapA", dw, statsHeader);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700808 const auto printStatsInfo = [&dw, this](const StatsKey& key, const StatsValue& value,
809 const BpfMap<StatsKey, StatsValue>&) {
810 uint32_t ifIndex = key.ifaceIndex;
811 auto ifname = mIfaceIndexNameMap.readValue(ifIndex);
812 if (!isOk(ifname)) {
813 strlcpy(ifname.value().name, "unknown", sizeof(IfaceValue));
Chenbo Fengef297172018-03-26 10:53:33 -0700814 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700815 dw.println("%u %s 0x%x %u %u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, ifIndex,
816 ifname.value().name, key.tag, key.uid, key.counterSet, value.rxBytes,
817 value.rxPackets, value.txBytes, value.txPackets);
818 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700819 };
Chenbo Fengf434e862018-06-27 14:08:39 -0700820 res = mStatsMapA.iterateWithValue(printStatsInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700821 if (!isOk(res)) {
Chenbo Fengf434e862018-06-27 14:08:39 -0700822 dw.println("mStatsMapA print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700823 }
824
825 // Print TagStatsMap content.
Chenbo Fengf434e862018-06-27 14:08:39 -0700826 dumpBpfMap("mStatsMapB", dw, statsHeader);
827 res = mStatsMapB.iterateWithValue(printStatsInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700828 if (!isOk(res)) {
Chenbo Fengf434e862018-06-27 14:08:39 -0700829 dw.println("mStatsMapB print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700830 }
831
832 // Print ifaceIndexToNameMap content.
833 dumpBpfMap("mIfaceIndexNameMap", dw, "");
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700834 const auto printIfaceNameInfo = [&dw](const uint32_t& key, const IfaceValue& value,
835 const BpfMap<uint32_t, IfaceValue>&) {
836 const char* ifname = value.name;
837 dw.println("ifaceIndex=%u ifaceName=%s", key, ifname);
838 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700839 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700840 res = mIfaceIndexNameMap.iterateWithValue(printIfaceNameInfo);
841 if (!isOk(res)) {
842 dw.println("mIfaceIndexNameMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700843 }
844
845 // Print ifaceStatsMap content
846 std::string ifaceStatsHeader = StringPrintf("ifaceIndex ifaceName rxBytes rxPackets txBytes"
847 " txPackets");
848 dumpBpfMap("mIfaceStatsMap:", dw, ifaceStatsHeader);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700849 const auto printIfaceStatsInfo = [&dw, this](const uint32_t& key, const StatsValue& value,
850 const BpfMap<uint32_t, StatsValue>&) {
851 auto ifname = mIfaceIndexNameMap.readValue(key);
852 if (!isOk(ifname)) {
853 strlcpy(ifname.value().name, "unknown", sizeof(IfaceValue));
Chenbo Fengef297172018-03-26 10:53:33 -0700854 }
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700855 dw.println("%u %s %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, ifname.value().name,
856 value.rxBytes, value.rxPackets, value.txBytes, value.txPackets);
857 return netdutils::status::ok;
Chenbo Fengef297172018-03-26 10:53:33 -0700858 };
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700859 res = mIfaceStatsMap.iterateWithValue(printIfaceStatsInfo);
860 if (!isOk(res)) {
861 dw.println("mIfaceStatsMap print end with error: %s", res.msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700862 }
863
Chenbo Feng703798e2018-06-15 17:07:59 -0700864 dw.blankline();
Chenbo Fengef297172018-03-26 10:53:33 -0700865
Chenbo Fengf434e862018-06-27 14:08:39 -0700866 uint32_t key = UID_RULES_CONFIGURATION_KEY;
Chenbo Feng703798e2018-06-15 17:07:59 -0700867 auto configuration = mConfigurationMap.readValue(key);
868 if (isOk(configuration)) {
Chenbo Fengf434e862018-06-27 14:08:39 -0700869 dw.println("current ownerMatch configuration: %d", configuration.value());
Chenbo Feng703798e2018-06-15 17:07:59 -0700870 } else {
Chenbo Fengf434e862018-06-27 14:08:39 -0700871 dw.println("mConfigurationMap read ownerMatch configure failed with error: %s",
872 configuration.status().msg().c_str());
873 }
874 key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
875 configuration = mConfigurationMap.readValue(key);
876 if (isOk(configuration)) {
877 dw.println("current statsMap configuration: %d", configuration.value());
878 } else {
879 dw.println("mConfigurationMap read stats map configure failed with error: %s",
880 configuration.status().msg().c_str());
Chenbo Fengef297172018-03-26 10:53:33 -0700881 }
Chenbo Feng703798e2018-06-15 17:07:59 -0700882 dumpBpfMap("mUidOwnerMap", dw, "");
883 const auto printUidMatchInfo = [&dw](const uint32_t& key, const uint8_t& value,
884 const BpfMap<uint32_t, uint8_t>&) {
885 dw.println("%u %s", key, uidMatchTypeToString(value).c_str());
886 return netdutils::status::ok;
887 };
888 res = mUidOwnerMap.iterateWithValue(printUidMatchInfo);
Chenbo Feng4f6c2372018-04-26 10:37:55 -0700889 if (!isOk(res)) {
Chenbo Feng703798e2018-06-15 17:07:59 -0700890 dw.println("mUidOwnerMap print end with error: %s", res.msg().c_str());
Chenbo Feng95892f32018-06-07 14:52:02 -0700891 }
Chenbo Feng48eaed32018-12-26 17:40:21 -0800892 dumpBpfMap("mUidPermissionMap", dw, "");
893 const auto printUidPermissionInfo = [&dw](const uint32_t& key, const uint8_t& value,
894 const BpfMap<uint32_t, uint8_t>&) {
895 dw.println("%u %s", key, UidPermissionTypeToString(value).c_str());
896 return netdutils::status::ok;
897 };
898 res = mUidPermissionMap.iterateWithValue(printUidPermissionInfo);
899 if (!isOk(res)) {
900 dw.println("mUidPermissionMap print end with error: %s", res.msg().c_str());
901 }
902
903 dumpBpfMap("mPrivilegedUser", dw, "");
904 for (uid_t uid : mPrivilegedUser) {
905 dw.println("%u ALLOW_UPDATE_DEVICE_STATS", (uint32_t)uid);
906 }
Chenbo Fengef297172018-03-26 10:53:33 -0700907}
908
Chenbo Fengf2759682017-10-10 17:31:57 -0700909} // namespace net
910} // namespace android