• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2022 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  * 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 
33 #include <android-base/file.h>
34 #include <android-base/logging.h>
35 #include <android-base/stringprintf.h>
36 #include <android-base/strings.h>
37 #include <binder/Status.h>
38 
39 #include <netdutils/MockSyscalls.h>
40 
41 #define BPF_MAP_MAKE_VISIBLE_FOR_TESTING
42 #include "TrafficController.h"
43 #include "bpf/BpfUtils.h"
44 #include "NetdUpdatablePublic.h"
45 
46 using namespace android::bpf;  // NOLINT(google-build-using-namespace): grandfathered
47 
48 namespace android {
49 namespace net {
50 
51 using android::netdutils::Status;
52 using base::Result;
53 using netdutils::isOk;
54 using netdutils::statusFromErrno;
55 
56 constexpr int TEST_MAP_SIZE = 10;
57 constexpr uid_t TEST_UID = 10086;
58 constexpr uid_t TEST_UID2 = 54321;
59 constexpr uid_t TEST_UID3 = 98765;
60 constexpr uint32_t TEST_TAG = 42;
61 constexpr uint32_t TEST_COUNTERSET = 1;
62 constexpr int TEST_IFINDEX = 999;
63 constexpr int RXPACKETS = 1;
64 constexpr int RXBYTES = 100;
65 constexpr int TXPACKETS = 0;
66 constexpr int TXBYTES = 0;
67 
68 #define ASSERT_VALID(x) ASSERT_TRUE((x).isValid())
69 #define ASSERT_INVALID(x) ASSERT_FALSE((x).isValid())
70 
71 class TrafficControllerTest : public ::testing::Test {
72   protected:
TrafficControllerTest()73     TrafficControllerTest() {}
74     TrafficController mTc;
75     BpfMap<uint64_t, UidTagValue> mFakeCookieTagMap;
76     BpfMap<uint32_t, StatsValue> mFakeAppUidStatsMap;
77     BpfMap<StatsKey, StatsValue> mFakeStatsMapA;
78     BpfMap<StatsKey, StatsValue> mFakeStatsMapB;  // makeTrafficControllerMapsInvalid only
79     BpfMap<uint32_t, StatsValue> mFakeIfaceStatsMap; ;  // makeTrafficControllerMapsInvalid only
80     BpfMap<uint32_t, uint32_t> mFakeConfigurationMap;
81     BpfMap<uint32_t, UidOwnerValue> mFakeUidOwnerMap;
82     BpfMap<uint32_t, uint8_t> mFakeUidPermissionMap;
83     BpfMap<uint32_t, uint8_t> mFakeUidCounterSetMap;
84     BpfMap<uint32_t, IfaceValue> mFakeIfaceIndexNameMap;
85 
SetUp()86     void SetUp() {
87         std::lock_guard guard(mTc.mMutex);
88         ASSERT_EQ(0, setrlimitForTest());
89 
90         mFakeCookieTagMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
91         ASSERT_VALID(mFakeCookieTagMap);
92 
93         mFakeAppUidStatsMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
94         ASSERT_VALID(mFakeAppUidStatsMap);
95 
96         mFakeStatsMapA.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
97         ASSERT_VALID(mFakeStatsMapA);
98 
99         mFakeConfigurationMap.resetMap(BPF_MAP_TYPE_ARRAY, CONFIGURATION_MAP_SIZE);
100         ASSERT_VALID(mFakeConfigurationMap);
101 
102         mFakeUidOwnerMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
103         ASSERT_VALID(mFakeUidOwnerMap);
104         mFakeUidPermissionMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
105         ASSERT_VALID(mFakeUidPermissionMap);
106 
107         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 
113         mTc.mCookieTagMap = mFakeCookieTagMap;
114         ASSERT_VALID(mTc.mCookieTagMap);
115         mTc.mAppUidStatsMap = mFakeAppUidStatsMap;
116         ASSERT_VALID(mTc.mAppUidStatsMap);
117         mTc.mStatsMapA = mFakeStatsMapA;
118         ASSERT_VALID(mTc.mStatsMapA);
119         mTc.mConfigurationMap = mFakeConfigurationMap;
120         ASSERT_VALID(mTc.mConfigurationMap);
121 
122         // Always write to stats map A by default.
123         static_assert(SELECT_MAP_A == 0);
124 
125         mTc.mUidOwnerMap = mFakeUidOwnerMap;
126         ASSERT_VALID(mTc.mUidOwnerMap);
127         mTc.mUidPermissionMap = mFakeUidPermissionMap;
128         ASSERT_VALID(mTc.mUidPermissionMap);
129         mTc.mPrivilegedUser.clear();
130 
131         mTc.mUidCounterSetMap = mFakeUidCounterSetMap;
132         ASSERT_VALID(mTc.mUidCounterSetMap);
133 
134         mTc.mIfaceIndexNameMap = mFakeIfaceIndexNameMap;
135         ASSERT_VALID(mTc.mIfaceIndexNameMap);
136     }
137 
populateFakeStats(uint64_t cookie,uint32_t uid,uint32_t tag,StatsKey * key)138     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));
141         *key = {.uid = uid, .tag = tag, .counterSet = TEST_COUNTERSET, .ifaceIndex = TEST_IFINDEX};
142         StatsValue statsMapValue = {.rxPackets = RXPACKETS, .rxBytes = RXBYTES,
143                                     .txPackets = TXPACKETS, .txBytes = TXBYTES};
144         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 
populateFakeCounterSet(uint32_t uid,uint32_t counterSet)150     void populateFakeCounterSet(uint32_t uid, uint32_t counterSet) {
151         EXPECT_RESULT_OK(mFakeUidCounterSetMap.writeValue(uid, counterSet, BPF_ANY));
152     }
153 
populateFakeIfaceIndexName(const char * name,uint32_t ifaceIndex)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 
checkUidOwnerRuleForChain(ChildChain chain,UidOwnerMatchType match)162     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 
checkEachUidValue(const std::vector<int32_t> & uids,UidOwnerMatchType match)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 
checkUidMapReplace(const std::string & name,const std::vector<int32_t> & uids,UidOwnerMatchType match)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 
expectUidOwnerMapValues(const std::vector<uint32_t> & appUids,uint32_t expectedRule,uint32_t expectedIif)219     void expectUidOwnerMapValues(const std::vector<uint32_t>& appUids, uint32_t expectedRule,
220                                  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>
expectMapEmpty(BpfMap<Key,Value> & map)234     void expectMapEmpty(BpfMap<Key, Value>& map) {
235         auto isEmpty = map.isEmpty();
236         EXPECT_RESULT_OK(isEmpty);
237         EXPECT_TRUE(isEmpty.value());
238     }
239 
expectUidPermissionMapValues(const std::vector<uid_t> & appUids,uint8_t expectedValue)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 
expectPrivilegedUserSet(const std::vector<uid_t> & appUids)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 
expectPrivilegedUserSetEmpty()258     void expectPrivilegedUserSetEmpty() {
259         std::lock_guard guard(mTc.mMutex);
260         EXPECT_TRUE(mTc.mPrivilegedUser.empty());
261     }
262 
updateUidOwnerMaps(const std::vector<uint32_t> & appUids,UidOwnerMatchType matchType,TrafficController::IptOp op)263     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     }
272 
dump(bool verbose,std::vector<std::string> & outputLines)273     Status dump(bool verbose, std::vector<std::string>& outputLines) {
274       if (!outputLines.empty()) return statusFromErrno(EUCLEAN, "Output buffer is not empty");
275 
276       android::base::unique_fd localFd, remoteFd;
277       if (!Pipe(&localFd, &remoteFd)) return statusFromErrno(errno, "Failed on pipe");
278 
279       // dump() blocks until another thread has consumed all its output.
280       std::thread dumpThread =
281           std::thread([this, remoteFd{std::move(remoteFd)}, verbose]() {
282             mTc.dump(remoteFd, verbose);
283           });
284 
285       std::string dumpContent;
286       if (!android::base::ReadFdToString(localFd.get(), &dumpContent)) {
287         return statusFromErrno(errno, "Failed to read dump results from fd");
288       }
289       dumpThread.join();
290 
291       std::stringstream dumpStream(std::move(dumpContent));
292       std::string line;
293       while (std::getline(dumpStream, line)) {
294         outputLines.push_back(line);
295       }
296 
297       return netdutils::status::ok;
298     }
299 
300     // Strings in the |expect| must exist in dump results in order. But no need to be consecutive.
expectDumpsysContains(std::vector<std::string> & expect)301     bool expectDumpsysContains(std::vector<std::string>& expect) {
302         if (expect.empty()) return false;
303 
304         std::vector<std::string> output;
305         Status result = dump(true, output);
306         if (!isOk(result)) {
307             GTEST_LOG_(ERROR) << "TrafficController dump failed: " << netdutils::toString(result);
308             return false;
309         }
310 
311         int matched = 0;
312         auto it = expect.begin();
313         for (const auto& line : output) {
314             if (it == expect.end()) break;
315             if (std::string::npos != line.find(*it)) {
316                 matched++;
317                 ++it;
318             }
319         }
320 
321         if (matched != expect.size()) {
322             // dump results for debugging
323             for (const auto& o : output) LOG(INFO) << "output: " << o;
324             for (const auto& e : expect) LOG(INFO) << "expect: " << e;
325             return false;
326         }
327         return true;
328     }
329 
330     // Once called, the maps of TrafficController can't recover to valid maps which initialized
331     // in SetUp().
makeTrafficControllerMapsInvalid()332     void makeTrafficControllerMapsInvalid() {
333         constexpr char INVALID_PATH[] = "invalid";
334 
335         mFakeCookieTagMap.init(INVALID_PATH);
336         mTc.mCookieTagMap = mFakeCookieTagMap;
337         ASSERT_INVALID(mTc.mCookieTagMap);
338 
339         mFakeAppUidStatsMap.init(INVALID_PATH);
340         mTc.mAppUidStatsMap = mFakeAppUidStatsMap;
341         ASSERT_INVALID(mTc.mAppUidStatsMap);
342 
343         mFakeStatsMapA.init(INVALID_PATH);
344         mTc.mStatsMapA = mFakeStatsMapA;
345         ASSERT_INVALID(mTc.mStatsMapA);
346 
347         mFakeStatsMapB.init(INVALID_PATH);
348         mTc.mStatsMapB = mFakeStatsMapB;
349         ASSERT_INVALID(mTc.mStatsMapB);
350 
351         mFakeIfaceStatsMap.init(INVALID_PATH);
352         mTc.mIfaceStatsMap = mFakeIfaceStatsMap;
353         ASSERT_INVALID(mTc.mIfaceStatsMap);
354 
355         mFakeConfigurationMap.init(INVALID_PATH);
356         mTc.mConfigurationMap = mFakeConfigurationMap;
357         ASSERT_INVALID(mTc.mConfigurationMap);
358 
359         mFakeUidOwnerMap.init(INVALID_PATH);
360         mTc.mUidOwnerMap = mFakeUidOwnerMap;
361         ASSERT_INVALID(mTc.mUidOwnerMap);
362 
363         mFakeUidPermissionMap.init(INVALID_PATH);
364         mTc.mUidPermissionMap = mFakeUidPermissionMap;
365         ASSERT_INVALID(mTc.mUidPermissionMap);
366 
367         mFakeUidCounterSetMap.init(INVALID_PATH);
368         mTc.mUidCounterSetMap = mFakeUidCounterSetMap;
369         ASSERT_INVALID(mTc.mUidCounterSetMap);
370 
371         mFakeIfaceIndexNameMap.init(INVALID_PATH);
372         mTc.mIfaceIndexNameMap = mFakeIfaceIndexNameMap;
373         ASSERT_INVALID(mTc.mIfaceIndexNameMap);
374     }
375 };
376 
TEST_F(TrafficControllerTest,TestUpdateOwnerMapEntry)377 TEST_F(TrafficControllerTest, TestUpdateOwnerMapEntry) {
378     uint32_t uid = TEST_UID;
379     ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, DENY, DENYLIST)));
380     Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
381     ASSERT_RESULT_OK(value);
382     ASSERT_TRUE(value.value().rule & STANDBY_MATCH);
383 
384     ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(DOZABLE_MATCH, uid, ALLOW, ALLOWLIST)));
385     value = mFakeUidOwnerMap.readValue(uid);
386     ASSERT_RESULT_OK(value);
387     ASSERT_TRUE(value.value().rule & DOZABLE_MATCH);
388 
389     ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(DOZABLE_MATCH, uid, DENY, ALLOWLIST)));
390     value = mFakeUidOwnerMap.readValue(uid);
391     ASSERT_RESULT_OK(value);
392     ASSERT_FALSE(value.value().rule & DOZABLE_MATCH);
393 
394     ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, ALLOW, DENYLIST)));
395     ASSERT_FALSE(mFakeUidOwnerMap.readValue(uid).ok());
396 
397     uid = TEST_UID2;
398     ASSERT_FALSE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, ALLOW, DENYLIST)));
399     ASSERT_FALSE(mFakeUidOwnerMap.readValue(uid).ok());
400 }
401 
TEST_F(TrafficControllerTest,TestChangeUidOwnerRule)402 TEST_F(TrafficControllerTest, TestChangeUidOwnerRule) {
403     checkUidOwnerRuleForChain(DOZABLE, DOZABLE_MATCH);
404     checkUidOwnerRuleForChain(STANDBY, STANDBY_MATCH);
405     checkUidOwnerRuleForChain(POWERSAVE, POWERSAVE_MATCH);
406     checkUidOwnerRuleForChain(RESTRICTED, RESTRICTED_MATCH);
407     checkUidOwnerRuleForChain(LOW_POWER_STANDBY, LOW_POWER_STANDBY_MATCH);
408     checkUidOwnerRuleForChain(OEM_DENY_1, OEM_DENY_1_MATCH);
409     checkUidOwnerRuleForChain(OEM_DENY_2, OEM_DENY_2_MATCH);
410     checkUidOwnerRuleForChain(OEM_DENY_3, OEM_DENY_3_MATCH);
411     ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(NONE, TEST_UID, ALLOW, ALLOWLIST));
412     ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(INVALID_CHAIN, TEST_UID, ALLOW, ALLOWLIST));
413 }
414 
TEST_F(TrafficControllerTest,TestReplaceUidOwnerMap)415 TEST_F(TrafficControllerTest, TestReplaceUidOwnerMap) {
416     std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
417     checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
418     checkUidMapReplace("fw_standby", uids, STANDBY_MATCH);
419     checkUidMapReplace("fw_powersave", uids, POWERSAVE_MATCH);
420     checkUidMapReplace("fw_restricted", uids, RESTRICTED_MATCH);
421     checkUidMapReplace("fw_low_power_standby", uids, LOW_POWER_STANDBY_MATCH);
422     checkUidMapReplace("fw_oem_deny_1", uids, OEM_DENY_1_MATCH);
423     checkUidMapReplace("fw_oem_deny_2", uids, OEM_DENY_2_MATCH);
424     checkUidMapReplace("fw_oem_deny_3", uids, OEM_DENY_3_MATCH);
425     ASSERT_EQ(-EINVAL, mTc.replaceUidOwnerMap("unknow", true, uids));
426 }
427 
TEST_F(TrafficControllerTest,TestReplaceSameChain)428 TEST_F(TrafficControllerTest, TestReplaceSameChain) {
429     std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
430     checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
431     std::vector<int32_t> newUids = {TEST_UID2, TEST_UID3};
432     checkUidMapReplace("fw_dozable", newUids, DOZABLE_MATCH);
433 }
434 
TEST_F(TrafficControllerTest,TestDenylistUidMatch)435 TEST_F(TrafficControllerTest, TestDenylistUidMatch) {
436     std::vector<uint32_t> appUids = {1000, 1001, 10012};
437     ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
438                                         TrafficController::IptOpInsert)));
439     expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
440     ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
441                                         TrafficController::IptOpDelete)));
442     expectMapEmpty(mFakeUidOwnerMap);
443 }
444 
TEST_F(TrafficControllerTest,TestAllowlistUidMatch)445 TEST_F(TrafficControllerTest, TestAllowlistUidMatch) {
446     std::vector<uint32_t> appUids = {1000, 1001, 10012};
447     ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
448     expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
449     ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
450     expectMapEmpty(mFakeUidOwnerMap);
451 }
452 
TEST_F(TrafficControllerTest,TestReplaceMatchUid)453 TEST_F(TrafficControllerTest, TestReplaceMatchUid) {
454     std::vector<uint32_t> appUids = {1000, 1001, 10012};
455     // Add appUids to the denylist and expect that their values are all PENALTY_BOX_MATCH.
456     ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
457                                         TrafficController::IptOpInsert)));
458     expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
459 
460     // Add the same UIDs to the allowlist and expect that we get PENALTY_BOX_MATCH |
461     // HAPPY_BOX_MATCH.
462     ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
463     expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH | PENALTY_BOX_MATCH, 0);
464 
465     // Remove the same UIDs from the allowlist and check the PENALTY_BOX_MATCH is still there.
466     ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
467     expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
468 
469     // Remove the same UIDs from the denylist and check the map is empty.
470     ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
471                                         TrafficController::IptOpDelete)));
472     ASSERT_FALSE(mFakeUidOwnerMap.getFirstKey().ok());
473 }
474 
TEST_F(TrafficControllerTest,TestDeleteWrongMatchSilentlyFails)475 TEST_F(TrafficControllerTest, TestDeleteWrongMatchSilentlyFails) {
476     std::vector<uint32_t> appUids = {1000, 1001, 10012};
477     // If the uid does not exist in the map, trying to delete a rule about it will fail.
478     ASSERT_FALSE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
479                                          TrafficController::IptOpDelete)));
480     expectMapEmpty(mFakeUidOwnerMap);
481 
482     // Add denylist rules for appUids.
483     ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
484                                         TrafficController::IptOpInsert)));
485     expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
486 
487     // Delete (non-existent) denylist rules for appUids, and check that this silently does
488     // nothing if the uid is in the map but does not have denylist match. This is required because
489     // NetworkManagementService will try to remove a uid from denylist after adding it to the
490     // allowlist and if the remove fails it will not update the uid status.
491     ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
492                                         TrafficController::IptOpDelete)));
493     expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
494 }
495 
TEST_F(TrafficControllerTest,TestAddUidInterfaceFilteringRules)496 TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRules) {
497     int iif0 = 15;
498     ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
499     expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
500 
501     // Add some non-overlapping new uids. They should coexist with existing rules
502     int iif1 = 16;
503     ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
504     expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
505     expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
506 
507     // Overwrite some existing uids
508     int iif2 = 17;
509     ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif2, {1000, 2000})));
510     expectUidOwnerMapValues({1001}, IIF_MATCH, iif0);
511     expectUidOwnerMapValues({2001}, IIF_MATCH, iif1);
512     expectUidOwnerMapValues({1000, 2000}, IIF_MATCH, iif2);
513 }
514 
TEST_F(TrafficControllerTest,TestRemoveUidInterfaceFilteringRules)515 TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRules) {
516     int iif0 = 15;
517     int iif1 = 16;
518     ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
519     ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
520     expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
521     expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
522 
523     // Rmove some uids
524     ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001, 2001})));
525     expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
526     expectUidOwnerMapValues({2000}, IIF_MATCH, iif1);
527     checkEachUidValue({1000, 2000}, IIF_MATCH);  // Make sure there are only two uids remaining
528 
529     // Remove non-existent uids shouldn't fail
530     ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({2000, 3000})));
531     expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
532     checkEachUidValue({1000}, IIF_MATCH);  // Make sure there are only one uid remaining
533 
534     // Remove everything
535     ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
536     expectMapEmpty(mFakeUidOwnerMap);
537 }
538 
TEST_F(TrafficControllerTest,TestUpdateUidLockdownRule)539 TEST_F(TrafficControllerTest, TestUpdateUidLockdownRule) {
540     // Add Lockdown rules
541     ASSERT_TRUE(isOk(mTc.updateUidLockdownRule(1000, true /* add */)));
542     ASSERT_TRUE(isOk(mTc.updateUidLockdownRule(1001, true /* add */)));
543     expectUidOwnerMapValues({1000, 1001}, LOCKDOWN_VPN_MATCH, 0);
544 
545     // Remove one of Lockdown rules
546     ASSERT_TRUE(isOk(mTc.updateUidLockdownRule(1000, false /* add */)));
547     expectUidOwnerMapValues({1001}, LOCKDOWN_VPN_MATCH, 0);
548 
549     // Remove remaining Lockdown rule
550     ASSERT_TRUE(isOk(mTc.updateUidLockdownRule(1001, false /* add */)));
551     expectMapEmpty(mFakeUidOwnerMap);
552 }
553 
TEST_F(TrafficControllerTest,TestUidInterfaceFilteringRulesCoexistWithExistingMatches)554 TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithExistingMatches) {
555     // Set up existing PENALTY_BOX_MATCH rules
556     ASSERT_TRUE(isOk(updateUidOwnerMaps({1000, 1001, 10012}, PENALTY_BOX_MATCH,
557                                         TrafficController::IptOpInsert)));
558     expectUidOwnerMapValues({1000, 1001, 10012}, PENALTY_BOX_MATCH, 0);
559 
560     // Add some partially-overlapping uid owner rules and check result
561     int iif1 = 32;
562     ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10012, 10013, 10014})));
563     expectUidOwnerMapValues({1000, 1001}, PENALTY_BOX_MATCH, 0);
564     expectUidOwnerMapValues({10012}, PENALTY_BOX_MATCH | IIF_MATCH, iif1);
565     expectUidOwnerMapValues({10013, 10014}, IIF_MATCH, iif1);
566 
567     // Removing some PENALTY_BOX_MATCH rules should not change uid interface rule
568     ASSERT_TRUE(isOk(updateUidOwnerMaps({1001, 10012}, PENALTY_BOX_MATCH,
569                                         TrafficController::IptOpDelete)));
570     expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
571     expectUidOwnerMapValues({10012, 10013, 10014}, IIF_MATCH, iif1);
572 
573     // Remove all uid interface rules
574     ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({10012, 10013, 10014})));
575     expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
576     // Make sure these are the only uids left
577     checkEachUidValue({1000}, PENALTY_BOX_MATCH);
578 }
579 
TEST_F(TrafficControllerTest,TestUidInterfaceFilteringRulesCoexistWithNewMatches)580 TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithNewMatches) {
581     int iif1 = 56;
582     // Set up existing uid interface rules
583     ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10001, 10002})));
584     expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
585 
586     // Add some partially-overlapping doze rules
587     EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {10002, 10003}));
588     expectUidOwnerMapValues({10001}, IIF_MATCH, iif1);
589     expectUidOwnerMapValues({10002}, DOZABLE_MATCH | IIF_MATCH, iif1);
590     expectUidOwnerMapValues({10003}, DOZABLE_MATCH, 0);
591 
592     // Introduce a third rule type (powersave) on various existing UIDs
593     EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {10000, 10001, 10002, 10003}));
594     expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
595     expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
596     expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif1);
597     expectUidOwnerMapValues({10003}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
598 
599     // Remove all doze rules
600     EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {}));
601     expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
602     expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
603     expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | IIF_MATCH, iif1);
604     expectUidOwnerMapValues({10003}, POWERSAVE_MATCH, 0);
605 
606     // Remove all powersave rules, expect ownerMap to only have uid interface rules left
607     EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {}));
608     expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
609     // Make sure these are the only uids left
610     checkEachUidValue({10001, 10002}, IIF_MATCH);
611 }
612 
TEST_F(TrafficControllerTest,TestAddUidInterfaceFilteringRulesWithWildcard)613 TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRulesWithWildcard) {
614     // iif=0 is a wildcard
615     int iif = 0;
616     // Add interface rule with wildcard to uids
617     ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000, 1001})));
618     expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif);
619 }
620 
TEST_F(TrafficControllerTest,TestRemoveUidInterfaceFilteringRulesWithWildcard)621 TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRulesWithWildcard) {
622     // iif=0 is a wildcard
623     int iif = 0;
624     // Add interface rule with wildcard to two uids
625     ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000, 1001})));
626     expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif);
627 
628     // Remove interface rule from one of the uids
629     ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
630     expectUidOwnerMapValues({1001}, IIF_MATCH, iif);
631     checkEachUidValue({1001}, IIF_MATCH);
632 
633     // Remove interface rule from the remaining uid
634     ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001})));
635     expectMapEmpty(mFakeUidOwnerMap);
636 }
637 
TEST_F(TrafficControllerTest,TestUidInterfaceFilteringRulesWithWildcardAndExistingMatches)638 TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesWithWildcardAndExistingMatches) {
639     // Set up existing DOZABLE_MATCH and POWERSAVE_MATCH rule
640     ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
641                                         TrafficController::IptOpInsert)));
642     ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
643                                         TrafficController::IptOpInsert)));
644 
645     // iif=0 is a wildcard
646     int iif = 0;
647     // Add interface rule with wildcard to the existing uid
648     ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000})));
649     expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif);
650 
651     // Remove interface rule with wildcard from the existing uid
652     ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
653     expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
654 }
655 
TEST_F(TrafficControllerTest,TestUidInterfaceFilteringRulesWithWildcardAndNewMatches)656 TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesWithWildcardAndNewMatches) {
657     // iif=0 is a wildcard
658     int iif = 0;
659     // Set up existing interface rule with wildcard
660     ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000})));
661 
662     // Add DOZABLE_MATCH and POWERSAVE_MATCH rule to the existing uid
663     ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
664                                         TrafficController::IptOpInsert)));
665     ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
666                                         TrafficController::IptOpInsert)));
667     expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif);
668 
669     // Remove DOZABLE_MATCH and POWERSAVE_MATCH rule from the existing uid
670     ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
671                                         TrafficController::IptOpDelete)));
672     ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
673                                         TrafficController::IptOpDelete)));
674     expectUidOwnerMapValues({1000}, IIF_MATCH, iif);
675 }
676 
TEST_F(TrafficControllerTest,TestGrantInternetPermission)677 TEST_F(TrafficControllerTest, TestGrantInternetPermission) {
678     std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
679 
680     mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
681     expectMapEmpty(mFakeUidPermissionMap);
682     expectPrivilegedUserSetEmpty();
683 }
684 
TEST_F(TrafficControllerTest,TestRevokeInternetPermission)685 TEST_F(TrafficControllerTest, TestRevokeInternetPermission) {
686     std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
687 
688     mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
689     expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
690 }
691 
TEST_F(TrafficControllerTest,TestPermissionUninstalled)692 TEST_F(TrafficControllerTest, TestPermissionUninstalled) {
693     std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
694 
695     mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
696     expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
697     expectPrivilegedUserSet(appUids);
698 
699     std::vector<uid_t> uidToRemove = {TEST_UID};
700     mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidToRemove);
701 
702     std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
703     expectUidPermissionMapValues(uidRemain, INetd::PERMISSION_UPDATE_DEVICE_STATS);
704     expectPrivilegedUserSet(uidRemain);
705 
706     mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidRemain);
707     expectMapEmpty(mFakeUidPermissionMap);
708     expectPrivilegedUserSetEmpty();
709 }
710 
TEST_F(TrafficControllerTest,TestGrantUpdateStatsPermission)711 TEST_F(TrafficControllerTest, TestGrantUpdateStatsPermission) {
712     std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
713 
714     mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
715     expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
716     expectPrivilegedUserSet(appUids);
717 
718     mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
719     expectPrivilegedUserSetEmpty();
720     expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
721 }
722 
TEST_F(TrafficControllerTest,TestRevokeUpdateStatsPermission)723 TEST_F(TrafficControllerTest, TestRevokeUpdateStatsPermission) {
724     std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
725 
726     mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
727     expectPrivilegedUserSet(appUids);
728 
729     std::vector<uid_t> uidToRemove = {TEST_UID};
730     mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidToRemove);
731 
732     std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
733     expectPrivilegedUserSet(uidRemain);
734 
735     mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidRemain);
736     expectPrivilegedUserSetEmpty();
737 }
738 
TEST_F(TrafficControllerTest,TestGrantWrongPermission)739 TEST_F(TrafficControllerTest, TestGrantWrongPermission) {
740     std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
741 
742     mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
743     expectPrivilegedUserSetEmpty();
744     expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
745 }
746 
TEST_F(TrafficControllerTest,TestGrantDuplicatePermissionSlientlyFail)747 TEST_F(TrafficControllerTest, TestGrantDuplicatePermissionSlientlyFail) {
748     std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
749 
750     mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
751     expectMapEmpty(mFakeUidPermissionMap);
752 
753     std::vector<uid_t> uidToAdd = {TEST_UID};
754     mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, uidToAdd);
755 
756     expectPrivilegedUserSetEmpty();
757 
758     mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
759     expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
760 
761     mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
762     expectPrivilegedUserSet(appUids);
763 
764     mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, uidToAdd);
765     expectPrivilegedUserSet(appUids);
766 
767     mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
768     expectPrivilegedUserSetEmpty();
769 }
770 
TEST_F(TrafficControllerTest,getFirewallType)771 TEST_F(TrafficControllerTest, getFirewallType) {
772     static const struct TestConfig {
773         ChildChain childChain;
774         FirewallType firewallType;
775     } testConfigs[] = {
776             // clang-format off
777             {NONE, DENYLIST},
778             {DOZABLE, ALLOWLIST},
779             {STANDBY, DENYLIST},
780             {POWERSAVE, ALLOWLIST},
781             {RESTRICTED, ALLOWLIST},
782             {LOW_POWER_STANDBY, ALLOWLIST},
783             {OEM_DENY_1, DENYLIST},
784             {OEM_DENY_2, DENYLIST},
785             {OEM_DENY_3, DENYLIST},
786             {INVALID_CHAIN, DENYLIST},
787             // clang-format on
788     };
789 
790     for (const auto& config : testConfigs) {
791         SCOPED_TRACE(fmt::format("testConfig: [{}, {}]", config.childChain, config.firewallType));
792         EXPECT_EQ(config.firewallType, mTc.getFirewallType(config.childChain));
793     }
794 }
795 
796 constexpr uint32_t SOCK_CLOSE_WAIT_US = 30 * 1000;
797 constexpr uint32_t ENOBUFS_POLL_WAIT_US = 10 * 1000;
798 
799 using android::base::Error;
800 using android::base::Result;
801 using android::bpf::BpfMap;
802 
803 // This test set up a SkDestroyListener that is running parallel with the production
804 // SkDestroyListener. The test will create thousands of sockets and tag them on the
805 // production cookieUidTagMap and close them in a short time. When the number of
806 // sockets get closed exceeds the buffer size, it will start to return ENOBUFF
807 // error. The error will be ignored by the production SkDestroyListener and the
808 // test will clean up the tags in tearDown if there is any remains.
809 
810 // TODO: Instead of test the ENOBUFF error, we can test the production
811 // SkDestroyListener to see if it failed to delete a tagged socket when ENOBUFF
812 // triggered.
813 class NetlinkListenerTest : public testing::Test {
814   protected:
NetlinkListenerTest()815     NetlinkListenerTest() {}
816     BpfMap<uint64_t, UidTagValue> mCookieTagMap;
817 
SetUp()818     void SetUp() {
819         mCookieTagMap.init(COOKIE_TAG_MAP_PATH);
820         ASSERT_TRUE(mCookieTagMap.isValid());
821     }
822 
TearDown()823     void TearDown() {
824         const auto deleteTestCookieEntries = [](const uint64_t& key, const UidTagValue& value,
825                                                 BpfMap<uint64_t, UidTagValue>& map) {
826             if ((value.uid == TEST_UID) && (value.tag == TEST_TAG)) {
827                 Result<void> res = map.deleteValue(key);
828                 if (res.ok() || (res.error().code() == ENOENT)) {
829                     return Result<void>();
830                 }
831                 ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s", key,
832                       strerror(res.error().code()));
833             }
834             // Move forward to next cookie in the map.
835             return Result<void>();
836         };
837         EXPECT_RESULT_OK(mCookieTagMap.iterateWithValue(deleteTestCookieEntries));
838     }
839 
checkNoGarbageTagsExist()840     Result<void> checkNoGarbageTagsExist() {
841         const auto checkGarbageTags = [](const uint64_t&, const UidTagValue& value,
842                                          const BpfMap<uint64_t, UidTagValue>&) -> Result<void> {
843             if ((TEST_UID == value.uid) && (TEST_TAG == value.tag)) {
844                 return Error(EUCLEAN) << "Closed socket is not untagged";
845             }
846             return {};
847         };
848         return mCookieTagMap.iterateWithValue(checkGarbageTags);
849     }
850 
checkMassiveSocketDestroy(int totalNumber,bool expectError)851     bool checkMassiveSocketDestroy(int totalNumber, bool expectError) {
852         std::unique_ptr<android::netdutils::NetlinkListenerInterface> skDestroyListener;
853         auto result = android::net::TrafficController::makeSkDestroyListener();
854         if (!isOk(result)) {
855             ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
856         } else {
857             skDestroyListener = std::move(result.value());
858         }
859         int rxErrorCount = 0;
860         // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
861         const auto rxErrorHandler = [&rxErrorCount](const int, const int) { rxErrorCount++; };
862         skDestroyListener->registerSkErrorHandler(rxErrorHandler);
863         int fds[totalNumber];
864         for (int i = 0; i < totalNumber; i++) {
865             fds[i] = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
866             // The likely reason for a failure is running out of available file descriptors.
867             EXPECT_LE(0, fds[i]) << i << " of " << totalNumber;
868             if (fds[i] < 0) {
869                 // EXPECT_LE already failed above, so test case is a failure, but we don't
870                 // want potentially tens of thousands of extra failures creating and then
871                 // closing all these fds cluttering up the logs.
872                 totalNumber = i;
873                 break;
874             };
875             libnetd_updatable_tagSocket(fds[i], TEST_TAG, TEST_UID, 1000);
876         }
877 
878         // TODO: Use a separate thread that has its own fd table so we can
879         // close sockets even faster simply by terminating that thread.
880         for (int i = 0; i < totalNumber; i++) {
881             EXPECT_EQ(0, close(fds[i]));
882         }
883         // wait a bit for netlink listener to handle all the messages.
884         usleep(SOCK_CLOSE_WAIT_US);
885         if (expectError) {
886             // If ENOBUFS triggered, check it only called into the handler once, ie.
887             // that the netlink handler is not spinning.
888             int currentErrorCount = rxErrorCount;
889             // 0 error count is acceptable because the system has chances to close all sockets
890             // normally.
891             EXPECT_LE(0, rxErrorCount);
892             if (!rxErrorCount) return true;
893 
894             usleep(ENOBUFS_POLL_WAIT_US);
895             EXPECT_EQ(currentErrorCount, rxErrorCount);
896         } else {
897             EXPECT_RESULT_OK(checkNoGarbageTagsExist());
898             EXPECT_EQ(0, rxErrorCount);
899         }
900         return false;
901     }
902 };
903 
TEST_F(NetlinkListenerTest,TestAllSocketUntagged)904 TEST_F(NetlinkListenerTest, TestAllSocketUntagged) {
905     checkMassiveSocketDestroy(10, false);
906     checkMassiveSocketDestroy(100, false);
907 }
908 
909 // Disabled because flaky on blueline-userdebug; this test relies on the main thread
910 // winning a race against the NetlinkListener::run() thread. There's no way to ensure
911 // things will be scheduled the same way across all architectures and test environments.
TEST_F(NetlinkListenerTest,DISABLED_TestSkDestroyError)912 TEST_F(NetlinkListenerTest, DISABLED_TestSkDestroyError) {
913     bool needRetry = false;
914     int retryCount = 0;
915     do {
916         needRetry = checkMassiveSocketDestroy(32500, true);
917         if (needRetry) retryCount++;
918     } while (needRetry && retryCount < 3);
919     // Should review test if it can always close all sockets correctly.
920     EXPECT_GT(3, retryCount);
921 }
922 
923 
924 }  // namespace net
925 }  // namespace android
926