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