1 /**
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
17 #define LOG_TAG "NetdUpdatable"
18
19 #include "BpfHandler.h"
20
21 #include <linux/bpf.h>
22 #include <inttypes.h>
23
24 #include <android-base/unique_fd.h>
25 #include <bpf/WaitForProgsLoaded.h>
26 #include <log/log.h>
27 #include <netdutils/UidConstants.h>
28 #include <private/android_filesystem_config.h>
29
30 #include "BpfSyscallWrappers.h"
31
32 namespace android {
33 namespace net {
34
35 using base::unique_fd;
36 using base::WaitForProperty;
37 using bpf::getSocketCookie;
38 using bpf::isAtLeastKernelVersion;
39 using bpf::isAtLeastT;
40 using bpf::isAtLeastU;
41 using bpf::isAtLeastV;
42 using bpf::isAtLeast25Q2;
43 using bpf::queryProgram;
44 using bpf::retrieveProgram;
45 using netdutils::Status;
46 using netdutils::statusFromErrno;
47
48 constexpr int PER_UID_STATS_ENTRIES_LIMIT = 500;
49 // At most 90% of the stats map may be used by tagged traffic entries. This ensures
50 // that 10% of the map is always available to count untagged traffic, one entry per UID.
51 // Otherwise, apps would be able to avoid data usage accounting entirely by filling up the
52 // map with tagged traffic entries.
53 constexpr int TOTAL_UID_STATS_ENTRIES_LIMIT = STATS_MAP_SIZE * 0.9;
54
55 static_assert(STATS_MAP_SIZE - TOTAL_UID_STATS_ENTRIES_LIMIT > 100,
56 "The limit for stats map is to high, stats data may be lost due to overflow");
57
attachProgramToCgroup(const char * programPath,const unique_fd & cgroupFd,bpf_attach_type type)58 static Status attachProgramToCgroup(const char* programPath, const unique_fd& cgroupFd,
59 bpf_attach_type type) {
60 unique_fd cgroupProg(retrieveProgram(programPath));
61 if (!cgroupProg.ok()) {
62 return statusFromErrno(errno, fmt::format("Failed to get program from {}", programPath));
63 }
64 if (bpf::attachProgram(type, cgroupProg, cgroupFd)) {
65 return statusFromErrno(errno, fmt::format("Program {} attach failed", programPath));
66 }
67 return netdutils::status::ok;
68 }
69
checkProgramAccessible(const char * programPath)70 static Status checkProgramAccessible(const char* programPath) {
71 unique_fd prog(retrieveProgram(programPath));
72 if (!prog.ok()) {
73 return statusFromErrno(errno, fmt::format("Failed to get program from {}", programPath));
74 }
75 return netdutils::status::ok;
76 }
77
initPrograms(const char * cg2_path)78 static Status initPrograms(const char* cg2_path) {
79 if (!cg2_path) return Status("cg2_path is NULL");
80
81 // This code was mainlined in T, so this should be trivially satisfied.
82 if (!isAtLeastT) return Status("S- platform is unsupported");
83
84 // S requires eBPF support which was only added in 4.9, so this should be satisfied.
85 if (!isAtLeastKernelVersion(4, 9, 0)) {
86 return Status("kernel version < 4.9.0 is unsupported");
87 }
88
89 // U bumps the kernel requirement up to 4.14
90 if (isAtLeastU && !isAtLeastKernelVersion(4, 14, 0)) {
91 return Status("U+ platform with kernel version < 4.14.0 is unsupported");
92 }
93
94 // U mandates this mount point (though it should also be the case on T)
95 if (isAtLeastU && !!strcmp(cg2_path, "/sys/fs/cgroup")) {
96 return Status("U+ platform with cg2_path != /sys/fs/cgroup is unsupported");
97 }
98
99 // V bumps the kernel requirement up to 4.19
100 if (isAtLeastV && !isAtLeastKernelVersion(4, 19, 0)) {
101 return Status("V+ platform with kernel version < 4.19.0 is unsupported");
102 }
103
104 // 25Q2 bumps the kernel requirement up to 5.4
105 if (isAtLeast25Q2 && !isAtLeastKernelVersion(5, 4, 0)) {
106 return Status("25Q2+ platform with kernel version < 5.4.0 is unsupported");
107 }
108
109 unique_fd cg_fd(open(cg2_path, O_DIRECTORY | O_RDONLY | O_CLOEXEC));
110 if (!cg_fd.ok()) return statusFromErrno(errno, "Opening cgroup dir failed");
111
112 RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_ALLOWLIST_PROG_PATH));
113 RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_DENYLIST_PROG_PATH));
114 RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_EGRESS_PROG_PATH));
115 RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_INGRESS_PROG_PATH));
116 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_EGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_EGRESS));
117 RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_INGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_INGRESS));
118
119 // For the devices that support cgroup socket filter, the socket filter
120 // should be loaded successfully by bpfloader. So we attach the filter to
121 // cgroup if the program is pinned properly.
122 // TODO: delete the if statement once all devices should support cgroup
123 // socket filter (ie. the minimum kernel version required is 4.14).
124 if (isAtLeastKernelVersion(4, 14, 0)) {
125 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_INET_CREATE_PROG_PATH,
126 cg_fd, BPF_CGROUP_INET_SOCK_CREATE));
127 }
128
129 if (isAtLeastKernelVersion(5, 10, 0)) {
130 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_INET_RELEASE_PROG_PATH,
131 cg_fd, BPF_CGROUP_INET_SOCK_RELEASE));
132 }
133
134 if (isAtLeastV) {
135 // V requires 4.19+, so technically this 2nd 'if' is not required, but it
136 // doesn't hurt us to try to support AOSP forks that try to support older kernels.
137 if (isAtLeastKernelVersion(4, 19, 0)) {
138 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_CONNECT4_PROG_PATH,
139 cg_fd, BPF_CGROUP_INET4_CONNECT));
140 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_CONNECT6_PROG_PATH,
141 cg_fd, BPF_CGROUP_INET6_CONNECT));
142 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_UDP4_RECVMSG_PROG_PATH,
143 cg_fd, BPF_CGROUP_UDP4_RECVMSG));
144 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_UDP6_RECVMSG_PROG_PATH,
145 cg_fd, BPF_CGROUP_UDP6_RECVMSG));
146 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_UDP4_SENDMSG_PROG_PATH,
147 cg_fd, BPF_CGROUP_UDP4_SENDMSG));
148 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_UDP6_SENDMSG_PROG_PATH,
149 cg_fd, BPF_CGROUP_UDP6_SENDMSG));
150 }
151
152 if (isAtLeastKernelVersion(5, 4, 0)) {
153 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_GETSOCKOPT_PROG_PATH,
154 cg_fd, BPF_CGROUP_GETSOCKOPT));
155 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_SETSOCKOPT_PROG_PATH,
156 cg_fd, BPF_CGROUP_SETSOCKOPT));
157 }
158 }
159
160 if (isAtLeastKernelVersion(4, 19, 0)) {
161 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_BIND4_PROG_PATH,
162 cg_fd, BPF_CGROUP_INET4_BIND));
163 RETURN_IF_NOT_OK(attachProgramToCgroup(CGROUP_BIND6_PROG_PATH,
164 cg_fd, BPF_CGROUP_INET6_BIND));
165
166 // This should trivially pass, since we just attached up above,
167 // but BPF_PROG_QUERY is only implemented on 4.19+ kernels.
168 if (queryProgram(cg_fd, BPF_CGROUP_INET_EGRESS) <= 0) abort();
169 if (queryProgram(cg_fd, BPF_CGROUP_INET_INGRESS) <= 0) abort();
170 if (queryProgram(cg_fd, BPF_CGROUP_INET_SOCK_CREATE) <= 0) abort();
171 if (queryProgram(cg_fd, BPF_CGROUP_INET4_BIND) <= 0) abort();
172 if (queryProgram(cg_fd, BPF_CGROUP_INET6_BIND) <= 0) abort();
173 }
174
175 if (isAtLeastKernelVersion(5, 10, 0)) {
176 if (queryProgram(cg_fd, BPF_CGROUP_INET_SOCK_RELEASE) <= 0) abort();
177 }
178
179 if (isAtLeastV) {
180 // V requires 4.19+, so technically this 2nd 'if' is not required, but it
181 // doesn't hurt us to try to support AOSP forks that try to support older kernels.
182 if (isAtLeastKernelVersion(4, 19, 0)) {
183 if (queryProgram(cg_fd, BPF_CGROUP_INET4_CONNECT) <= 0) abort();
184 if (queryProgram(cg_fd, BPF_CGROUP_INET6_CONNECT) <= 0) abort();
185 if (queryProgram(cg_fd, BPF_CGROUP_UDP4_RECVMSG) <= 0) abort();
186 if (queryProgram(cg_fd, BPF_CGROUP_UDP6_RECVMSG) <= 0) abort();
187 if (queryProgram(cg_fd, BPF_CGROUP_UDP4_SENDMSG) <= 0) abort();
188 if (queryProgram(cg_fd, BPF_CGROUP_UDP6_SENDMSG) <= 0) abort();
189 }
190
191 if (isAtLeastKernelVersion(5, 4, 0)) {
192 if (queryProgram(cg_fd, BPF_CGROUP_GETSOCKOPT) <= 0) abort();
193 if (queryProgram(cg_fd, BPF_CGROUP_SETSOCKOPT) <= 0) abort();
194 }
195 }
196
197 return netdutils::status::ok;
198 }
199
BpfHandler()200 BpfHandler::BpfHandler()
201 : mPerUidStatsEntriesLimit(PER_UID_STATS_ENTRIES_LIMIT),
202 mTotalUidStatsEntriesLimit(TOTAL_UID_STATS_ENTRIES_LIMIT) {}
203
BpfHandler(uint32_t perUidLimit,uint32_t totalLimit)204 BpfHandler::BpfHandler(uint32_t perUidLimit, uint32_t totalLimit)
205 : mPerUidStatsEntriesLimit(perUidLimit), mTotalUidStatsEntriesLimit(totalLimit) {}
206
mainlineNetBpfLoadDone()207 static bool mainlineNetBpfLoadDone() {
208 return !access("/sys/fs/bpf/netd_shared/mainline_done", F_OK);
209 }
210
211 // copied with minor changes from waitForProgsLoaded()
212 // p/m/C's staticlibs/native/bpf_headers/include/bpf/WaitForProgsLoaded.h
waitForNetProgsLoaded()213 static inline void waitForNetProgsLoaded() {
214 // infinite loop until success with 5/10/20/40/60/60/60... delay
215 for (int delay = 5;; delay *= 2) {
216 if (delay > 60) delay = 60;
217 if (WaitForProperty("init.svc.mdnsd_netbpfload", "stopped", std::chrono::seconds(delay))
218 && mainlineNetBpfLoadDone())
219 return;
220 ALOGW("Waited %ds for init.svc.mdnsd_netbpfload=stopped, still waiting...", delay);
221 }
222 }
223
waitForBpf()224 static inline void waitForBpf() {
225 // Note: netd *can* be restarted, so this might get called a second time after boot is complete
226 // at which point we don't need to (and shouldn't) wait for (more importantly start) loading bpf
227
228 if (base::GetProperty("bpf.progs_loaded", "") != "1") {
229 // AOSP platform netd & mainline don't need this (at least prior to U QPR3),
230 // but there could be platform provided (xt_)bpf programs that oem/vendor
231 // modified netd (which calls us during init) depends on...
232 ALOGI("Waiting for platform BPF programs");
233 bpf::waitForProgsLoaded();
234 }
235
236 if (!mainlineNetBpfLoadDone()) {
237 // We're on < U QPR3 & it's the first time netd is starting up (unless crashlooping)
238 //
239 // On U QPR3+ netbpfload is guaranteed to run before the platform bpfloader,
240 // so waitForProgsLoaded() implies mainlineNetBpfLoadDone().
241 if (!base::SetProperty("ctl.start", "mdnsd_netbpfload")) {
242 ALOGE("Failed to set property ctl.start=mdnsd_netbpfload, see dmesg for reason.");
243 abort();
244 }
245
246 ALOGI("Waiting for Networking BPF programs");
247 waitForNetProgsLoaded();
248 ALOGI("Networking BPF programs are loaded");
249 }
250
251 ALOGI("BPF programs are loaded");
252 }
253
init(const char * cg2_path)254 Status BpfHandler::init(const char* cg2_path) {
255 // This wait is effectively a no-op on U QPR3+ devices (as netd starts
256 // *after* the synchronous 'exec_start bpfloader' which calls NetBpfLoad)
257 // but checking for U QPR3 is hard.
258 //
259 // Waiting should not be required on U QPR3+ devices,
260 // ...
261 //
262 // ...unless someone changed 'exec_start bpfloader' to 'start bpfloader'
263 // in the rc file.
264 //
265 if (!isAtLeast25Q2) waitForBpf();
266
267 RETURN_IF_NOT_OK(initPrograms(cg2_path));
268 RETURN_IF_NOT_OK(initMaps());
269
270 if (isAtLeast25Q2) {
271 struct rlimit limit = {
272 .rlim_cur = 1u << 30, // 1 GiB
273 .rlim_max = 1u << 30, // 1 GiB
274 };
275 // 25Q2 netd.rc includes "rlimit memlock 1073741824 1073741824"
276 // so this should be a no-op, and thus just succeed.
277 // make sure it isn't lowered in platform netd.rc...
278 if (setrlimit(RLIMIT_MEMLOCK, &limit))
279 return statusFromErrno(errno, "Failed to set 1GiB RLIMIT_MEMLOCK");
280
281 // Make sure netd can create & write maps. sepolicy is V+, but enough to enforce on 25Q2+
282 int key = 1;
283 int value = 123;
284 unique_fd map(bpf::createMap(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), 2, 0));
285 if (!map.ok()) return statusFromErrno(errno, fmt::format("map create failed"));
286 int rv = bpf::writeToMapEntry(map, &key, &value, BPF_ANY);
287 if (rv) return statusFromErrno(errno, fmt::format("map write failed (rv={})", rv));
288 }
289
290 return netdutils::status::ok;
291 }
292
mapLockTest(void)293 static void mapLockTest(void) {
294 // The maps must be R/W, and as yet unopened (or more specifically not yet lock'ed).
295 const char * const m1 = BPF_NETD_PATH "map_netd_lock_array_test_map";
296 const char * const m2 = BPF_NETD_PATH "map_netd_lock_hash_test_map";
297
298 unique_fd fd0(bpf::mapRetrieveExclusiveRW(m1)); if (!fd0.ok()) abort(); // grabs exclusive lock
299
300 unique_fd fd1(bpf::mapRetrieveExclusiveRW(m2)); if (!fd1.ok()) abort(); // no conflict with fd0
301 unique_fd fd2(bpf::mapRetrieveExclusiveRW(m2)); if ( fd2.ok()) abort(); // busy due to fd1
302 unique_fd fd3(bpf::mapRetrieveRO(m2)); if (!fd3.ok()) abort(); // no lock taken
303 unique_fd fd4(bpf::mapRetrieveRW(m2)); if ( fd4.ok()) abort(); // busy due to fd1
304 fd1.reset(); // releases exclusive lock
305 unique_fd fd5(bpf::mapRetrieveRO(m2)); if (!fd5.ok()) abort(); // no lock taken
306 unique_fd fd6(bpf::mapRetrieveRW(m2)); if (!fd6.ok()) abort(); // now ok
307 unique_fd fd7(bpf::mapRetrieveRO(m2)); if (!fd7.ok()) abort(); // no lock taken
308 unique_fd fd8(bpf::mapRetrieveExclusiveRW(m2)); if ( fd8.ok()) abort(); // busy due to fd6
309
310 fd0.reset(); // releases exclusive lock
311 unique_fd fd9(bpf::mapRetrieveWO(m1)); if (!fd9.ok()) abort(); // grabs exclusive lock
312 }
313
initMaps()314 Status BpfHandler::initMaps() {
315 // bpfLock() requires bpfGetFdMapId which is only available on 4.14+ kernels.
316 if (isAtLeastKernelVersion(4, 14, 0)) {
317 mapLockTest();
318 }
319
320 RETURN_IF_NOT_OK(mStatsMapA.init(STATS_MAP_A_PATH));
321 RETURN_IF_NOT_OK(mStatsMapB.init(STATS_MAP_B_PATH));
322 RETURN_IF_NOT_OK(mConfigurationMap.init(CONFIGURATION_MAP_PATH));
323 RETURN_IF_NOT_OK(mUidPermissionMap.init(UID_PERMISSION_MAP_PATH));
324 // initialized last so mCookieTagMap.isValid() implies everything else is valid too
325 RETURN_IF_NOT_OK(mCookieTagMap.init(COOKIE_TAG_MAP_PATH));
326
327 return netdutils::status::ok;
328 }
329
hasUpdateDeviceStatsPermission(uid_t uid)330 bool BpfHandler::hasUpdateDeviceStatsPermission(uid_t uid) {
331 // This implementation is the same logic as method ActivityManager#checkComponentPermission.
332 // It implies that the real uid can never be the same as PER_USER_RANGE.
333 uint32_t appId = uid % PER_USER_RANGE;
334 auto permission = mUidPermissionMap.readValue(appId);
335 if (permission.ok() && (permission.value() & BPF_PERMISSION_UPDATE_DEVICE_STATS)) {
336 return true;
337 }
338 return ((appId == AID_ROOT) || (appId == AID_SYSTEM) || (appId == AID_DNS));
339 }
340
tagSocket(int sockFd,uint32_t tag,uid_t chargeUid,uid_t realUid)341 int BpfHandler::tagSocket(int sockFd, uint32_t tag, uid_t chargeUid, uid_t realUid) {
342 if (!mCookieTagMap.isValid()) return -EPERM;
343
344 if (chargeUid != realUid && !hasUpdateDeviceStatsPermission(realUid)) return -EPERM;
345
346 // Note that tagging the socket to AID_CLAT is only implemented in JNI ClatCoordinator.
347 // The process is not allowed to tag socket to AID_CLAT via tagSocket() which would cause
348 // process data usage accounting to be bypassed. Tagging AID_CLAT is used for avoiding counting
349 // CLAT traffic data usage twice. See packages/modules/Connectivity/service/jni/
350 // com_android_server_connectivity_ClatCoordinator.cpp
351 if (chargeUid == AID_CLAT) return -EPERM;
352
353 // The socket destroy listener only monitors on the group {INET_TCP, INET_UDP, INET6_TCP,
354 // INET6_UDP}. Tagging listener unsupported sockets (on <5.10) means the tag cannot be
355 // removed from tag map automatically. Eventually, it may run out of space due to dead tag
356 // entries. Note that although tagSocket() of net client has already denied the family which
357 // is neither AF_INET nor AF_INET6, the family validation is still added here just in case.
358 // See tagSocket in system/netd/client/NetdClient.cpp and
359 // TrafficController::makeSkDestroyListener in
360 // packages/modules/Connectivity/service/native/TrafficController.cpp
361 // TODO: remove this once the socket destroy listener can detect more types of socket destroy.
362 int socketFamily;
363 socklen_t familyLen = sizeof(socketFamily);
364 if (getsockopt(sockFd, SOL_SOCKET, SO_DOMAIN, &socketFamily, &familyLen)) {
365 ALOGE("Failed to getsockopt SO_DOMAIN: %s, fd: %d", strerror(errno), sockFd);
366 return -errno;
367 }
368 if (socketFamily != AF_INET && socketFamily != AF_INET6) {
369 ALOGV("Unsupported family: %d", socketFamily);
370 return -EAFNOSUPPORT;
371 }
372
373 // On 5.10+ the BPF_CGROUP_INET_SOCK_RELEASE hook takes care of cookie tag map cleanup
374 // during socket destruction. As such the socket destroy listener is superfluous.
375 if (!isAtLeastKernelVersion(5, 10, 0)) {
376 int socketProto;
377 socklen_t protoLen = sizeof(socketProto);
378 if (getsockopt(sockFd, SOL_SOCKET, SO_PROTOCOL, &socketProto, &protoLen)) {
379 ALOGE("Failed to getsockopt SO_PROTOCOL: %s, fd: %d", strerror(errno), sockFd);
380 return -errno;
381 }
382 if (socketProto != IPPROTO_UDP && socketProto != IPPROTO_TCP) {
383 ALOGV("Unsupported protocol: %d", socketProto);
384 return -EPROTONOSUPPORT;
385 }
386 }
387
388 uint64_t sock_cookie = getSocketCookie(sockFd);
389 if (!sock_cookie) return -errno;
390
391 UidTagValue newKey = {.uid = (uint32_t)chargeUid, .tag = tag};
392
393 uint32_t totalEntryCount = 0;
394 uint32_t perUidEntryCount = 0;
395 // Now we go through the stats map and count how many entries are associated
396 // with chargeUid. If the uid entry hit the limit for each chargeUid, we block
397 // the request to prevent the map from overflow. Note though that it isn't really
398 // safe here to iterate over the map since it might be modified by the system server,
399 // which might toggle the live stats map and clean it.
400 const auto countUidStatsEntries = [chargeUid, &totalEntryCount, &perUidEntryCount](
401 const StatsKey& key,
402 const BpfMapRO<StatsKey, StatsValue>&) {
403 if (key.uid == chargeUid) {
404 perUidEntryCount++;
405 }
406 totalEntryCount++;
407 return base::Result<void>();
408 };
409 auto configuration = mConfigurationMap.readValue(CURRENT_STATS_MAP_CONFIGURATION_KEY);
410 if (!configuration.ok()) {
411 ALOGE("Failed to get current configuration: %s",
412 strerror(configuration.error().code()));
413 return -configuration.error().code();
414 }
415 if (configuration.value() != SELECT_MAP_A && configuration.value() != SELECT_MAP_B) {
416 ALOGE("unknown configuration value: %d", configuration.value());
417 return -EINVAL;
418 }
419
420 BpfMapRO<StatsKey, StatsValue>& currentMap =
421 (configuration.value() == SELECT_MAP_A) ? mStatsMapA : mStatsMapB;
422 base::Result<void> res = currentMap.iterate(countUidStatsEntries);
423 if (!res.ok()) {
424 ALOGE("Failed to count the stats entry in map: %s",
425 strerror(res.error().code()));
426 return -res.error().code();
427 }
428
429 if (totalEntryCount > mTotalUidStatsEntriesLimit ||
430 perUidEntryCount > mPerUidStatsEntriesLimit) {
431 ALOGE("Too many stats entries in the map, total count: %u, chargeUid(%u) count: %u,"
432 " blocking tag request to prevent map overflow",
433 totalEntryCount, chargeUid, perUidEntryCount);
434 return -EMFILE;
435 }
436 // Update the tag information of a socket to the cookieUidMap. Use BPF_ANY
437 // flag so it will insert a new entry to the map if that value doesn't exist
438 // yet and update the tag if there is already a tag stored. Since the eBPF
439 // program in kernel only read this map, and is protected by rcu read lock. It
440 // should be fine to concurrently update the map while eBPF program is running.
441 res = mCookieTagMap.writeValue(sock_cookie, newKey, BPF_ANY);
442 if (!res.ok()) {
443 ALOGE("Failed to tag the socket: %s", strerror(res.error().code()));
444 return -res.error().code();
445 }
446 ALOGV("Socket with cookie %" PRIu64 " tagged successfully with tag %" PRIu32 " uid %u "
447 "and real uid %u", sock_cookie, tag, chargeUid, realUid);
448 return 0;
449 }
450
untagSocket(int sockFd)451 int BpfHandler::untagSocket(int sockFd) {
452 uint64_t sock_cookie = getSocketCookie(sockFd);
453 if (!sock_cookie) return -errno;
454
455 if (!mCookieTagMap.isValid()) return -EPERM;
456 base::Result<void> res = mCookieTagMap.deleteValue(sock_cookie);
457 if (!res.ok()) {
458 const int err = res.error().code();
459 if (err != ENOENT) ALOGE("Failed to untag socket: %s", strerror(err));
460 return -err;
461 }
462 ALOGV("Socket with cookie %" PRIu64 " untagged successfully.", sock_cookie);
463 return 0;
464 }
465
466 } // namespace net
467 } // namespace android
468