blob: f43178c1cebe7243b1c3b5b7b5e7f4ad7f079c4f [file] [log] [blame]
Chenbo Fengf43bf812017-12-15 18:27:22 -08001/*
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
17#include <inttypes.h>
18#include <net/if.h>
19#include <string.h>
20#include <unordered_set>
21
22#include <utils/Log.h>
23#include <utils/misc.h>
24
25#include "android-base/file.h"
26#include "android-base/strings.h"
27#include "android-base/unique_fd.h"
28#include "bpf/BpfNetworkStats.h"
29#include "bpf/BpfUtils.h"
30
Lorenzo Colittif9c654c2018-03-01 18:02:15 +090031#ifdef LOG_TAG
32#undef LOG_TAG
33#endif
34
35#define LOG_TAG "BpfNetworkStats"
36
Chenbo Fengf43bf812017-12-15 18:27:22 -080037namespace android {
38namespace bpf {
39
40static const char* BPF_IFACE_STATS = "/proc/net/dev";
41
Chenbo Feng7e974052018-02-28 22:57:21 -080042// The limit for stats received by a unknown interface;
43static const uint64_t MAX_UNKNOWN_IFACE_BYTES = 100*1000;
44
Chenbo Feng06c73642018-03-05 04:10:38 -080045static constexpr uint32_t BPF_OPEN_FLAGS = BPF_F_RDONLY;
Lorenzo Colittif9c654c2018-03-01 18:02:15 +090046
Chenbo Fengf43bf812017-12-15 18:27:22 -080047int bpfGetUidStatsInternal(uid_t uid, Stats* stats, const base::unique_fd& map_fd) {
Chenbo Feng16513482018-03-15 17:59:58 -070048 struct StatsKey nonExistentKey = NONEXISTENT_STATSKEY;
49 struct StatsValue dummyValue;
50 auto processUidStats = [uid, stats](void *key, const base::unique_fd& map_fd) {
51 if (((StatsKey *) key)->uid != uid) {
52 return 0;
Chenbo Fengf43bf812017-12-15 18:27:22 -080053 }
Chenbo Feng16513482018-03-15 17:59:58 -070054 StatsValue statsEntry;
55 int ret = bpf::findMapEntry(map_fd, key, &statsEntry);
56 if (ret) return -errno;
57 stats->rxPackets += statsEntry.rxPackets;
58 stats->txPackets += statsEntry.txPackets;
59 stats->rxBytes += statsEntry.rxBytes;
60 stats->txBytes += statsEntry.txBytes;
61 return 0;
62 };
63 return bpfIterateMap(nonExistentKey, dummyValue, map_fd, processUidStats);
Chenbo Fengf43bf812017-12-15 18:27:22 -080064}
65
66int bpfGetUidStats(uid_t uid, Stats* stats) {
Lorenzo Colittif9c654c2018-03-01 18:02:15 +090067 base::unique_fd uidStatsMap(bpf::mapRetrieve(UID_STATS_MAP_PATH, BPF_OPEN_FLAGS));
Chenbo Fengf43bf812017-12-15 18:27:22 -080068 if (uidStatsMap < 0) {
69 int ret = -errno;
Lorenzo Colittif9c654c2018-03-01 18:02:15 +090070 ALOGE("Opening map fd from %s failed: %s", UID_STATS_MAP_PATH, strerror(errno));
Chenbo Fengf43bf812017-12-15 18:27:22 -080071 return ret;
72 }
73 return bpfGetUidStatsInternal(uid, stats, uidStatsMap);
74}
75
76// TODO: The iface stats read from proc/net/dev contains additional L2 header.
77// Need to adjust the byte length read depend on the packets number before
78// return.
79// Bug: b/72111305
80int bpfGetIfaceStatsInternal(const char* iface, Stats* stats, const char* file) {
81 std::string content;
82 if (!android::base::ReadFileToString(file, &content)) {
83 ALOGE("Cannot read iface stats from: %s", file);
84 return -errno;
85 }
86 std::istringstream stream(content);
87 for (std::string ifaceLine; std::getline(stream, ifaceLine);) {
88 const char* buffer = android::base::Trim(ifaceLine).c_str();
89 char cur_iface[IFNAMSIZ];
90 uint64_t rxBytes, rxPackets, txBytes, txPackets;
91 // Typical iface stats read to parse:
92 // interface rxbytes rxpackets errs drop fifo frame compressed multicast txbytes txpackets \
93 // errs drop fifo colls carrier compressed
94 // lo: 13470483181 57249790 0 0 0 0 0 0 13470483181 57249790 0 0 0 0 0 0
95 int matched = sscanf(buffer,
96 "%[^ :]: %" SCNu64 " %" SCNu64
97 " %*lu %*lu %*lu %*lu %*lu %*lu "
98 "%" SCNu64 " %" SCNu64 "",
99 cur_iface, &rxBytes, &rxPackets, &txBytes, &txPackets);
100 if (matched >= 5) {
101 if (!iface || !strcmp(iface, cur_iface)) {
102 stats->rxBytes += rxBytes;
103 stats->rxPackets += rxPackets;
104 stats->txBytes += txBytes;
105 stats->txPackets += txPackets;
106 }
107 }
108 }
109 stats->tcpRxPackets = -1;
110 stats->tcpTxPackets = -1;
111
112 return 0;
113}
114
115int bpfGetIfaceStats(const char* iface, Stats* stats) {
116 return bpfGetIfaceStatsInternal(iface, stats, BPF_IFACE_STATS);
117}
118
119stats_line populateStatsEntry(const StatsKey& statsKey, const StatsValue& statsEntry,
120 const char* ifname) {
121 stats_line newLine;
122 strlcpy(newLine.iface, ifname, sizeof(newLine.iface));
123 newLine.uid = statsKey.uid;
124 newLine.set = statsKey.counterSet;
125 newLine.tag = statsKey.tag;
Chenbo Fengeac6c472018-02-05 15:06:23 -0800126 newLine.rxPackets = statsEntry.rxPackets;
127 newLine.txPackets = statsEntry.txPackets;
128 newLine.rxBytes = statsEntry.rxBytes;
129 newLine.txBytes = statsEntry.txBytes;
Chenbo Fengf43bf812017-12-15 18:27:22 -0800130 return newLine;
131}
132
Chenbo Feng7e974052018-02-28 22:57:21 -0800133int getIfaceNameFromMap(const base::unique_fd& ifaceMapFd, const base::unique_fd& statsMapFd,
134 char *ifname, StatsKey &curKey, uint64_t *unknownIfaceBytesTotal) {
135 if (bpf::findMapEntry(ifaceMapFd, &curKey.ifaceIndex, ifname) < 0) {
136 StatsValue statsEntry;
137 if (bpf::findMapEntry(statsMapFd, &curKey, &statsEntry) < 0) return -errno;
138 *unknownIfaceBytesTotal += (statsEntry.rxBytes + statsEntry.txBytes);
139 if (*unknownIfaceBytesTotal >= MAX_UNKNOWN_IFACE_BYTES) {
140 ALOGE("Unknown name for ifindex %d with more than %" PRIu64 " bytes of traffic",
141 curKey.ifaceIndex, *unknownIfaceBytesTotal);
142 }
143 return -ENODEV;
144 }
145 return 0;
146}
147
Chenbo Feng16513482018-03-15 17:59:58 -0700148int parseBpfNetworkStatsDetailInternal(std::vector<stats_line>* lines,
149 const std::vector<std::string>& limitIfaces, int limitTag,
150 int limitUid, const base::unique_fd& statsMapFd,
151 const base::unique_fd& ifaceMapFd) {
Chenbo Feng7e974052018-02-28 22:57:21 -0800152 uint64_t unknownIfaceBytesTotal = 0;
Chenbo Feng16513482018-03-15 17:59:58 -0700153 struct StatsKey nonExistentKey = NONEXISTENT_STATSKEY;
154 struct StatsValue dummyValue;
155 auto processDetailUidStats = [lines, &limitIfaces, limitTag, limitUid,
156 &unknownIfaceBytesTotal, &ifaceMapFd]
157 (void* key, const base::unique_fd& statsMapFd) {
158 struct StatsKey curKey = * (struct StatsKey*)key;
Chenbo Feng7e974052018-02-28 22:57:21 -0800159 char ifname[IFNAMSIZ];
160 if (getIfaceNameFromMap(ifaceMapFd, statsMapFd, ifname, curKey, &unknownIfaceBytesTotal)) {
Chenbo Feng16513482018-03-15 17:59:58 -0700161 return 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800162 }
Chenbo Fengf43bf812017-12-15 18:27:22 -0800163 std::string ifnameStr(ifname);
164 if (limitIfaces.size() > 0 &&
165 std::find(limitIfaces.begin(), limitIfaces.end(), ifnameStr) == limitIfaces.end()) {
166 // Nothing matched; skip this line.
Chenbo Feng16513482018-03-15 17:59:58 -0700167 return 0;
Chenbo Fengf43bf812017-12-15 18:27:22 -0800168 }
Chenbo Feng16513482018-03-15 17:59:58 -0700169 if (limitTag != TAG_ALL && uint32_t(limitTag) != curKey.tag) {
170 return 0;
171 }
172 if (limitUid != UID_ALL && uint32_t(limitUid) != curKey.uid) {
173 return 0;
174 }
Chenbo Fengf43bf812017-12-15 18:27:22 -0800175 StatsValue statsEntry;
Chenbo Feng7e974052018-02-28 22:57:21 -0800176 if (bpf::findMapEntry(statsMapFd, &curKey, &statsEntry) < 0) return -errno;
Chenbo Fengf43bf812017-12-15 18:27:22 -0800177 lines->push_back(populateStatsEntry(curKey, statsEntry, ifname));
Chenbo Feng16513482018-03-15 17:59:58 -0700178 return 0;
179 };
180 return bpfIterateMap(nonExistentKey, dummyValue, statsMapFd, processDetailUidStats);
Chenbo Fengf43bf812017-12-15 18:27:22 -0800181}
182
183int parseBpfNetworkStatsDetail(std::vector<stats_line>* lines,
184 const std::vector<std::string>& limitIfaces, int limitTag,
185 int limitUid) {
Chenbo Fengf43bf812017-12-15 18:27:22 -0800186 int ret = 0;
Chenbo Feng7e974052018-02-28 22:57:21 -0800187 base::unique_fd ifaceIndexNameMap(bpf::mapRetrieve(IFACE_INDEX_NAME_MAP_PATH, BPF_OPEN_FLAGS));
188 if (ifaceIndexNameMap < 0) {
189 ret = -errno;
190 ALOGE("get ifaceIndexName map fd failed: %s", strerror(errno));
191 return ret;
192 }
Chenbo Fengf43bf812017-12-15 18:27:22 -0800193
Chenbo Feng16513482018-03-15 17:59:58 -0700194 // If the caller did not pass in TAG_NONE, read tag data.
195 if (limitTag != TAG_NONE) {
196 base::unique_fd tagStatsMap(bpf::mapRetrieve(TAG_STATS_MAP_PATH, BPF_OPEN_FLAGS));
197 if (tagStatsMap < 0) {
198 ret = -errno;
199 ALOGE("get tagStats map fd failed: %s", strerror(errno));
200 return ret;
201 }
202 ret = parseBpfNetworkStatsDetailInternal(lines, limitIfaces, limitTag, limitUid,
203 tagStatsMap, ifaceIndexNameMap);
204 if (ret) return ret;
205 }
206
207 // If the caller did not pass in a specific tag (i.e., if limitTag is TAG_NONE(0) or
208 // TAG_ALL(-1)) read UID data.
209 if (limitTag == TAG_NONE || limitTag == TAG_ALL) {
Lorenzo Colittif9c654c2018-03-01 18:02:15 +0900210 base::unique_fd uidStatsMap(bpf::mapRetrieve(UID_STATS_MAP_PATH, BPF_OPEN_FLAGS));
Chenbo Fengf43bf812017-12-15 18:27:22 -0800211 if (uidStatsMap < 0) {
212 ret = -errno;
Lorenzo Colittif9c654c2018-03-01 18:02:15 +0900213 ALOGE("Opening map fd from %s failed: %s", UID_STATS_MAP_PATH, strerror(errno));
Chenbo Fengf43bf812017-12-15 18:27:22 -0800214 return ret;
215 }
Chenbo Feng16513482018-03-15 17:59:58 -0700216 ret = parseBpfNetworkStatsDetailInternal(lines, limitIfaces, limitTag, limitUid,
217 uidStatsMap, ifaceIndexNameMap);
Chenbo Fengf43bf812017-12-15 18:27:22 -0800218 }
219 return ret;
220}
221
222uint64_t combineUidTag(const uid_t uid, const uint32_t tag) {
223 return (uint64_t)uid << 32 | tag;
224}
225
226// This function get called when the system_server decided to clean up the
227// tagStatsMap after it gethered the information of taggged socket stats. The
228// function go through all the entry in tagStatsMap and remove all the entry
229// for which the tag no longer exists.
230int cleanStatsMapInternal(const base::unique_fd& cookieTagMap, const base::unique_fd& tagStatsMap) {
231 uint64_t curCookie = 0;
232 uint64_t nextCookie = 0;
233 int res;
234 UidTag tmp_uidtag;
235 std::unordered_set<uint64_t> uidTagSet;
236 StatsKey curKey, nextKey;
237
238 // Find all the uid, tag pair exist in cookieTagMap.
239 while (bpf::getNextMapKey(cookieTagMap, &curCookie, &nextCookie) != -1) {
240 curCookie = nextCookie;
241 res = bpf::findMapEntry(cookieTagMap, &curCookie, &tmp_uidtag);
242 if (res < 0) {
243 // might be a concurrent delete, continue to check other entries.
244 continue;
245 }
246 uint64_t uidTag = combineUidTag(tmp_uidtag.uid, tmp_uidtag.tag);
247 uidTagSet.insert(uidTag);
248 }
249
250 // Find all the entries in tagStatsMap where the key is not in the set of
251 // uid, tag pairs found above.
252 curKey = NONEXISTENT_STATSKEY;
253 std::vector<StatsKey> keyList;
254 while (bpf::getNextMapKey(tagStatsMap, &curKey, &nextKey) != -1) {
255 curKey = nextKey;
256 uint64_t uidTag = combineUidTag(curKey.uid, curKey.tag);
257 if (uidTagSet.find(uidTag) == uidTagSet.end()) {
258 keyList.push_back(curKey);
259 }
260 }
261
262 // Delete the entries
263 int size = keyList.size();
264 while (!keyList.empty()) {
265 StatsKey key = keyList.back();
266 keyList.pop_back();
267 res = bpf::deleteMapEntry(tagStatsMap, &key);
268 if (res < 0 && errno != ENOENT) {
269 res = -errno;
270 ALOGE("Failed to delete data(uid=%u, tag=%u): %s\n", key.uid, key.tag, strerror(errno));
271 return res;
272 }
273 }
274 ALOGD("finish clean up, %d stats entry cleaned", size);
275 return 0;
276}
277
278int cleanStatsMap() {
Lorenzo Colittif9c654c2018-03-01 18:02:15 +0900279 base::unique_fd cookieTagMap(bpf::mapRetrieve(COOKIE_UID_MAP_PATH, BPF_OPEN_FLAGS));
Chenbo Fengf43bf812017-12-15 18:27:22 -0800280 int ret = 0;
281 if (cookieTagMap < 0) {
282 ret = -errno;
283 ALOGE("get cookieTag map fd failed: %s", strerror(errno));
284 return ret;
285 }
286
Lorenzo Colittif9c654c2018-03-01 18:02:15 +0900287 base::unique_fd tagStatsMap(bpf::mapRetrieve(TAG_STATS_MAP_PATH, BPF_OPEN_FLAGS));
Chenbo Fengf43bf812017-12-15 18:27:22 -0800288 if (tagStatsMap < 0) {
289 ret = -errno;
290 ALOGE("get tagStats map fd failed: %s", strerror(errno));
291 return ret;
292 }
293
294 return cleanStatsMapInternal(cookieTagMap, tagStatsMap);
295}
296
297} // namespace bpf
298} // namespace android