blob: 31ba6067e37eeab3e3914471a74f68d51c27ef62 [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
Lorenzo Colittif9c654c2018-03-01 18:02:15 +090042// TODO: change this to BPF_F_RDONLY as soon as device kernels have been updated.
43static constexpr uint32_t BPF_OPEN_FLAGS = 0;
44
Chenbo Fengf43bf812017-12-15 18:27:22 -080045int bpfGetUidStatsInternal(uid_t uid, Stats* stats, const base::unique_fd& map_fd) {
46 struct StatsKey curKey, nextKey;
47 curKey = NONEXISTENT_STATSKEY;
48 while (bpf::getNextMapKey(map_fd, &curKey, &nextKey) != -1) {
49 curKey = nextKey;
50 if (curKey.uid == uid) {
51 StatsValue statsEntry;
52 if (bpf::findMapEntry(map_fd, &curKey, &statsEntry) < 0) {
53 return -errno;
54 }
Chenbo Fengeac6c472018-02-05 15:06:23 -080055 stats->rxPackets += statsEntry.rxPackets;
56 stats->txPackets += statsEntry.txPackets;
57 stats->rxBytes += statsEntry.rxBytes;
58 stats->txBytes += statsEntry.txBytes;
Chenbo Fengf43bf812017-12-15 18:27:22 -080059 }
60 }
61 // Return errno if getNextMapKey return error before hit to the end of the map.
62 if (errno != ENOENT) return -errno;
63 return 0;
64}
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
133int parseBpfUidStatsDetail(std::vector<stats_line>* lines,
134 const std::vector<std::string>& limitIfaces, int limitUid,
135 const base::unique_fd& map_fd) {
136 struct StatsKey curKey, nextKey;
137 curKey = NONEXISTENT_STATSKEY;
138 while (bpf::getNextMapKey(map_fd, &curKey, &nextKey) != -1) {
139 curKey = nextKey;
140 char ifname[IFNAMSIZ];
141 // The data entry in uid map that stores removed uid stats use 0 as the
142 // iface. Just skip when seen.
143 if (curKey.ifaceIndex == 0) continue;
144 // this is relatively expensive, involving a context switch and probably contention on the
145 // RTNL lock.
146 // TODO: store iface name in map directly instead of ifindex.
147 if_indextoname(curKey.ifaceIndex, ifname);
148 std::string ifnameStr(ifname);
149 if (limitIfaces.size() > 0 &&
150 std::find(limitIfaces.begin(), limitIfaces.end(), ifnameStr) == limitIfaces.end()) {
151 // Nothing matched; skip this line.
152 continue;
153 }
154 if (limitUid != UID_ALL && limitUid != int(curKey.uid)) continue;
155 StatsValue statsEntry;
156 if (bpf::findMapEntry(map_fd, &curKey, &statsEntry) < 0) {
157 int ret = -errno;
158 ALOGE("get map statsEntry failed: %s", strerror(errno));
159 return ret;
160 }
161 lines->push_back(populateStatsEntry(curKey, statsEntry, ifname));
162 }
163 return 0;
164}
165
166int parseBpfTagStatsDetail(std::vector<stats_line>* lines,
167 const std::vector<std::string>& limitIfaces, int limitTag, int limitUid,
168 const base::unique_fd& map_fd) {
169 struct StatsKey curKey, nextKey;
170 curKey = NONEXISTENT_STATSKEY;
171 while (bpf::getNextMapKey(map_fd, &curKey, &nextKey) != -1) {
172 curKey = nextKey;
173 char ifname[32];
174 if (curKey.ifaceIndex == 0) continue;
175 if_indextoname(curKey.ifaceIndex, ifname);
176 std::string ifnameStr(ifname);
177 if (limitIfaces.size() > 0 &&
178 std::find(limitIfaces.begin(), limitIfaces.end(), ifnameStr) == limitIfaces.end()) {
179 // Nothing matched; skip this line.
180 continue;
181 }
182 if ((limitTag != TAG_ALL && uint32_t(limitTag) != (curKey.tag)) ||
183 (limitUid != UID_ALL && uint32_t(limitUid) != curKey.uid))
184 continue;
185 StatsValue statsEntry;
186 if (bpf::findMapEntry(map_fd, &curKey, &statsEntry) < 0) return -errno;
187 lines->push_back(populateStatsEntry(curKey, statsEntry, ifname));
188 }
189 if (errno != ENOENT) return -errno;
190 return 0;
191}
192
193int parseBpfNetworkStatsDetail(std::vector<stats_line>* lines,
194 const std::vector<std::string>& limitIfaces, int limitTag,
195 int limitUid) {
Lorenzo Colittif9c654c2018-03-01 18:02:15 +0900196 base::unique_fd tagStatsMap(bpf::mapRetrieve(TAG_STATS_MAP_PATH, BPF_OPEN_FLAGS));
Chenbo Fengf43bf812017-12-15 18:27:22 -0800197 int ret = 0;
198 if (tagStatsMap < 0) {
199 ret = -errno;
200 ALOGE("get tagStats map fd failed: %s", strerror(errno));
201 return ret;
202 }
203 ret = parseBpfTagStatsDetail(lines, limitIfaces, limitTag, limitUid, tagStatsMap);
204 if (ret) return ret;
205
206 if (limitTag == TAG_ALL) {
Lorenzo Colittif9c654c2018-03-01 18:02:15 +0900207 base::unique_fd uidStatsMap(bpf::mapRetrieve(UID_STATS_MAP_PATH, BPF_OPEN_FLAGS));
Chenbo Fengf43bf812017-12-15 18:27:22 -0800208 if (uidStatsMap < 0) {
209 ret = -errno;
Lorenzo Colittif9c654c2018-03-01 18:02:15 +0900210 ALOGE("Opening map fd from %s failed: %s", UID_STATS_MAP_PATH, strerror(errno));
Chenbo Fengf43bf812017-12-15 18:27:22 -0800211 return ret;
212 }
213 ret = parseBpfUidStatsDetail(lines, limitIfaces, limitUid, uidStatsMap);
214 }
215 return ret;
216}
217
218uint64_t combineUidTag(const uid_t uid, const uint32_t tag) {
219 return (uint64_t)uid << 32 | tag;
220}
221
222// This function get called when the system_server decided to clean up the
223// tagStatsMap after it gethered the information of taggged socket stats. The
224// function go through all the entry in tagStatsMap and remove all the entry
225// for which the tag no longer exists.
226int cleanStatsMapInternal(const base::unique_fd& cookieTagMap, const base::unique_fd& tagStatsMap) {
227 uint64_t curCookie = 0;
228 uint64_t nextCookie = 0;
229 int res;
230 UidTag tmp_uidtag;
231 std::unordered_set<uint64_t> uidTagSet;
232 StatsKey curKey, nextKey;
233
234 // Find all the uid, tag pair exist in cookieTagMap.
235 while (bpf::getNextMapKey(cookieTagMap, &curCookie, &nextCookie) != -1) {
236 curCookie = nextCookie;
237 res = bpf::findMapEntry(cookieTagMap, &curCookie, &tmp_uidtag);
238 if (res < 0) {
239 // might be a concurrent delete, continue to check other entries.
240 continue;
241 }
242 uint64_t uidTag = combineUidTag(tmp_uidtag.uid, tmp_uidtag.tag);
243 uidTagSet.insert(uidTag);
244 }
245
246 // Find all the entries in tagStatsMap where the key is not in the set of
247 // uid, tag pairs found above.
248 curKey = NONEXISTENT_STATSKEY;
249 std::vector<StatsKey> keyList;
250 while (bpf::getNextMapKey(tagStatsMap, &curKey, &nextKey) != -1) {
251 curKey = nextKey;
252 uint64_t uidTag = combineUidTag(curKey.uid, curKey.tag);
253 if (uidTagSet.find(uidTag) == uidTagSet.end()) {
254 keyList.push_back(curKey);
255 }
256 }
257
258 // Delete the entries
259 int size = keyList.size();
260 while (!keyList.empty()) {
261 StatsKey key = keyList.back();
262 keyList.pop_back();
263 res = bpf::deleteMapEntry(tagStatsMap, &key);
264 if (res < 0 && errno != ENOENT) {
265 res = -errno;
266 ALOGE("Failed to delete data(uid=%u, tag=%u): %s\n", key.uid, key.tag, strerror(errno));
267 return res;
268 }
269 }
270 ALOGD("finish clean up, %d stats entry cleaned", size);
271 return 0;
272}
273
274int cleanStatsMap() {
Lorenzo Colittif9c654c2018-03-01 18:02:15 +0900275 base::unique_fd cookieTagMap(bpf::mapRetrieve(COOKIE_UID_MAP_PATH, BPF_OPEN_FLAGS));
Chenbo Fengf43bf812017-12-15 18:27:22 -0800276 int ret = 0;
277 if (cookieTagMap < 0) {
278 ret = -errno;
279 ALOGE("get cookieTag map fd failed: %s", strerror(errno));
280 return ret;
281 }
282
Lorenzo Colittif9c654c2018-03-01 18:02:15 +0900283 base::unique_fd tagStatsMap(bpf::mapRetrieve(TAG_STATS_MAP_PATH, BPF_OPEN_FLAGS));
Chenbo Fengf43bf812017-12-15 18:27:22 -0800284 if (tagStatsMap < 0) {
285 ret = -errno;
286 ALOGE("get tagStats map fd failed: %s", strerror(errno));
287 return ret;
288 }
289
290 return cleanStatsMapInternal(cookieTagMap, tagStatsMap);
291}
292
293} // namespace bpf
294} // namespace android