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