blob: 06873fa8c12856f9b62db6188d067d5969cd7c68 [file] [log] [blame]
Ken Chen1647f602021-10-05 21:55:22 +08001/**
2 * Copyright (c) 2022, 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
Maciej Żenczykowskia81daca2024-05-20 14:33:17 +000017#define LOG_TAG "NetdUpdatable"
Ken Chen1647f602021-10-05 21:55:22 +080018
19#include "BpfHandler.h"
20
21#include <linux/bpf.h>
Nick Wille5076a022023-06-01 18:39:25 +000022#include <inttypes.h>
Ken Chen1647f602021-10-05 21:55:22 +080023
24#include <android-base/unique_fd.h>
Maciej Żenczykowski65075bb2023-06-01 23:09:14 +000025#include <android-modules-utils/sdk_level.h>
Ken Chen1647f602021-10-05 21:55:22 +080026#include <bpf/WaitForProgsLoaded.h>
27#include <log/log.h>
28#include <netdutils/UidConstants.h>
29#include <private/android_filesystem_config.h>
30
31#include "BpfSyscallWrappers.h"
32
33namespace android {
34namespace net {
35
36using base::unique_fd;
Maciej Żenczykowski15f97312024-06-13 14:11:28 -070037using base::WaitForProperty;
Ken Chen1647f602021-10-05 21:55:22 +080038using bpf::getSocketCookie;
39using bpf::retrieveProgram;
40using netdutils::Status;
41using netdutils::statusFromErrno;
42
43constexpr int PER_UID_STATS_ENTRIES_LIMIT = 500;
44// At most 90% of the stats map may be used by tagged traffic entries. This ensures
45// that 10% of the map is always available to count untagged traffic, one entry per UID.
46// Otherwise, apps would be able to avoid data usage accounting entirely by filling up the
47// map with tagged traffic entries.
48constexpr int TOTAL_UID_STATS_ENTRIES_LIMIT = STATS_MAP_SIZE * 0.9;
49
50static_assert(STATS_MAP_SIZE - TOTAL_UID_STATS_ENTRIES_LIMIT > 100,
51 "The limit for stats map is to high, stats data may be lost due to overflow");
52
53static Status attachProgramToCgroup(const char* programPath, const unique_fd& cgroupFd,
54 bpf_attach_type type) {
55 unique_fd cgroupProg(retrieveProgram(programPath));
Maciej Żenczykowski25824452023-06-14 10:08:31 +000056 if (!cgroupProg.ok()) {
Ken Chend6ea75a2023-11-28 23:29:47 +080057 return statusFromErrno(errno, fmt::format("Failed to get program from {}", programPath));
Ken Chen1647f602021-10-05 21:55:22 +080058 }
59 if (android::bpf::attachProgram(type, cgroupProg, cgroupFd)) {
Ken Chend6ea75a2023-11-28 23:29:47 +080060 return statusFromErrno(errno, fmt::format("Program {} attach failed", programPath));
Ken Chen1647f602021-10-05 21:55:22 +080061 }
62 return netdutils::status::ok;
63}
64
Maciej Żenczykowskic576c0d2022-08-07 22:18:15 +000065static Status checkProgramAccessible(const char* programPath) {
66 unique_fd prog(retrieveProgram(programPath));
Maciej Żenczykowski25824452023-06-14 10:08:31 +000067 if (!prog.ok()) {
Ken Chend6ea75a2023-11-28 23:29:47 +080068 return statusFromErrno(errno, fmt::format("Failed to get program from {}", programPath));
Maciej Żenczykowskic576c0d2022-08-07 22:18:15 +000069 }
70 return netdutils::status::ok;
71}
72
Ken Chen1647f602021-10-05 21:55:22 +080073static Status initPrograms(const char* cg2_path) {
Ken Chend6ea75a2023-11-28 23:29:47 +080074 if (!cg2_path) return Status("cg2_path is NULL");
Ken Chen5d146492023-11-27 17:05:43 +080075
Maciej Żenczykowskic2dd01c2023-09-01 21:02:36 +000076 // This code was mainlined in T, so this should be trivially satisfied.
Ken Chend6ea75a2023-11-28 23:29:47 +080077 if (!modules::sdklevel::IsAtLeastT()) return Status("S- platform is unsupported");
Maciej Żenczykowskic2dd01c2023-09-01 21:02:36 +000078
79 // S requires eBPF support which was only added in 4.9, so this should be satisfied.
Ken Chen5d146492023-11-27 17:05:43 +080080 if (!bpf::isAtLeastKernelVersion(4, 9, 0)) {
Ken Chend6ea75a2023-11-28 23:29:47 +080081 return Status("kernel version < 4.9.0 is unsupported");
Ken Chen5d146492023-11-27 17:05:43 +080082 }
Maciej Żenczykowskic2dd01c2023-09-01 21:02:36 +000083
84 // U bumps the kernel requirement up to 4.14
Ken Chen5d146492023-11-27 17:05:43 +080085 if (modules::sdklevel::IsAtLeastU() && !bpf::isAtLeastKernelVersion(4, 14, 0)) {
Ken Chend6ea75a2023-11-28 23:29:47 +080086 return Status("U+ platform with kernel version < 4.14.0 is unsupported");
Ken Chen5d146492023-11-27 17:05:43 +080087 }
Maciej Żenczykowskic2dd01c2023-09-01 21:02:36 +000088
Maciej Żenczykowskic2dd01c2023-09-01 21:02:36 +000089 // U mandates this mount point (though it should also be the case on T)
Ken Chen5d146492023-11-27 17:05:43 +080090 if (modules::sdklevel::IsAtLeastU() && !!strcmp(cg2_path, "/sys/fs/cgroup")) {
Ken Chend6ea75a2023-11-28 23:29:47 +080091 return Status("U+ platform with cg2_path != /sys/fs/cgroup is unsupported");
Ken Chen5d146492023-11-27 17:05:43 +080092 }
Maciej Żenczykowski65075bb2023-06-01 23:09:14 +000093
Ken Chen1647f602021-10-05 21:55:22 +080094 unique_fd cg_fd(open(cg2_path, O_DIRECTORY | O_RDONLY | O_CLOEXEC));
Maciej Żenczykowski25824452023-06-14 10:08:31 +000095 if (!cg_fd.ok()) {
96 const int err = errno;
97 ALOGE("Failed to open the cgroup directory: %s", strerror(err));
98 return statusFromErrno(err, "Open the cgroup directory failed");
Ken Chen1647f602021-10-05 21:55:22 +080099 }
Maciej Żenczykowskic576c0d2022-08-07 22:18:15 +0000100 RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_ALLOWLIST_PROG_PATH));
101 RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_DENYLIST_PROG_PATH));
102 RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_EGRESS_PROG_PATH));
103 RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_INGRESS_PROG_PATH));
Ken Chen1647f602021-10-05 21:55:22 +0800104 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_EGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_EGRESS));
105 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_INGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_INGRESS));
Lorenzo Colitti3505b582022-10-27 19:36:27 +0900106
107 // For the devices that support cgroup socket filter, the socket filter
108 // should be loaded successfully by bpfloader. So we attach the filter to
109 // cgroup if the program is pinned properly.
110 // TODO: delete the if statement once all devices should support cgroup
111 // socket filter (ie. the minimum kernel version required is 4.14).
Maciej Żenczykowski03093622023-02-22 22:09:25 +0000112 if (bpf::isAtLeastKernelVersion(4, 14, 0)) {
Lorenzo Colitti3505b582022-10-27 19:36:27 +0900113 RETURN_IF_NOT_OK(
114 attachProgramToCgroup(CGROUP_SOCKET_PROG_PATH, cg_fd, BPF_CGROUP_INET_SOCK_CREATE));
115 }
Maciej Żenczykowski5b2611d2023-10-04 00:44:56 +0000116
Maciej Żenczykowski5b2611d2023-10-04 00:44:56 +0000117 if (bpf::isAtLeastKernelVersion(4, 19, 0)) {
Maciej Żenczykowski3cb494f2023-10-04 21:35:41 +0000118 RETURN_IF_NOT_OK(attachProgramToCgroup(
119 "/sys/fs/bpf/netd_readonly/prog_block_bind4_block_port",
120 cg_fd, BPF_CGROUP_INET4_BIND));
121 RETURN_IF_NOT_OK(attachProgramToCgroup(
122 "/sys/fs/bpf/netd_readonly/prog_block_bind6_block_port",
123 cg_fd, BPF_CGROUP_INET6_BIND));
124
125 // This should trivially pass, since we just attached up above,
126 // but BPF_PROG_QUERY is only implemented on 4.19+ kernels.
Maciej Żenczykowski5b2611d2023-10-04 00:44:56 +0000127 if (bpf::queryProgram(cg_fd, BPF_CGROUP_INET_EGRESS) <= 0) abort();
128 if (bpf::queryProgram(cg_fd, BPF_CGROUP_INET_INGRESS) <= 0) abort();
129 if (bpf::queryProgram(cg_fd, BPF_CGROUP_INET_SOCK_CREATE) <= 0) abort();
Maciej Żenczykowski3cb494f2023-10-04 21:35:41 +0000130 if (bpf::queryProgram(cg_fd, BPF_CGROUP_INET4_BIND) <= 0) abort();
131 if (bpf::queryProgram(cg_fd, BPF_CGROUP_INET6_BIND) <= 0) abort();
Maciej Żenczykowski5b2611d2023-10-04 00:44:56 +0000132 }
133
Ken Chen1647f602021-10-05 21:55:22 +0800134 return netdutils::status::ok;
135}
136
137BpfHandler::BpfHandler()
138 : mPerUidStatsEntriesLimit(PER_UID_STATS_ENTRIES_LIMIT),
139 mTotalUidStatsEntriesLimit(TOTAL_UID_STATS_ENTRIES_LIMIT) {}
140
141BpfHandler::BpfHandler(uint32_t perUidLimit, uint32_t totalLimit)
142 : mPerUidStatsEntriesLimit(perUidLimit), mTotalUidStatsEntriesLimit(totalLimit) {}
143
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700144static bool mainlineNetBpfLoadDone() {
145 return !access("/sys/fs/bpf/netd_shared/mainline_done", F_OK);
146}
147
Maciej Żenczykowski732a1412024-03-14 00:17:18 -0700148// copied with minor changes from waitForProgsLoaded()
149// p/m/C's staticlibs/native/bpf_headers/include/bpf/WaitForProgsLoaded.h
150static inline void waitForNetProgsLoaded() {
151 // infinite loop until success with 5/10/20/40/60/60/60... delay
152 for (int delay = 5;; delay *= 2) {
153 if (delay > 60) delay = 60;
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700154 if (WaitForProperty("init.svc.mdnsd_netbpfload", "stopped", std::chrono::seconds(delay))
155 && mainlineNetBpfLoadDone())
Maciej Żenczykowski732a1412024-03-14 00:17:18 -0700156 return;
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700157 ALOGW("Waited %ds for init.svc.mdnsd_netbpfload=stopped, still waiting...", delay);
Maciej Żenczykowski732a1412024-03-14 00:17:18 -0700158 }
159}
160
Ken Chen1647f602021-10-05 21:55:22 +0800161Status BpfHandler::init(const char* cg2_path) {
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700162 // Note: netd *can* be restarted, so this might get called a second time after boot is complete
163 // at which point we don't need to (and shouldn't) wait for (more importantly start) loading bpf
164
Maciej Żenczykowski23d2c1e2024-03-28 22:54:01 -0700165 if (base::GetProperty("bpf.progs_loaded", "") != "1") {
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700166 // AOSP platform netd & mainline don't need this (at least prior to U QPR3),
167 // but there could be platform provided (xt_)bpf programs that oem/vendor
168 // modified netd (which calls us during init) depends on...
169 ALOGI("Waiting for platform BPF programs");
Maciej Żenczykowski23d2c1e2024-03-28 22:54:01 -0700170 android::bpf::waitForProgsLoaded();
Maciej Żenczykowski732a1412024-03-14 00:17:18 -0700171 }
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700172
Maciej Żenczykowski231598b2024-06-14 04:39:03 -0700173 if (!mainlineNetBpfLoadDone()) {
174 const bool enforce_mainline = false; // TODO: flip to true
175
Maciej Żenczykowski72628992024-06-14 13:46:11 -0700176 // We're on < U QPR3 & it's the first time netd is starting up (unless crashlooping)
177 //
178 // On U QPR3+ netbpfload is guaranteed to run before the platform bpfloader,
179 // so waitForProgsLoaded() implies mainlineNetBpfLoadDone().
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700180 if (!base::SetProperty("ctl.start", "mdnsd_netbpfload")) {
181 ALOGE("Failed to set property ctl.start=mdnsd_netbpfload, see dmesg for reason.");
Maciej Żenczykowski231598b2024-06-14 04:39:03 -0700182 if (enforce_mainline) abort();
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700183 }
184
Maciej Żenczykowski231598b2024-06-14 04:39:03 -0700185 if (enforce_mainline) {
186 ALOGI("Waiting for Networking BPF programs");
187 waitForNetProgsLoaded();
188 ALOGI("Networking BPF programs are loaded");
189 } else {
190 ALOGI("Started mdnsd_netbpfload asynchronously.");
191 }
Maciej Żenczykowski15f97312024-06-13 14:11:28 -0700192 }
193
Ken Chen1647f602021-10-05 21:55:22 +0800194 ALOGI("BPF programs are loaded");
195
196 RETURN_IF_NOT_OK(initPrograms(cg2_path));
197 RETURN_IF_NOT_OK(initMaps());
198
199 return netdutils::status::ok;
200}
201
Maciej Żenczykowski52018c82024-06-04 16:05:16 +0000202static void mapLockTest(void) {
203 // The maps must be R/W, and as yet unopened (or more specifically not yet lock'ed).
204 const char * const m1 = BPF_NETD_PATH "map_netd_lock_array_test_map";
205 const char * const m2 = BPF_NETD_PATH "map_netd_lock_hash_test_map";
206
207 unique_fd fd0(bpf::mapRetrieveExclusiveRW(m1)); if (!fd0.ok()) abort();
208
209 unique_fd fd1(bpf::mapRetrieveExclusiveRW(m2)); if (!fd1.ok()) abort(); // no conflict with fd0
210 unique_fd fd2(bpf::mapRetrieveExclusiveRW(m2)); if ( fd2.ok()) abort(); // busy due to fd1
211 unique_fd fd3(bpf::mapRetrieveRO(m2)); if (!fd3.ok()) abort(); // no lock taken
212 unique_fd fd4(bpf::mapRetrieveRW(m2)); if ( fd4.ok()) abort(); // busy due to fd1
213 fd1.reset(); // releases exclusive lock
214 unique_fd fd5(bpf::mapRetrieveRO(m2)); if (!fd5.ok()) abort(); // no lock taken
215 unique_fd fd6(bpf::mapRetrieveRW(m2)); if (!fd6.ok()) abort(); // now ok
216 unique_fd fd7(bpf::mapRetrieveRO(m2)); if (!fd7.ok()) abort(); // no lock taken
217 unique_fd fd8(bpf::mapRetrieveExclusiveRW(m2)); if ( fd8.ok()) abort(); // busy due to fd6
218}
219
Ken Chen1647f602021-10-05 21:55:22 +0800220Status BpfHandler::initMaps() {
Maciej Żenczykowski52018c82024-06-04 16:05:16 +0000221 mapLockTest();
222
Ken Chen1647f602021-10-05 21:55:22 +0800223 RETURN_IF_NOT_OK(mStatsMapA.init(STATS_MAP_A_PATH));
224 RETURN_IF_NOT_OK(mStatsMapB.init(STATS_MAP_B_PATH));
225 RETURN_IF_NOT_OK(mConfigurationMap.init(CONFIGURATION_MAP_PATH));
Ken Chen1647f602021-10-05 21:55:22 +0800226 RETURN_IF_NOT_OK(mUidPermissionMap.init(UID_PERMISSION_MAP_PATH));
Maciej Żenczykowskib5868a02022-08-31 04:21:01 +0000227 // initialized last so mCookieTagMap.isValid() implies everything else is valid too
228 RETURN_IF_NOT_OK(mCookieTagMap.init(COOKIE_TAG_MAP_PATH));
Ken Chen322ffcb2022-05-23 22:27:40 +0800229 ALOGI("%s successfully", __func__);
Ken Chen1647f602021-10-05 21:55:22 +0800230
231 return netdutils::status::ok;
232}
233
234bool BpfHandler::hasUpdateDeviceStatsPermission(uid_t uid) {
235 // This implementation is the same logic as method ActivityManager#checkComponentPermission.
236 // It implies that the real uid can never be the same as PER_USER_RANGE.
237 uint32_t appId = uid % PER_USER_RANGE;
238 auto permission = mUidPermissionMap.readValue(appId);
239 if (permission.ok() && (permission.value() & BPF_PERMISSION_UPDATE_DEVICE_STATS)) {
240 return true;
241 }
242 return ((appId == AID_ROOT) || (appId == AID_SYSTEM) || (appId == AID_DNS));
243}
244
245int BpfHandler::tagSocket(int sockFd, uint32_t tag, uid_t chargeUid, uid_t realUid) {
Maciej Żenczykowski4938d402022-08-14 14:36:20 +0000246 if (!mCookieTagMap.isValid()) return -EPERM;
247
248 if (chargeUid != realUid && !hasUpdateDeviceStatsPermission(realUid)) return -EPERM;
Ken Chen1647f602021-10-05 21:55:22 +0800249
Hungming Chen436547e2022-02-18 17:52:11 +0800250 // Note that tagging the socket to AID_CLAT is only implemented in JNI ClatCoordinator.
251 // The process is not allowed to tag socket to AID_CLAT via tagSocket() which would cause
252 // process data usage accounting to be bypassed. Tagging AID_CLAT is used for avoiding counting
253 // CLAT traffic data usage twice. See packages/modules/Connectivity/service/jni/
254 // com_android_server_connectivity_ClatCoordinator.cpp
Maciej Żenczykowski4938d402022-08-14 14:36:20 +0000255 if (chargeUid == AID_CLAT) return -EPERM;
Hungming Chen436547e2022-02-18 17:52:11 +0800256
Hungming Chen478c0eb2022-03-04 21:16:59 +0800257 // The socket destroy listener only monitors on the group {INET_TCP, INET_UDP, INET6_TCP,
258 // INET6_UDP}. Tagging listener unsupported socket causes that the tag can't be removed from
259 // tag map automatically. Eventually, the tag map may run out of space because of dead tag
Hungming Chenbcc0f5b2022-03-07 14:13:49 +0800260 // entries. Note that although tagSocket() of net client has already denied the family which
261 // is neither AF_INET nor AF_INET6, the family validation is still added here just in case.
262 // See tagSocket in system/netd/client/NetdClient.cpp and
263 // TrafficController::makeSkDestroyListener in
Hungming Chen478c0eb2022-03-04 21:16:59 +0800264 // packages/modules/Connectivity/service/native/TrafficController.cpp
265 // TODO: remove this once the socket destroy listener can detect more types of socket destroy.
Hungming Chenbcc0f5b2022-03-07 14:13:49 +0800266 int socketFamily;
267 socklen_t familyLen = sizeof(socketFamily);
268 if (getsockopt(sockFd, SOL_SOCKET, SO_DOMAIN, &socketFamily, &familyLen)) {
269 ALOGE("Failed to getsockopt SO_DOMAIN: %s, fd: %d", strerror(errno), sockFd);
Hungming Chen478c0eb2022-03-04 21:16:59 +0800270 return -errno;
Hungming Chenbcc0f5b2022-03-07 14:13:49 +0800271 }
272 if (socketFamily != AF_INET && socketFamily != AF_INET6) {
273 ALOGE("Unsupported family: %d", socketFamily);
274 return -EAFNOSUPPORT;
275 }
276
277 int socketProto;
278 socklen_t protoLen = sizeof(socketProto);
279 if (getsockopt(sockFd, SOL_SOCKET, SO_PROTOCOL, &socketProto, &protoLen)) {
280 ALOGE("Failed to getsockopt SO_PROTOCOL: %s, fd: %d", strerror(errno), sockFd);
281 return -errno;
282 }
283 if (socketProto != IPPROTO_UDP && socketProto != IPPROTO_TCP) {
284 ALOGE("Unsupported protocol: %d", socketProto);
285 return -EPROTONOSUPPORT;
Hungming Chen478c0eb2022-03-04 21:16:59 +0800286 }
287
Ken Chen1647f602021-10-05 21:55:22 +0800288 uint64_t sock_cookie = getSocketCookie(sockFd);
Maciej Żenczykowskid3fe1542023-02-23 03:56:45 +0000289 if (!sock_cookie) return -errno;
Maciej Żenczykowski4938d402022-08-14 14:36:20 +0000290
Ken Chen1647f602021-10-05 21:55:22 +0800291 UidTagValue newKey = {.uid = (uint32_t)chargeUid, .tag = tag};
292
293 uint32_t totalEntryCount = 0;
294 uint32_t perUidEntryCount = 0;
295 // Now we go through the stats map and count how many entries are associated
296 // with chargeUid. If the uid entry hit the limit for each chargeUid, we block
Maciej Żenczykowskib5868a02022-08-31 04:21:01 +0000297 // the request to prevent the map from overflow. Note though that it isn't really
298 // safe here to iterate over the map since it might be modified by the system server,
299 // which might toggle the live stats map and clean it.
Ken Chen1647f602021-10-05 21:55:22 +0800300 const auto countUidStatsEntries = [chargeUid, &totalEntryCount, &perUidEntryCount](
301 const StatsKey& key,
Maciej Żenczykowski7e2f53e2023-09-28 01:08:28 +0000302 const BpfMapRO<StatsKey, StatsValue>&) {
Ken Chen1647f602021-10-05 21:55:22 +0800303 if (key.uid == chargeUid) {
304 perUidEntryCount++;
305 }
306 totalEntryCount++;
307 return base::Result<void>();
308 };
309 auto configuration = mConfigurationMap.readValue(CURRENT_STATS_MAP_CONFIGURATION_KEY);
310 if (!configuration.ok()) {
Maciej Żenczykowski85d4a5e2023-08-20 16:41:50 +0000311 ALOGE("Failed to get current configuration: %s",
312 strerror(configuration.error().code()));
Ken Chen1647f602021-10-05 21:55:22 +0800313 return -configuration.error().code();
314 }
315 if (configuration.value() != SELECT_MAP_A && configuration.value() != SELECT_MAP_B) {
316 ALOGE("unknown configuration value: %d", configuration.value());
317 return -EINVAL;
318 }
319
Maciej Żenczykowski7e2f53e2023-09-28 01:08:28 +0000320 BpfMapRO<StatsKey, StatsValue>& currentMap =
Ken Chen1647f602021-10-05 21:55:22 +0800321 (configuration.value() == SELECT_MAP_A) ? mStatsMapA : mStatsMapB;
322 base::Result<void> res = currentMap.iterate(countUidStatsEntries);
323 if (!res.ok()) {
Maciej Żenczykowski85d4a5e2023-08-20 16:41:50 +0000324 ALOGE("Failed to count the stats entry in map: %s",
Ken Chen1647f602021-10-05 21:55:22 +0800325 strerror(res.error().code()));
326 return -res.error().code();
327 }
328
329 if (totalEntryCount > mTotalUidStatsEntriesLimit ||
330 perUidEntryCount > mPerUidStatsEntriesLimit) {
331 ALOGE("Too many stats entries in the map, total count: %u, chargeUid(%u) count: %u,"
332 " blocking tag request to prevent map overflow",
333 totalEntryCount, chargeUid, perUidEntryCount);
334 return -EMFILE;
335 }
336 // Update the tag information of a socket to the cookieUidMap. Use BPF_ANY
337 // flag so it will insert a new entry to the map if that value doesn't exist
Maciej Żenczykowskib5868a02022-08-31 04:21:01 +0000338 // yet and update the tag if there is already a tag stored. Since the eBPF
Ken Chen1647f602021-10-05 21:55:22 +0800339 // program in kernel only read this map, and is protected by rcu read lock. It
Maciej Żenczykowskib5868a02022-08-31 04:21:01 +0000340 // should be fine to concurrently update the map while eBPF program is running.
Ken Chen1647f602021-10-05 21:55:22 +0800341 res = mCookieTagMap.writeValue(sock_cookie, newKey, BPF_ANY);
342 if (!res.ok()) {
Maciej Żenczykowski85d4a5e2023-08-20 16:41:50 +0000343 ALOGE("Failed to tag the socket: %s", strerror(res.error().code()));
Ken Chen1647f602021-10-05 21:55:22 +0800344 return -res.error().code();
345 }
Nick Wille5076a022023-06-01 18:39:25 +0000346 ALOGD("Socket with cookie %" PRIu64 " tagged successfully with tag %" PRIu32 " uid %u "
347 "and real uid %u", sock_cookie, tag, chargeUid, realUid);
Ken Chen1647f602021-10-05 21:55:22 +0800348 return 0;
349}
350
351int BpfHandler::untagSocket(int sockFd) {
Maciej Żenczykowski4938d402022-08-14 14:36:20 +0000352 uint64_t sock_cookie = getSocketCookie(sockFd);
Maciej Żenczykowskid3fe1542023-02-23 03:56:45 +0000353 if (!sock_cookie) return -errno;
Maciej Żenczykowski4938d402022-08-14 14:36:20 +0000354
355 if (!mCookieTagMap.isValid()) return -EPERM;
Ken Chen1647f602021-10-05 21:55:22 +0800356 base::Result<void> res = mCookieTagMap.deleteValue(sock_cookie);
357 if (!res.ok()) {
Maciej Żenczykowskie0f58462022-05-17 13:59:22 -0700358 ALOGE("Failed to untag socket: %s", strerror(res.error().code()));
Ken Chen1647f602021-10-05 21:55:22 +0800359 return -res.error().code();
360 }
Nick Wille5076a022023-06-01 18:39:25 +0000361 ALOGD("Socket with cookie %" PRIu64 " untagged successfully.", sock_cookie);
Ken Chen1647f602021-10-05 21:55:22 +0800362 return 0;
363}
364
365} // namespace net
366} // namespace android