blob: 99e98314997d2a4d60df504b85bc27e34ff60c65 [file] [log] [blame]
Wayne Ma4d692332022-01-19 16:04:04 +08001/*
Wayne Ma7be6bce2022-01-12 16:29:49 +08002 * Copyright 2022 The Android Open Source Project
Wayne Ma4d692332022-01-19 16:04:04 +08003 *
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 * TrafficControllerTest.cpp - unit tests for TrafficController.cpp
17 */
18
19#include <cstdint>
20#include <string>
21#include <vector>
22
23#include <fcntl.h>
24#include <inttypes.h>
25#include <linux/inet_diag.h>
26#include <linux/sock_diag.h>
27#include <sys/socket.h>
28#include <sys/types.h>
29#include <unistd.h>
30
31#include <gtest/gtest.h>
32
Ken Chen2fb86362022-06-05 11:39:38 +080033#include <android-base/file.h>
Ken Chen0dd74952022-06-06 18:25:18 +080034#include <android-base/logging.h>
Wayne Ma4d692332022-01-19 16:04:04 +080035#include <android-base/stringprintf.h>
36#include <android-base/strings.h>
Wayne Ma7be6bce2022-01-12 16:29:49 +080037#include <binder/Status.h>
Wayne Ma4d692332022-01-19 16:04:04 +080038
39#include <netdutils/MockSyscalls.h>
40
Maciej Żenczykowski01319d92022-06-13 18:25:34 -070041#define BPF_MAP_MAKE_VISIBLE_FOR_TESTING
Wayne Ma4d692332022-01-19 16:04:04 +080042#include "TrafficController.h"
43#include "bpf/BpfUtils.h"
Patrick Rohr61e94672022-02-01 21:06:40 +010044#include "NetdUpdatablePublic.h"
Wayne Ma4d692332022-01-19 16:04:04 +080045
46using namespace android::bpf; // NOLINT(google-build-using-namespace): grandfathered
47
48namespace android {
49namespace net {
50
Wayne Ma7be6bce2022-01-12 16:29:49 +080051using android::netdutils::Status;
Wayne Ma4d692332022-01-19 16:04:04 +080052using base::Result;
53using netdutils::isOk;
Ken Chen2fb86362022-06-05 11:39:38 +080054using netdutils::statusFromErrno;
Wayne Ma4d692332022-01-19 16:04:04 +080055
56constexpr int TEST_MAP_SIZE = 10;
Wayne Ma4d692332022-01-19 16:04:04 +080057constexpr uid_t TEST_UID = 10086;
58constexpr uid_t TEST_UID2 = 54321;
59constexpr uid_t TEST_UID3 = 98765;
60constexpr uint32_t TEST_TAG = 42;
61constexpr uint32_t TEST_COUNTERSET = 1;
Ken Chen0dd74952022-06-06 18:25:18 +080062constexpr int TEST_IFINDEX = 999;
63constexpr int RXPACKETS = 1;
64constexpr int RXBYTES = 100;
65constexpr int TXPACKETS = 0;
66constexpr int TXBYTES = 0;
Wayne Ma4d692332022-01-19 16:04:04 +080067
68#define ASSERT_VALID(x) ASSERT_TRUE((x).isValid())
Hungming Chen410bb122022-06-09 01:32:00 +080069#define ASSERT_INVALID(x) ASSERT_FALSE((x).isValid())
Wayne Ma4d692332022-01-19 16:04:04 +080070
71class TrafficControllerTest : public ::testing::Test {
72 protected:
Wayne Ma92d80792022-01-20 13:20:34 +080073 TrafficControllerTest() {}
Wayne Ma4d692332022-01-19 16:04:04 +080074 TrafficController mTc;
75 BpfMap<uint64_t, UidTagValue> mFakeCookieTagMap;
Wayne Ma4d692332022-01-19 16:04:04 +080076 BpfMap<uint32_t, StatsValue> mFakeAppUidStatsMap;
77 BpfMap<StatsKey, StatsValue> mFakeStatsMapA;
Hungming Chen410bb122022-06-09 01:32:00 +080078 BpfMap<StatsKey, StatsValue> mFakeStatsMapB; // makeTrafficControllerMapsInvalid only
79 BpfMap<uint32_t, StatsValue> mFakeIfaceStatsMap; ; // makeTrafficControllerMapsInvalid only
Lorenzo Colitti60cbed32022-03-03 17:49:01 +090080 BpfMap<uint32_t, uint32_t> mFakeConfigurationMap;
Wayne Ma4d692332022-01-19 16:04:04 +080081 BpfMap<uint32_t, UidOwnerValue> mFakeUidOwnerMap;
82 BpfMap<uint32_t, uint8_t> mFakeUidPermissionMap;
Ken Chen0dd74952022-06-06 18:25:18 +080083 BpfMap<uint32_t, uint8_t> mFakeUidCounterSetMap;
84 BpfMap<uint32_t, IfaceValue> mFakeIfaceIndexNameMap;
Wayne Ma4d692332022-01-19 16:04:04 +080085
86 void SetUp() {
87 std::lock_guard guard(mTc.mMutex);
88 ASSERT_EQ(0, setrlimitForTest());
89
Maciej Żenczykowski439bac22022-05-31 03:22:32 -070090 mFakeCookieTagMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +080091 ASSERT_VALID(mFakeCookieTagMap);
92
Maciej Żenczykowski439bac22022-05-31 03:22:32 -070093 mFakeAppUidStatsMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +080094 ASSERT_VALID(mFakeAppUidStatsMap);
95
Maciej Żenczykowski439bac22022-05-31 03:22:32 -070096 mFakeStatsMapA.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +080097 ASSERT_VALID(mFakeStatsMapA);
98
Maciej Żenczykowskib10e0552022-06-16 14:49:27 -070099 mFakeConfigurationMap.resetMap(BPF_MAP_TYPE_ARRAY, CONFIGURATION_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +0800100 ASSERT_VALID(mFakeConfigurationMap);
101
Maciej Żenczykowski439bac22022-05-31 03:22:32 -0700102 mFakeUidOwnerMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +0800103 ASSERT_VALID(mFakeUidOwnerMap);
Maciej Żenczykowski439bac22022-05-31 03:22:32 -0700104 mFakeUidPermissionMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
Wayne Ma4d692332022-01-19 16:04:04 +0800105 ASSERT_VALID(mFakeUidPermissionMap);
106
Ken Chen0dd74952022-06-06 18:25:18 +0800107 mFakeUidCounterSetMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
108 ASSERT_VALID(mFakeUidCounterSetMap);
109
110 mFakeIfaceIndexNameMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
111 ASSERT_VALID(mFakeIfaceIndexNameMap);
112
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700113 mTc.mCookieTagMap = mFakeCookieTagMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800114 ASSERT_VALID(mTc.mCookieTagMap);
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700115 mTc.mAppUidStatsMap = mFakeAppUidStatsMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800116 ASSERT_VALID(mTc.mAppUidStatsMap);
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700117 mTc.mStatsMapA = mFakeStatsMapA;
Wayne Ma4d692332022-01-19 16:04:04 +0800118 ASSERT_VALID(mTc.mStatsMapA);
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700119 mTc.mConfigurationMap = mFakeConfigurationMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800120 ASSERT_VALID(mTc.mConfigurationMap);
121
122 // Always write to stats map A by default.
Maciej Żenczykowskib10e0552022-06-16 14:49:27 -0700123 static_assert(SELECT_MAP_A == 0);
124
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700125 mTc.mUidOwnerMap = mFakeUidOwnerMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800126 ASSERT_VALID(mTc.mUidOwnerMap);
Maciej Żenczykowski55ab87a2022-05-31 03:15:12 -0700127 mTc.mUidPermissionMap = mFakeUidPermissionMap;
Wayne Ma4d692332022-01-19 16:04:04 +0800128 ASSERT_VALID(mTc.mUidPermissionMap);
129 mTc.mPrivilegedUser.clear();
Ken Chen0dd74952022-06-06 18:25:18 +0800130
131 mTc.mUidCounterSetMap = mFakeUidCounterSetMap;
132 ASSERT_VALID(mTc.mUidCounterSetMap);
133
134 mTc.mIfaceIndexNameMap = mFakeIfaceIndexNameMap;
135 ASSERT_VALID(mTc.mIfaceIndexNameMap);
Wayne Ma4d692332022-01-19 16:04:04 +0800136 }
137
Wayne Ma4d692332022-01-19 16:04:04 +0800138 void populateFakeStats(uint64_t cookie, uint32_t uid, uint32_t tag, StatsKey* key) {
139 UidTagValue cookieMapkey = {.uid = (uint32_t)uid, .tag = tag};
140 EXPECT_RESULT_OK(mFakeCookieTagMap.writeValue(cookie, cookieMapkey, BPF_ANY));
Ken Chen0dd74952022-06-06 18:25:18 +0800141 *key = {.uid = uid, .tag = tag, .counterSet = TEST_COUNTERSET, .ifaceIndex = TEST_IFINDEX};
142 StatsValue statsMapValue = {.rxPackets = RXPACKETS, .rxBytes = RXBYTES,
143 .txPackets = TXPACKETS, .txBytes = TXBYTES};
Wayne Ma4d692332022-01-19 16:04:04 +0800144 EXPECT_RESULT_OK(mFakeStatsMapA.writeValue(*key, statsMapValue, BPF_ANY));
145 EXPECT_RESULT_OK(mFakeAppUidStatsMap.writeValue(uid, statsMapValue, BPF_ANY));
146 // put tag information back to statsKey
147 key->tag = tag;
148 }
149
Ken Chen0dd74952022-06-06 18:25:18 +0800150 void populateFakeCounterSet(uint32_t uid, uint32_t counterSet) {
151 EXPECT_RESULT_OK(mFakeUidCounterSetMap.writeValue(uid, counterSet, BPF_ANY));
152 }
153
154 void populateFakeIfaceIndexName(const char* name, uint32_t ifaceIndex) {
155 if (name == nullptr || ifaceIndex <= 0) return;
156
157 IfaceValue iface;
158 strlcpy(iface.name, name, sizeof(IfaceValue));
159 EXPECT_RESULT_OK(mFakeIfaceIndexNameMap.writeValue(ifaceIndex, iface, BPF_ANY));
160 }
161
Wayne Ma4d692332022-01-19 16:04:04 +0800162 void checkUidOwnerRuleForChain(ChildChain chain, UidOwnerMatchType match) {
163 uint32_t uid = TEST_UID;
164 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, DENY, DENYLIST));
165 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
166 EXPECT_RESULT_OK(value);
167 EXPECT_TRUE(value.value().rule & match);
168
169 uid = TEST_UID2;
170 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, ALLOW, ALLOWLIST));
171 value = mFakeUidOwnerMap.readValue(uid);
172 EXPECT_RESULT_OK(value);
173 EXPECT_TRUE(value.value().rule & match);
174
175 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, DENY, ALLOWLIST));
176 value = mFakeUidOwnerMap.readValue(uid);
177 EXPECT_FALSE(value.ok());
178 EXPECT_EQ(ENOENT, value.error().code());
179
180 uid = TEST_UID;
181 EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, ALLOW, DENYLIST));
182 value = mFakeUidOwnerMap.readValue(uid);
183 EXPECT_FALSE(value.ok());
184 EXPECT_EQ(ENOENT, value.error().code());
185
186 uid = TEST_UID3;
187 EXPECT_EQ(-ENOENT, mTc.changeUidOwnerRule(chain, uid, ALLOW, DENYLIST));
188 value = mFakeUidOwnerMap.readValue(uid);
189 EXPECT_FALSE(value.ok());
190 EXPECT_EQ(ENOENT, value.error().code());
191 }
192
193 void checkEachUidValue(const std::vector<int32_t>& uids, UidOwnerMatchType match) {
194 for (uint32_t uid : uids) {
195 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
196 EXPECT_RESULT_OK(value);
197 EXPECT_TRUE(value.value().rule & match);
198 }
199 std::set<uint32_t> uidSet(uids.begin(), uids.end());
200 const auto checkNoOtherUid = [&uidSet](const int32_t& key,
201 const BpfMap<uint32_t, UidOwnerValue>&) {
202 EXPECT_NE(uidSet.end(), uidSet.find(key));
203 return Result<void>();
204 };
205 EXPECT_RESULT_OK(mFakeUidOwnerMap.iterate(checkNoOtherUid));
206 }
207
208 void checkUidMapReplace(const std::string& name, const std::vector<int32_t>& uids,
209 UidOwnerMatchType match) {
210 bool isAllowlist = true;
211 EXPECT_EQ(0, mTc.replaceUidOwnerMap(name, isAllowlist, uids));
212 checkEachUidValue(uids, match);
213
214 isAllowlist = false;
215 EXPECT_EQ(0, mTc.replaceUidOwnerMap(name, isAllowlist, uids));
216 checkEachUidValue(uids, match);
217 }
218
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000219 void expectUidOwnerMapValues(const std::vector<uint32_t>& appUids, uint32_t expectedRule,
Wayne Ma4d692332022-01-19 16:04:04 +0800220 uint32_t expectedIif) {
221 for (uint32_t uid : appUids) {
222 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
223 EXPECT_RESULT_OK(value);
224 EXPECT_EQ(expectedRule, value.value().rule)
225 << "Expected rule for UID " << uid << " to be " << expectedRule << ", but was "
226 << value.value().rule;
227 EXPECT_EQ(expectedIif, value.value().iif)
228 << "Expected iif for UID " << uid << " to be " << expectedIif << ", but was "
229 << value.value().iif;
230 }
231 }
232
233 template <class Key, class Value>
234 void expectMapEmpty(BpfMap<Key, Value>& map) {
235 auto isEmpty = map.isEmpty();
236 EXPECT_RESULT_OK(isEmpty);
237 EXPECT_TRUE(isEmpty.value());
238 }
239
240 void expectUidPermissionMapValues(const std::vector<uid_t>& appUids, uint8_t expectedValue) {
241 for (uid_t uid : appUids) {
242 Result<uint8_t> value = mFakeUidPermissionMap.readValue(uid);
243 EXPECT_RESULT_OK(value);
244 EXPECT_EQ(expectedValue, value.value())
245 << "Expected value for UID " << uid << " to be " << expectedValue
246 << ", but was " << value.value();
247 }
248 }
249
250 void expectPrivilegedUserSet(const std::vector<uid_t>& appUids) {
251 std::lock_guard guard(mTc.mMutex);
252 EXPECT_EQ(appUids.size(), mTc.mPrivilegedUser.size());
253 for (uid_t uid : appUids) {
254 EXPECT_NE(mTc.mPrivilegedUser.end(), mTc.mPrivilegedUser.find(uid));
255 }
256 }
257
258 void expectPrivilegedUserSetEmpty() {
259 std::lock_guard guard(mTc.mMutex);
260 EXPECT_TRUE(mTc.mPrivilegedUser.empty());
261 }
262
Wayne Ma7be6bce2022-01-12 16:29:49 +0800263 Status updateUidOwnerMaps(const std::vector<uint32_t>& appUids,
264 UidOwnerMatchType matchType, TrafficController::IptOp op) {
265 Status ret(0);
266 for (auto uid : appUids) {
267 ret = mTc.updateUidOwnerMap(uid, matchType, op);
268 if(!isOk(ret)) break;
269 }
270 return ret;
271 }
Wayne Ma4d692332022-01-19 16:04:04 +0800272};
273
Wayne Ma4d692332022-01-19 16:04:04 +0800274TEST_F(TrafficControllerTest, TestUpdateOwnerMapEntry) {
275 uint32_t uid = TEST_UID;
276 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, DENY, DENYLIST)));
277 Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
278 ASSERT_RESULT_OK(value);
279 ASSERT_TRUE(value.value().rule & STANDBY_MATCH);
280
281 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(DOZABLE_MATCH, uid, ALLOW, ALLOWLIST)));
282 value = mFakeUidOwnerMap.readValue(uid);
283 ASSERT_RESULT_OK(value);
284 ASSERT_TRUE(value.value().rule & DOZABLE_MATCH);
285
286 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(DOZABLE_MATCH, uid, DENY, ALLOWLIST)));
287 value = mFakeUidOwnerMap.readValue(uid);
288 ASSERT_RESULT_OK(value);
289 ASSERT_FALSE(value.value().rule & DOZABLE_MATCH);
290
291 ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, ALLOW, DENYLIST)));
292 ASSERT_FALSE(mFakeUidOwnerMap.readValue(uid).ok());
293
294 uid = TEST_UID2;
295 ASSERT_FALSE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, ALLOW, DENYLIST)));
296 ASSERT_FALSE(mFakeUidOwnerMap.readValue(uid).ok());
297}
298
299TEST_F(TrafficControllerTest, TestChangeUidOwnerRule) {
300 checkUidOwnerRuleForChain(DOZABLE, DOZABLE_MATCH);
301 checkUidOwnerRuleForChain(STANDBY, STANDBY_MATCH);
302 checkUidOwnerRuleForChain(POWERSAVE, POWERSAVE_MATCH);
303 checkUidOwnerRuleForChain(RESTRICTED, RESTRICTED_MATCH);
Robert Horvathd945bf02022-01-27 19:55:16 +0100304 checkUidOwnerRuleForChain(LOW_POWER_STANDBY, LOW_POWER_STANDBY_MATCH);
Motomu Utsumid9801492022-06-01 13:57:27 +0000305 checkUidOwnerRuleForChain(OEM_DENY_1, OEM_DENY_1_MATCH);
306 checkUidOwnerRuleForChain(OEM_DENY_2, OEM_DENY_2_MATCH);
Motomu Utsumi1d9054b2022-06-06 07:44:05 +0000307 checkUidOwnerRuleForChain(OEM_DENY_3, OEM_DENY_3_MATCH);
Wayne Ma4d692332022-01-19 16:04:04 +0800308 ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(NONE, TEST_UID, ALLOW, ALLOWLIST));
309 ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(INVALID_CHAIN, TEST_UID, ALLOW, ALLOWLIST));
310}
311
312TEST_F(TrafficControllerTest, TestReplaceUidOwnerMap) {
313 std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
314 checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
315 checkUidMapReplace("fw_standby", uids, STANDBY_MATCH);
316 checkUidMapReplace("fw_powersave", uids, POWERSAVE_MATCH);
317 checkUidMapReplace("fw_restricted", uids, RESTRICTED_MATCH);
Robert Horvathd945bf02022-01-27 19:55:16 +0100318 checkUidMapReplace("fw_low_power_standby", uids, LOW_POWER_STANDBY_MATCH);
Motomu Utsumid9801492022-06-01 13:57:27 +0000319 checkUidMapReplace("fw_oem_deny_1", uids, OEM_DENY_1_MATCH);
320 checkUidMapReplace("fw_oem_deny_2", uids, OEM_DENY_2_MATCH);
Motomu Utsumi1d9054b2022-06-06 07:44:05 +0000321 checkUidMapReplace("fw_oem_deny_3", uids, OEM_DENY_3_MATCH);
Wayne Ma4d692332022-01-19 16:04:04 +0800322 ASSERT_EQ(-EINVAL, mTc.replaceUidOwnerMap("unknow", true, uids));
323}
324
325TEST_F(TrafficControllerTest, TestReplaceSameChain) {
326 std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
327 checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
328 std::vector<int32_t> newUids = {TEST_UID2, TEST_UID3};
329 checkUidMapReplace("fw_dozable", newUids, DOZABLE_MATCH);
330}
331
332TEST_F(TrafficControllerTest, TestDenylistUidMatch) {
333 std::vector<uint32_t> appUids = {1000, 1001, 10012};
Wayne Ma7be6bce2022-01-12 16:29:49 +0800334 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
335 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800336 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
Wayne Ma7be6bce2022-01-12 16:29:49 +0800337 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
338 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800339 expectMapEmpty(mFakeUidOwnerMap);
340}
341
342TEST_F(TrafficControllerTest, TestAllowlistUidMatch) {
343 std::vector<uint32_t> appUids = {1000, 1001, 10012};
Wayne Ma7be6bce2022-01-12 16:29:49 +0800344 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800345 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
Wayne Ma7be6bce2022-01-12 16:29:49 +0800346 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800347 expectMapEmpty(mFakeUidOwnerMap);
348}
349
350TEST_F(TrafficControllerTest, TestReplaceMatchUid) {
351 std::vector<uint32_t> appUids = {1000, 1001, 10012};
352 // Add appUids to the denylist and expect that their values are all PENALTY_BOX_MATCH.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800353 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
354 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800355 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
356
357 // Add the same UIDs to the allowlist and expect that we get PENALTY_BOX_MATCH |
358 // HAPPY_BOX_MATCH.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800359 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800360 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH | PENALTY_BOX_MATCH, 0);
361
362 // Remove the same UIDs from the allowlist and check the PENALTY_BOX_MATCH is still there.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800363 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800364 expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
365
366 // Remove the same UIDs from the denylist and check the map is empty.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800367 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
368 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800369 ASSERT_FALSE(mFakeUidOwnerMap.getFirstKey().ok());
370}
371
372TEST_F(TrafficControllerTest, TestDeleteWrongMatchSilentlyFails) {
373 std::vector<uint32_t> appUids = {1000, 1001, 10012};
374 // If the uid does not exist in the map, trying to delete a rule about it will fail.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800375 ASSERT_FALSE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
376 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800377 expectMapEmpty(mFakeUidOwnerMap);
378
379 // Add denylist rules for appUids.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800380 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
381 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800382 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
383
384 // Delete (non-existent) denylist rules for appUids, and check that this silently does
385 // nothing if the uid is in the map but does not have denylist match. This is required because
386 // NetworkManagementService will try to remove a uid from denylist after adding it to the
387 // allowlist and if the remove fails it will not update the uid status.
Wayne Ma7be6bce2022-01-12 16:29:49 +0800388 ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
389 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800390 expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
391}
392
393TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRules) {
394 int iif0 = 15;
395 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
396 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
397
398 // Add some non-overlapping new uids. They should coexist with existing rules
399 int iif1 = 16;
400 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
401 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
402 expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
403
404 // Overwrite some existing uids
405 int iif2 = 17;
406 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif2, {1000, 2000})));
407 expectUidOwnerMapValues({1001}, IIF_MATCH, iif0);
408 expectUidOwnerMapValues({2001}, IIF_MATCH, iif1);
409 expectUidOwnerMapValues({1000, 2000}, IIF_MATCH, iif2);
410}
411
412TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRules) {
413 int iif0 = 15;
414 int iif1 = 16;
415 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
416 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
417 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
418 expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
419
420 // Rmove some uids
421 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001, 2001})));
422 expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
423 expectUidOwnerMapValues({2000}, IIF_MATCH, iif1);
424 checkEachUidValue({1000, 2000}, IIF_MATCH); // Make sure there are only two uids remaining
425
426 // Remove non-existent uids shouldn't fail
427 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({2000, 3000})));
428 expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
429 checkEachUidValue({1000}, IIF_MATCH); // Make sure there are only one uid remaining
430
431 // Remove everything
432 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
433 expectMapEmpty(mFakeUidOwnerMap);
434}
435
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000436TEST_F(TrafficControllerTest, TestUpdateUidLockdownRule) {
437 // Add Lockdown rules
438 ASSERT_TRUE(isOk(mTc.updateUidLockdownRule(1000, true /* add */)));
439 ASSERT_TRUE(isOk(mTc.updateUidLockdownRule(1001, true /* add */)));
440 expectUidOwnerMapValues({1000, 1001}, LOCKDOWN_VPN_MATCH, 0);
441
442 // Remove one of Lockdown rules
443 ASSERT_TRUE(isOk(mTc.updateUidLockdownRule(1000, false /* add */)));
444 expectUidOwnerMapValues({1001}, LOCKDOWN_VPN_MATCH, 0);
445
446 // Remove remaining Lockdown rule
447 ASSERT_TRUE(isOk(mTc.updateUidLockdownRule(1001, false /* add */)));
448 expectMapEmpty(mFakeUidOwnerMap);
449}
450
Wayne Ma4d692332022-01-19 16:04:04 +0800451TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithExistingMatches) {
452 // Set up existing PENALTY_BOX_MATCH rules
Wayne Ma7be6bce2022-01-12 16:29:49 +0800453 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000, 1001, 10012}, PENALTY_BOX_MATCH,
454 TrafficController::IptOpInsert)));
Wayne Ma4d692332022-01-19 16:04:04 +0800455 expectUidOwnerMapValues({1000, 1001, 10012}, PENALTY_BOX_MATCH, 0);
456
457 // Add some partially-overlapping uid owner rules and check result
458 int iif1 = 32;
459 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10012, 10013, 10014})));
460 expectUidOwnerMapValues({1000, 1001}, PENALTY_BOX_MATCH, 0);
461 expectUidOwnerMapValues({10012}, PENALTY_BOX_MATCH | IIF_MATCH, iif1);
462 expectUidOwnerMapValues({10013, 10014}, IIF_MATCH, iif1);
463
464 // Removing some PENALTY_BOX_MATCH rules should not change uid interface rule
Wayne Ma7be6bce2022-01-12 16:29:49 +0800465 ASSERT_TRUE(isOk(updateUidOwnerMaps({1001, 10012}, PENALTY_BOX_MATCH,
466 TrafficController::IptOpDelete)));
Wayne Ma4d692332022-01-19 16:04:04 +0800467 expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
468 expectUidOwnerMapValues({10012, 10013, 10014}, IIF_MATCH, iif1);
469
470 // Remove all uid interface rules
471 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({10012, 10013, 10014})));
472 expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
473 // Make sure these are the only uids left
474 checkEachUidValue({1000}, PENALTY_BOX_MATCH);
475}
476
477TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithNewMatches) {
478 int iif1 = 56;
479 // Set up existing uid interface rules
480 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10001, 10002})));
481 expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
482
483 // Add some partially-overlapping doze rules
484 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {10002, 10003}));
485 expectUidOwnerMapValues({10001}, IIF_MATCH, iif1);
486 expectUidOwnerMapValues({10002}, DOZABLE_MATCH | IIF_MATCH, iif1);
487 expectUidOwnerMapValues({10003}, DOZABLE_MATCH, 0);
488
489 // Introduce a third rule type (powersave) on various existing UIDs
490 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {10000, 10001, 10002, 10003}));
491 expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
492 expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
493 expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif1);
494 expectUidOwnerMapValues({10003}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
495
496 // Remove all doze rules
497 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {}));
498 expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
499 expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
500 expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | IIF_MATCH, iif1);
501 expectUidOwnerMapValues({10003}, POWERSAVE_MATCH, 0);
502
503 // Remove all powersave rules, expect ownerMap to only have uid interface rules left
504 EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {}));
505 expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
506 // Make sure these are the only uids left
507 checkEachUidValue({10001, 10002}, IIF_MATCH);
508}
509
Motomu Utsumib08654c2022-05-11 05:56:26 +0000510TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRulesWithWildcard) {
511 // iif=0 is a wildcard
512 int iif = 0;
513 // Add interface rule with wildcard to uids
514 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000, 1001})));
515 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif);
516}
517
518TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRulesWithWildcard) {
519 // iif=0 is a wildcard
520 int iif = 0;
521 // Add interface rule with wildcard to two uids
522 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000, 1001})));
523 expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif);
524
525 // Remove interface rule from one of the uids
526 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
527 expectUidOwnerMapValues({1001}, IIF_MATCH, iif);
528 checkEachUidValue({1001}, IIF_MATCH);
529
530 // Remove interface rule from the remaining uid
531 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001})));
532 expectMapEmpty(mFakeUidOwnerMap);
533}
534
535TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesWithWildcardAndExistingMatches) {
536 // Set up existing DOZABLE_MATCH and POWERSAVE_MATCH rule
537 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
538 TrafficController::IptOpInsert)));
539 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
540 TrafficController::IptOpInsert)));
541
542 // iif=0 is a wildcard
543 int iif = 0;
544 // Add interface rule with wildcard to the existing uid
545 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000})));
546 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif);
547
548 // Remove interface rule with wildcard from the existing uid
549 ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
550 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
551}
552
553TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesWithWildcardAndNewMatches) {
554 // iif=0 is a wildcard
555 int iif = 0;
556 // Set up existing interface rule with wildcard
557 ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000})));
558
559 // Add DOZABLE_MATCH and POWERSAVE_MATCH rule to the existing uid
560 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
561 TrafficController::IptOpInsert)));
562 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
563 TrafficController::IptOpInsert)));
564 expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif);
565
566 // Remove DOZABLE_MATCH and POWERSAVE_MATCH rule from the existing uid
567 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
568 TrafficController::IptOpDelete)));
569 ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
570 TrafficController::IptOpDelete)));
571 expectUidOwnerMapValues({1000}, IIF_MATCH, iif);
572}
573
Wayne Ma4d692332022-01-19 16:04:04 +0800574TEST_F(TrafficControllerTest, TestGrantInternetPermission) {
575 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
576
577 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
578 expectMapEmpty(mFakeUidPermissionMap);
579 expectPrivilegedUserSetEmpty();
580}
581
582TEST_F(TrafficControllerTest, TestRevokeInternetPermission) {
583 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
584
585 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
586 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
587}
588
589TEST_F(TrafficControllerTest, TestPermissionUninstalled) {
590 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
591
592 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
593 expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
594 expectPrivilegedUserSet(appUids);
595
596 std::vector<uid_t> uidToRemove = {TEST_UID};
597 mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidToRemove);
598
599 std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
600 expectUidPermissionMapValues(uidRemain, INetd::PERMISSION_UPDATE_DEVICE_STATS);
601 expectPrivilegedUserSet(uidRemain);
602
603 mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidRemain);
604 expectMapEmpty(mFakeUidPermissionMap);
605 expectPrivilegedUserSetEmpty();
606}
607
608TEST_F(TrafficControllerTest, TestGrantUpdateStatsPermission) {
609 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
610
611 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
612 expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
613 expectPrivilegedUserSet(appUids);
614
615 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
616 expectPrivilegedUserSetEmpty();
617 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
618}
619
620TEST_F(TrafficControllerTest, TestRevokeUpdateStatsPermission) {
621 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
622
623 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
624 expectPrivilegedUserSet(appUids);
625
626 std::vector<uid_t> uidToRemove = {TEST_UID};
627 mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidToRemove);
628
629 std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
630 expectPrivilegedUserSet(uidRemain);
631
632 mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidRemain);
633 expectPrivilegedUserSetEmpty();
634}
635
636TEST_F(TrafficControllerTest, TestGrantWrongPermission) {
637 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
638
639 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
640 expectPrivilegedUserSetEmpty();
641 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
642}
643
644TEST_F(TrafficControllerTest, TestGrantDuplicatePermissionSlientlyFail) {
645 std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
646
647 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
648 expectMapEmpty(mFakeUidPermissionMap);
649
650 std::vector<uid_t> uidToAdd = {TEST_UID};
651 mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, uidToAdd);
652
653 expectPrivilegedUserSetEmpty();
654
655 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
656 expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
657
658 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
659 expectPrivilegedUserSet(appUids);
660
661 mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, uidToAdd);
662 expectPrivilegedUserSet(appUids);
663
664 mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
665 expectPrivilegedUserSetEmpty();
666}
667
Ken Chen77a6b712022-06-06 12:46:36 +0800668TEST_F(TrafficControllerTest, getFirewallType) {
669 static const struct TestConfig {
670 ChildChain childChain;
671 FirewallType firewallType;
672 } testConfigs[] = {
673 // clang-format off
674 {NONE, DENYLIST},
675 {DOZABLE, ALLOWLIST},
676 {STANDBY, DENYLIST},
677 {POWERSAVE, ALLOWLIST},
678 {RESTRICTED, ALLOWLIST},
679 {LOW_POWER_STANDBY, ALLOWLIST},
Ken Chen77a6b712022-06-06 12:46:36 +0800680 {OEM_DENY_1, DENYLIST},
681 {OEM_DENY_2, DENYLIST},
Ken Chend3a3af52022-06-08 02:54:09 +0000682 {OEM_DENY_3, DENYLIST},
Ken Chen77a6b712022-06-06 12:46:36 +0800683 {INVALID_CHAIN, DENYLIST},
684 // clang-format on
685 };
686
687 for (const auto& config : testConfigs) {
688 SCOPED_TRACE(fmt::format("testConfig: [{}, {}]", config.childChain, config.firewallType));
689 EXPECT_EQ(config.firewallType, mTc.getFirewallType(config.childChain));
690 }
691}
692
Patrick Rohr61e94672022-02-01 21:06:40 +0100693constexpr uint32_t SOCK_CLOSE_WAIT_US = 30 * 1000;
694constexpr uint32_t ENOBUFS_POLL_WAIT_US = 10 * 1000;
695
696using android::base::Error;
697using android::base::Result;
698using android::bpf::BpfMap;
699
700// This test set up a SkDestroyListener that is running parallel with the production
701// SkDestroyListener. The test will create thousands of sockets and tag them on the
702// production cookieUidTagMap and close them in a short time. When the number of
703// sockets get closed exceeds the buffer size, it will start to return ENOBUFF
704// error. The error will be ignored by the production SkDestroyListener and the
705// test will clean up the tags in tearDown if there is any remains.
706
707// TODO: Instead of test the ENOBUFF error, we can test the production
708// SkDestroyListener to see if it failed to delete a tagged socket when ENOBUFF
709// triggered.
710class NetlinkListenerTest : public testing::Test {
711 protected:
712 NetlinkListenerTest() {}
713 BpfMap<uint64_t, UidTagValue> mCookieTagMap;
714
715 void SetUp() {
Maciej Żenczykowskiced35312022-05-31 05:11:12 -0700716 mCookieTagMap.init(COOKIE_TAG_MAP_PATH);
Patrick Rohr61e94672022-02-01 21:06:40 +0100717 ASSERT_TRUE(mCookieTagMap.isValid());
718 }
719
720 void TearDown() {
721 const auto deleteTestCookieEntries = [](const uint64_t& key, const UidTagValue& value,
722 BpfMap<uint64_t, UidTagValue>& map) {
723 if ((value.uid == TEST_UID) && (value.tag == TEST_TAG)) {
724 Result<void> res = map.deleteValue(key);
725 if (res.ok() || (res.error().code() == ENOENT)) {
726 return Result<void>();
727 }
Maciej Żenczykowskie0f58462022-05-17 13:59:22 -0700728 ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s", key,
Patrick Rohr61e94672022-02-01 21:06:40 +0100729 strerror(res.error().code()));
730 }
731 // Move forward to next cookie in the map.
732 return Result<void>();
733 };
734 EXPECT_RESULT_OK(mCookieTagMap.iterateWithValue(deleteTestCookieEntries));
735 }
736
737 Result<void> checkNoGarbageTagsExist() {
738 const auto checkGarbageTags = [](const uint64_t&, const UidTagValue& value,
739 const BpfMap<uint64_t, UidTagValue>&) -> Result<void> {
740 if ((TEST_UID == value.uid) && (TEST_TAG == value.tag)) {
741 return Error(EUCLEAN) << "Closed socket is not untagged";
742 }
743 return {};
744 };
745 return mCookieTagMap.iterateWithValue(checkGarbageTags);
746 }
747
748 bool checkMassiveSocketDestroy(int totalNumber, bool expectError) {
749 std::unique_ptr<android::netdutils::NetlinkListenerInterface> skDestroyListener;
750 auto result = android::net::TrafficController::makeSkDestroyListener();
751 if (!isOk(result)) {
752 ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
753 } else {
754 skDestroyListener = std::move(result.value());
755 }
756 int rxErrorCount = 0;
757 // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
758 const auto rxErrorHandler = [&rxErrorCount](const int, const int) { rxErrorCount++; };
759 skDestroyListener->registerSkErrorHandler(rxErrorHandler);
760 int fds[totalNumber];
761 for (int i = 0; i < totalNumber; i++) {
762 fds[i] = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
763 // The likely reason for a failure is running out of available file descriptors.
764 EXPECT_LE(0, fds[i]) << i << " of " << totalNumber;
765 if (fds[i] < 0) {
766 // EXPECT_LE already failed above, so test case is a failure, but we don't
767 // want potentially tens of thousands of extra failures creating and then
768 // closing all these fds cluttering up the logs.
769 totalNumber = i;
770 break;
771 };
772 libnetd_updatable_tagSocket(fds[i], TEST_TAG, TEST_UID, 1000);
773 }
774
775 // TODO: Use a separate thread that has its own fd table so we can
776 // close sockets even faster simply by terminating that thread.
777 for (int i = 0; i < totalNumber; i++) {
778 EXPECT_EQ(0, close(fds[i]));
779 }
780 // wait a bit for netlink listener to handle all the messages.
781 usleep(SOCK_CLOSE_WAIT_US);
782 if (expectError) {
783 // If ENOBUFS triggered, check it only called into the handler once, ie.
784 // that the netlink handler is not spinning.
785 int currentErrorCount = rxErrorCount;
786 // 0 error count is acceptable because the system has chances to close all sockets
787 // normally.
788 EXPECT_LE(0, rxErrorCount);
789 if (!rxErrorCount) return true;
790
791 usleep(ENOBUFS_POLL_WAIT_US);
792 EXPECT_EQ(currentErrorCount, rxErrorCount);
793 } else {
794 EXPECT_RESULT_OK(checkNoGarbageTagsExist());
795 EXPECT_EQ(0, rxErrorCount);
796 }
797 return false;
798 }
799};
800
801TEST_F(NetlinkListenerTest, TestAllSocketUntagged) {
802 checkMassiveSocketDestroy(10, false);
803 checkMassiveSocketDestroy(100, false);
804}
805
806// Disabled because flaky on blueline-userdebug; this test relies on the main thread
807// winning a race against the NetlinkListener::run() thread. There's no way to ensure
808// things will be scheduled the same way across all architectures and test environments.
809TEST_F(NetlinkListenerTest, DISABLED_TestSkDestroyError) {
810 bool needRetry = false;
811 int retryCount = 0;
812 do {
813 needRetry = checkMassiveSocketDestroy(32500, true);
814 if (needRetry) retryCount++;
815 } while (needRetry && retryCount < 3);
816 // Should review test if it can always close all sockets correctly.
817 EXPECT_GT(3, retryCount);
818}
819
820
Wayne Ma4d692332022-01-19 16:04:04 +0800821} // namespace net
822} // namespace android