blob: 5df2dfdf12e45ffc0ac3290be7b5b909df5b8836 [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 Feng06c73642018-03-05 04:10:38 -080042static constexpr uint32_t BPF_OPEN_FLAGS = BPF_F_RDONLY;
Lorenzo Colittif9c654c2018-03-01 18:02:15 +090043
Chenbo Fengf43bf812017-12-15 18:27:22 -080044int bpfGetUidStatsInternal(uid_t uid, Stats* stats, const base::unique_fd& map_fd) {
45 struct StatsKey curKey, nextKey;
46 curKey = NONEXISTENT_STATSKEY;
47 while (bpf::getNextMapKey(map_fd, &curKey, &nextKey) != -1) {
48 curKey = nextKey;
49 if (curKey.uid == uid) {
50 StatsValue statsEntry;
51 if (bpf::findMapEntry(map_fd, &curKey, &statsEntry) < 0) {
52 return -errno;
53 }
Chenbo Fengeac6c472018-02-05 15:06:23 -080054 stats->rxPackets += statsEntry.rxPackets;
55 stats->txPackets += statsEntry.txPackets;
56 stats->rxBytes += statsEntry.rxBytes;
57 stats->txBytes += statsEntry.txBytes;
Chenbo Fengf43bf812017-12-15 18:27:22 -080058 }
59 }
60 // Return errno if getNextMapKey return error before hit to the end of the map.
61 if (errno != ENOENT) return -errno;
62 return 0;
63}
64
65int bpfGetUidStats(uid_t uid, Stats* stats) {
Lorenzo Colittif9c654c2018-03-01 18:02:15 +090066 base::unique_fd uidStatsMap(bpf::mapRetrieve(UID_STATS_MAP_PATH, BPF_OPEN_FLAGS));
Chenbo Fengf43bf812017-12-15 18:27:22 -080067 if (uidStatsMap < 0) {
68 int ret = -errno;
Lorenzo Colittif9c654c2018-03-01 18:02:15 +090069 ALOGE("Opening map fd from %s failed: %s", UID_STATS_MAP_PATH, strerror(errno));
Chenbo Fengf43bf812017-12-15 18:27:22 -080070 return ret;
71 }
72 return bpfGetUidStatsInternal(uid, stats, uidStatsMap);
73}
74
75// TODO: The iface stats read from proc/net/dev contains additional L2 header.
76// Need to adjust the byte length read depend on the packets number before
77// return.
78// Bug: b/72111305
79int bpfGetIfaceStatsInternal(const char* iface, Stats* stats, const char* file) {
80 std::string content;
81 if (!android::base::ReadFileToString(file, &content)) {
82 ALOGE("Cannot read iface stats from: %s", file);
83 return -errno;
84 }
85 std::istringstream stream(content);
86 for (std::string ifaceLine; std::getline(stream, ifaceLine);) {
87 const char* buffer = android::base::Trim(ifaceLine).c_str();
88 char cur_iface[IFNAMSIZ];
89 uint64_t rxBytes, rxPackets, txBytes, txPackets;
90 // Typical iface stats read to parse:
91 // interface rxbytes rxpackets errs drop fifo frame compressed multicast txbytes txpackets \
92 // errs drop fifo colls carrier compressed
93 // lo: 13470483181 57249790 0 0 0 0 0 0 13470483181 57249790 0 0 0 0 0 0
94 int matched = sscanf(buffer,
95 "%[^ :]: %" SCNu64 " %" SCNu64
96 " %*lu %*lu %*lu %*lu %*lu %*lu "
97 "%" SCNu64 " %" SCNu64 "",
98 cur_iface, &rxBytes, &rxPackets, &txBytes, &txPackets);
99 if (matched >= 5) {
100 if (!iface || !strcmp(iface, cur_iface)) {
101 stats->rxBytes += rxBytes;
102 stats->rxPackets += rxPackets;
103 stats->txBytes += txBytes;
104 stats->txPackets += txPackets;
105 }
106 }
107 }
108 stats->tcpRxPackets = -1;
109 stats->tcpTxPackets = -1;
110
111 return 0;
112}
113
114int bpfGetIfaceStats(const char* iface, Stats* stats) {
115 return bpfGetIfaceStatsInternal(iface, stats, BPF_IFACE_STATS);
116}
117
118stats_line populateStatsEntry(const StatsKey& statsKey, const StatsValue& statsEntry,
119 const char* ifname) {
120 stats_line newLine;
121 strlcpy(newLine.iface, ifname, sizeof(newLine.iface));
122 newLine.uid = statsKey.uid;
123 newLine.set = statsKey.counterSet;
124 newLine.tag = statsKey.tag;
Chenbo Fengeac6c472018-02-05 15:06:23 -0800125 newLine.rxPackets = statsEntry.rxPackets;
126 newLine.txPackets = statsEntry.txPackets;
127 newLine.rxBytes = statsEntry.rxBytes;
128 newLine.txBytes = statsEntry.txBytes;
Chenbo Fengf43bf812017-12-15 18:27:22 -0800129 return newLine;
130}
131
132int parseBpfUidStatsDetail(std::vector<stats_line>* lines,
133 const std::vector<std::string>& limitIfaces, int limitUid,
134 const base::unique_fd& map_fd) {
135 struct StatsKey curKey, nextKey;
136 curKey = NONEXISTENT_STATSKEY;
137 while (bpf::getNextMapKey(map_fd, &curKey, &nextKey) != -1) {
138 curKey = nextKey;
139 char ifname[IFNAMSIZ];
140 // The data entry in uid map that stores removed uid stats use 0 as the
141 // iface. Just skip when seen.
142 if (curKey.ifaceIndex == 0) continue;
143 // this is relatively expensive, involving a context switch and probably contention on the
144 // RTNL lock.
145 // TODO: store iface name in map directly instead of ifindex.
146 if_indextoname(curKey.ifaceIndex, ifname);
147 std::string ifnameStr(ifname);
148 if (limitIfaces.size() > 0 &&
149 std::find(limitIfaces.begin(), limitIfaces.end(), ifnameStr) == limitIfaces.end()) {
150 // Nothing matched; skip this line.
151 continue;
152 }
153 if (limitUid != UID_ALL && limitUid != int(curKey.uid)) continue;
154 StatsValue statsEntry;
155 if (bpf::findMapEntry(map_fd, &curKey, &statsEntry) < 0) {
156 int ret = -errno;
157 ALOGE("get map statsEntry failed: %s", strerror(errno));
158 return ret;
159 }
160 lines->push_back(populateStatsEntry(curKey, statsEntry, ifname));
161 }
162 return 0;
163}
164
165int parseBpfTagStatsDetail(std::vector<stats_line>* lines,
166 const std::vector<std::string>& limitIfaces, int limitTag, int limitUid,
167 const base::unique_fd& map_fd) {
168 struct StatsKey curKey, nextKey;
169 curKey = NONEXISTENT_STATSKEY;
170 while (bpf::getNextMapKey(map_fd, &curKey, &nextKey) != -1) {
171 curKey = nextKey;
172 char ifname[32];
173 if (curKey.ifaceIndex == 0) continue;
174 if_indextoname(curKey.ifaceIndex, ifname);
175 std::string ifnameStr(ifname);
176 if (limitIfaces.size() > 0 &&
177 std::find(limitIfaces.begin(), limitIfaces.end(), ifnameStr) == limitIfaces.end()) {
178 // Nothing matched; skip this line.
179 continue;
180 }
181 if ((limitTag != TAG_ALL && uint32_t(limitTag) != (curKey.tag)) ||
182 (limitUid != UID_ALL && uint32_t(limitUid) != curKey.uid))
183 continue;
184 StatsValue statsEntry;
185 if (bpf::findMapEntry(map_fd, &curKey, &statsEntry) < 0) return -errno;
186 lines->push_back(populateStatsEntry(curKey, statsEntry, ifname));
187 }
188 if (errno != ENOENT) return -errno;
189 return 0;
190}
191
192int parseBpfNetworkStatsDetail(std::vector<stats_line>* lines,
193 const std::vector<std::string>& limitIfaces, int limitTag,
194 int limitUid) {
Lorenzo Colittif9c654c2018-03-01 18:02:15 +0900195 base::unique_fd tagStatsMap(bpf::mapRetrieve(TAG_STATS_MAP_PATH, BPF_OPEN_FLAGS));
Chenbo Fengf43bf812017-12-15 18:27:22 -0800196 int ret = 0;
197 if (tagStatsMap < 0) {
198 ret = -errno;
199 ALOGE("get tagStats map fd failed: %s", strerror(errno));
200 return ret;
201 }
202 ret = parseBpfTagStatsDetail(lines, limitIfaces, limitTag, limitUid, tagStatsMap);
203 if (ret) return ret;
204
205 if (limitTag == TAG_ALL) {
Lorenzo Colittif9c654c2018-03-01 18:02:15 +0900206 base::unique_fd uidStatsMap(bpf::mapRetrieve(UID_STATS_MAP_PATH, BPF_OPEN_FLAGS));
Chenbo Fengf43bf812017-12-15 18:27:22 -0800207 if (uidStatsMap < 0) {
208 ret = -errno;
Lorenzo Colittif9c654c2018-03-01 18:02:15 +0900209 ALOGE("Opening map fd from %s failed: %s", UID_STATS_MAP_PATH, strerror(errno));
Chenbo Fengf43bf812017-12-15 18:27:22 -0800210 return ret;
211 }
212 ret = parseBpfUidStatsDetail(lines, limitIfaces, limitUid, uidStatsMap);
213 }
214 return ret;
215}
216
217uint64_t combineUidTag(const uid_t uid, const uint32_t tag) {
218 return (uint64_t)uid << 32 | tag;
219}
220
221// This function get called when the system_server decided to clean up the
222// tagStatsMap after it gethered the information of taggged socket stats. The
223// function go through all the entry in tagStatsMap and remove all the entry
224// for which the tag no longer exists.
225int cleanStatsMapInternal(const base::unique_fd& cookieTagMap, const base::unique_fd& tagStatsMap) {
226 uint64_t curCookie = 0;
227 uint64_t nextCookie = 0;
228 int res;
229 UidTag tmp_uidtag;
230 std::unordered_set<uint64_t> uidTagSet;
231 StatsKey curKey, nextKey;
232
233 // Find all the uid, tag pair exist in cookieTagMap.
234 while (bpf::getNextMapKey(cookieTagMap, &curCookie, &nextCookie) != -1) {
235 curCookie = nextCookie;
236 res = bpf::findMapEntry(cookieTagMap, &curCookie, &tmp_uidtag);
237 if (res < 0) {
238 // might be a concurrent delete, continue to check other entries.
239 continue;
240 }
241 uint64_t uidTag = combineUidTag(tmp_uidtag.uid, tmp_uidtag.tag);
242 uidTagSet.insert(uidTag);
243 }
244
245 // Find all the entries in tagStatsMap where the key is not in the set of
246 // uid, tag pairs found above.
247 curKey = NONEXISTENT_STATSKEY;
248 std::vector<StatsKey> keyList;
249 while (bpf::getNextMapKey(tagStatsMap, &curKey, &nextKey) != -1) {
250 curKey = nextKey;
251 uint64_t uidTag = combineUidTag(curKey.uid, curKey.tag);
252 if (uidTagSet.find(uidTag) == uidTagSet.end()) {
253 keyList.push_back(curKey);
254 }
255 }
256
257 // Delete the entries
258 int size = keyList.size();
259 while (!keyList.empty()) {
260 StatsKey key = keyList.back();
261 keyList.pop_back();
262 res = bpf::deleteMapEntry(tagStatsMap, &key);
263 if (res < 0 && errno != ENOENT) {
264 res = -errno;
265 ALOGE("Failed to delete data(uid=%u, tag=%u): %s\n", key.uid, key.tag, strerror(errno));
266 return res;
267 }
268 }
269 ALOGD("finish clean up, %d stats entry cleaned", size);
270 return 0;
271}
272
273int cleanStatsMap() {
Lorenzo Colittif9c654c2018-03-01 18:02:15 +0900274 base::unique_fd cookieTagMap(bpf::mapRetrieve(COOKIE_UID_MAP_PATH, BPF_OPEN_FLAGS));
Chenbo Fengf43bf812017-12-15 18:27:22 -0800275 int ret = 0;
276 if (cookieTagMap < 0) {
277 ret = -errno;
278 ALOGE("get cookieTag map fd failed: %s", strerror(errno));
279 return ret;
280 }
281
Lorenzo Colittif9c654c2018-03-01 18:02:15 +0900282 base::unique_fd tagStatsMap(bpf::mapRetrieve(TAG_STATS_MAP_PATH, BPF_OPEN_FLAGS));
Chenbo Fengf43bf812017-12-15 18:27:22 -0800283 if (tagStatsMap < 0) {
284 ret = -errno;
285 ALOGE("get tagStats map fd failed: %s", strerror(errno));
286 return ret;
287 }
288
289 return cleanStatsMapInternal(cookieTagMap, tagStatsMap);
290}
291
292} // namespace bpf
293} // namespace android