Home | History | Annotate | Download | only in tests
      1 /*
      2  * Copyright 2016 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  * binder_test.cpp - unit tests for netd binder RPCs.
     17  */
     18 
     19 #include <cerrno>
     20 #include <cinttypes>
     21 #include <cstdint>
     22 #include <cstdio>
     23 #include <cstdlib>
     24 #include <set>
     25 #include <vector>
     26 
     27 #include <fcntl.h>
     28 #include <ifaddrs.h>
     29 #include <netdb.h>
     30 #include <sys/socket.h>
     31 #include <sys/types.h>
     32 #include <netinet/in.h>
     33 #include <linux/if.h>
     34 #include <linux/if_tun.h>
     35 
     36 #include <android-base/macros.h>
     37 #include <android-base/stringprintf.h>
     38 #include <android-base/strings.h>
     39 #include <cutils/multiuser.h>
     40 #include <gtest/gtest.h>
     41 #include <logwrap/logwrap.h>
     42 #include <netutils/ifc.h>
     43 
     44 #include "NetdConstants.h"
     45 #include "android/net/INetd.h"
     46 #include "android/net/UidRange.h"
     47 #include "binder/IServiceManager.h"
     48 
     49 #define TUN_DEV "/dev/tun"
     50 
     51 using namespace android;
     52 using namespace android::base;
     53 using namespace android::binder;
     54 using android::net::INetd;
     55 using android::net::UidRange;
     56 
     57 static const char* IP_RULE_V4 = "-4";
     58 static const char* IP_RULE_V6 = "-6";
     59 
     60 class BinderTest : public ::testing::Test {
     61 
     62 public:
     63     BinderTest() {
     64         sp<IServiceManager> sm = defaultServiceManager();
     65         sp<IBinder> binder = sm->getService(String16("netd"));
     66         if (binder != nullptr) {
     67             mNetd = interface_cast<INetd>(binder);
     68         }
     69     }
     70 
     71     void SetUp() override {
     72         ASSERT_NE(nullptr, mNetd.get());
     73     }
     74 
     75     // Static because setting up the tun interface takes about 40ms.
     76     static void SetUpTestCase() {
     77         sTunFd = createTunInterface();
     78         ASSERT_LE(sTunIfName.size(), static_cast<size_t>(IFNAMSIZ));
     79         ASSERT_NE(-1, sTunFd);
     80     }
     81 
     82     static void TearDownTestCase() {
     83         // Closing the socket removes the interface and IP addresses.
     84         close(sTunFd);
     85     }
     86 
     87     static void fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket);
     88     static int createTunInterface();
     89 
     90 protected:
     91     sp<INetd> mNetd;
     92     static int sTunFd;
     93     static std::string sTunIfName;
     94     static in6_addr sSrcAddr, sDstAddr;
     95     static char sSrcStr[], sDstStr[];
     96 };
     97 
     98 int BinderTest::sTunFd;
     99 std::string BinderTest::sTunIfName;
    100 in6_addr BinderTest::sSrcAddr;
    101 in6_addr BinderTest::sDstAddr;
    102 char BinderTest::sSrcStr[INET6_ADDRSTRLEN];
    103 char BinderTest::sDstStr[INET6_ADDRSTRLEN];
    104 
    105 class TimedOperation : public Stopwatch {
    106 public:
    107     TimedOperation(std::string name): mName(name) {}
    108     virtual ~TimedOperation() {
    109         fprintf(stderr, "    %s: %6.1f ms\n", mName.c_str(), timeTaken());
    110     }
    111 
    112 private:
    113     std::string mName;
    114 };
    115 
    116 TEST_F(BinderTest, TestIsAlive) {
    117     TimedOperation t("isAlive RPC");
    118     bool isAlive = false;
    119     mNetd->isAlive(&isAlive);
    120     ASSERT_TRUE(isAlive);
    121 }
    122 
    123 static int randomUid() {
    124     return 100000 * arc4random_uniform(7) + 10000 + arc4random_uniform(5000);
    125 }
    126 
    127 static std::vector<std::string> runCommand(const std::string& command) {
    128     std::vector<std::string> lines;
    129     FILE *f;
    130 
    131     if ((f = popen(command.c_str(), "r")) == nullptr) {
    132         perror("popen");
    133         return lines;
    134     }
    135 
    136     char *line = nullptr;
    137     size_t bufsize = 0;
    138     ssize_t linelen = 0;
    139     while ((linelen = getline(&line, &bufsize, f)) >= 0) {
    140         lines.push_back(std::string(line, linelen));
    141         free(line);
    142         line = nullptr;
    143     }
    144 
    145     pclose(f);
    146     return lines;
    147 }
    148 
    149 static std::vector<std::string> listIpRules(const char *ipVersion) {
    150     std::string command = StringPrintf("%s %s rule list", IP_PATH, ipVersion);
    151     return runCommand(command);
    152 }
    153 
    154 static std::vector<std::string> listIptablesRule(const char *binary, const char *chainName) {
    155     std::string command = StringPrintf("%s -w -n -L %s", binary, chainName);
    156     return runCommand(command);
    157 }
    158 
    159 static int iptablesRuleLineLength(const char *binary, const char *chainName) {
    160     return listIptablesRule(binary, chainName).size();
    161 }
    162 
    163 TEST_F(BinderTest, TestFirewallReplaceUidChain) {
    164     std::string chainName = StringPrintf("netd_binder_test_%u", arc4random_uniform(10000));
    165     const int kNumUids = 500;
    166     std::vector<int32_t> noUids(0);
    167     std::vector<int32_t> uids(kNumUids);
    168     for (int i = 0; i < kNumUids; i++) {
    169         uids[i] = randomUid();
    170     }
    171 
    172     bool ret;
    173     {
    174         TimedOperation op(StringPrintf("Programming %d-UID whitelist chain", kNumUids));
    175         mNetd->firewallReplaceUidChain(String16(chainName.c_str()), true, uids, &ret);
    176     }
    177     EXPECT_EQ(true, ret);
    178     EXPECT_EQ((int) uids.size() + 6, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
    179     EXPECT_EQ((int) uids.size() + 12, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
    180     {
    181         TimedOperation op("Clearing whitelist chain");
    182         mNetd->firewallReplaceUidChain(String16(chainName.c_str()), false, noUids, &ret);
    183     }
    184     EXPECT_EQ(true, ret);
    185     EXPECT_EQ(4, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
    186     EXPECT_EQ(4, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
    187 
    188     {
    189         TimedOperation op(StringPrintf("Programming %d-UID blacklist chain", kNumUids));
    190         mNetd->firewallReplaceUidChain(String16(chainName.c_str()), false, uids, &ret);
    191     }
    192     EXPECT_EQ(true, ret);
    193     EXPECT_EQ((int) uids.size() + 4, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
    194     EXPECT_EQ((int) uids.size() + 4, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
    195 
    196     {
    197         TimedOperation op("Clearing blacklist chain");
    198         mNetd->firewallReplaceUidChain(String16(chainName.c_str()), false, noUids, &ret);
    199     }
    200     EXPECT_EQ(true, ret);
    201     EXPECT_EQ(4, iptablesRuleLineLength(IPTABLES_PATH, chainName.c_str()));
    202     EXPECT_EQ(4, iptablesRuleLineLength(IP6TABLES_PATH, chainName.c_str()));
    203 
    204     // Check that the call fails if iptables returns an error.
    205     std::string veryLongStringName = "netd_binder_test_UnacceptablyLongIptablesChainName";
    206     mNetd->firewallReplaceUidChain(String16(veryLongStringName.c_str()), true, noUids, &ret);
    207     EXPECT_EQ(false, ret);
    208 }
    209 
    210 static int bandwidthDataSaverEnabled(const char *binary) {
    211     std::vector<std::string> lines = listIptablesRule(binary, "bw_data_saver");
    212 
    213     // Output looks like this:
    214     //
    215     // Chain bw_data_saver (1 references)
    216     // target     prot opt source               destination
    217     // RETURN     all  --  0.0.0.0/0            0.0.0.0/0
    218     EXPECT_EQ(3U, lines.size());
    219     if (lines.size() != 3) return -1;
    220 
    221     EXPECT_TRUE(android::base::StartsWith(lines[2], "RETURN ") ||
    222                 android::base::StartsWith(lines[2], "REJECT "));
    223 
    224     return android::base::StartsWith(lines[2], "REJECT");
    225 }
    226 
    227 bool enableDataSaver(sp<INetd>& netd, bool enable) {
    228     TimedOperation op(enable ? " Enabling data saver" : "Disabling data saver");
    229     bool ret;
    230     netd->bandwidthEnableDataSaver(enable, &ret);
    231     return ret;
    232 }
    233 
    234 int getDataSaverState() {
    235     const int enabled4 = bandwidthDataSaverEnabled(IPTABLES_PATH);
    236     const int enabled6 = bandwidthDataSaverEnabled(IP6TABLES_PATH);
    237     EXPECT_EQ(enabled4, enabled6);
    238     EXPECT_NE(-1, enabled4);
    239     EXPECT_NE(-1, enabled6);
    240     if (enabled4 != enabled6 || (enabled6 != 0 && enabled6 != 1)) {
    241         return -1;
    242     }
    243     return enabled6;
    244 }
    245 
    246 TEST_F(BinderTest, TestBandwidthEnableDataSaver) {
    247     const int wasEnabled = getDataSaverState();
    248     ASSERT_NE(-1, wasEnabled);
    249 
    250     if (wasEnabled) {
    251         ASSERT_TRUE(enableDataSaver(mNetd, false));
    252         EXPECT_EQ(0, getDataSaverState());
    253     }
    254 
    255     ASSERT_TRUE(enableDataSaver(mNetd, false));
    256     EXPECT_EQ(0, getDataSaverState());
    257 
    258     ASSERT_TRUE(enableDataSaver(mNetd, true));
    259     EXPECT_EQ(1, getDataSaverState());
    260 
    261     ASSERT_TRUE(enableDataSaver(mNetd, true));
    262     EXPECT_EQ(1, getDataSaverState());
    263 
    264     if (!wasEnabled) {
    265         ASSERT_TRUE(enableDataSaver(mNetd, false));
    266         EXPECT_EQ(0, getDataSaverState());
    267     }
    268 }
    269 
    270 static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
    271         const std::string& action, const char* ipVersion) {
    272     // Output looks like this:
    273     //   "12500:\tfrom all fwmark 0x0/0x20000 iif lo uidrange 1000-2000 prohibit"
    274     std::vector<std::string> rules = listIpRules(ipVersion);
    275 
    276     std::string prefix = StringPrintf("%" PRIu32 ":", priority);
    277     std::string suffix = StringPrintf(" iif lo uidrange %d-%d %s\n",
    278             range.getStart(), range.getStop(), action.c_str());
    279     for (std::string line : rules) {
    280         if (android::base::StartsWith(line, prefix.c_str())
    281                 && android::base::EndsWith(line, suffix.c_str())) {
    282             return true;
    283         }
    284     }
    285     return false;
    286 }
    287 
    288 static bool ipRuleExistsForRange(const uint32_t priority, const UidRange& range,
    289         const std::string& action) {
    290     bool existsIp4 = ipRuleExistsForRange(priority, range, action, IP_RULE_V4);
    291     bool existsIp6 = ipRuleExistsForRange(priority, range, action, IP_RULE_V6);
    292     EXPECT_EQ(existsIp4, existsIp6);
    293     return existsIp4;
    294 }
    295 
    296 TEST_F(BinderTest, TestNetworkRejectNonSecureVpn) {
    297     constexpr uint32_t RULE_PRIORITY = 12500;
    298 
    299     constexpr int baseUid = MULTIUSER_APP_PER_USER_RANGE * 5;
    300     std::vector<UidRange> uidRanges = {
    301         {baseUid + 150, baseUid + 224},
    302         {baseUid + 226, baseUid + 300}
    303     };
    304 
    305     const std::vector<std::string> initialRulesV4 = listIpRules(IP_RULE_V4);
    306     const std::vector<std::string> initialRulesV6 = listIpRules(IP_RULE_V6);
    307 
    308     // Create two valid rules.
    309     ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(true, uidRanges).isOk());
    310     EXPECT_EQ(initialRulesV4.size() + 2, listIpRules(IP_RULE_V4).size());
    311     EXPECT_EQ(initialRulesV6.size() + 2, listIpRules(IP_RULE_V6).size());
    312     for (auto const& range : uidRanges) {
    313         EXPECT_TRUE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
    314     }
    315 
    316     // Remove the rules.
    317     ASSERT_TRUE(mNetd->networkRejectNonSecureVpn(false, uidRanges).isOk());
    318     EXPECT_EQ(initialRulesV4.size(), listIpRules(IP_RULE_V4).size());
    319     EXPECT_EQ(initialRulesV6.size(), listIpRules(IP_RULE_V6).size());
    320     for (auto const& range : uidRanges) {
    321         EXPECT_FALSE(ipRuleExistsForRange(RULE_PRIORITY, range, "prohibit"));
    322     }
    323 
    324     // Fail to remove the rules a second time after they are already deleted.
    325     binder::Status status = mNetd->networkRejectNonSecureVpn(false, uidRanges);
    326     ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
    327     EXPECT_EQ(ENOENT, status.serviceSpecificErrorCode());
    328 
    329     // All rules should be the same as before.
    330     EXPECT_EQ(initialRulesV4, listIpRules(IP_RULE_V4));
    331     EXPECT_EQ(initialRulesV6, listIpRules(IP_RULE_V6));
    332 }
    333 
    334 int BinderTest::createTunInterface() {
    335     // Generate a random ULA address pair.
    336     arc4random_buf(&sSrcAddr, sizeof(sSrcAddr));
    337     sSrcAddr.s6_addr[0] = 0xfd;
    338     memcpy(&sDstAddr, &sSrcAddr, sizeof(sDstAddr));
    339     sDstAddr.s6_addr[15] ^= 1;
    340 
    341     // Convert the addresses to strings because that's what ifc_add_address takes.
    342     sockaddr_in6 src6 = { .sin6_family = AF_INET6, .sin6_addr = sSrcAddr, };
    343     sockaddr_in6 dst6 = { .sin6_family = AF_INET6, .sin6_addr = sDstAddr, };
    344     int flags = NI_NUMERICHOST;
    345     if (getnameinfo((sockaddr *) &src6, sizeof(src6), sSrcStr, sizeof(sSrcStr), NULL, 0, flags) ||
    346         getnameinfo((sockaddr *) &dst6, sizeof(dst6), sDstStr, sizeof(sDstStr), NULL, 0, flags)) {
    347         return -1;
    348     }
    349 
    350     // Create a tun interface with a name based on our PID.
    351     sTunIfName = StringPrintf("netdtest%u", getpid());
    352     struct ifreq ifr = {
    353         .ifr_ifru = { .ifru_flags = IFF_TUN },
    354     };
    355     snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", sTunIfName.c_str());
    356 
    357     int fd = open(TUN_DEV, O_RDWR | O_NONBLOCK | O_CLOEXEC);
    358     EXPECT_NE(-1, fd) << TUN_DEV << ": " << strerror(errno);
    359     if (fd == -1) return fd;
    360 
    361     int ret = ioctl(fd, TUNSETIFF, &ifr, sizeof(ifr));
    362     EXPECT_EQ(0, ret) << "TUNSETIFF: " << strerror(errno);
    363     if (ret) {
    364         close(fd);
    365         return -1;
    366     }
    367 
    368     if (ifc_add_address(ifr.ifr_name, sSrcStr, 64) ||
    369         ifc_add_address(ifr.ifr_name, sDstStr, 64)) {
    370         close(fd);
    371         return -1;
    372     }
    373     return fd;
    374 }
    375 
    376 // Create a socket pair that isLoopbackSocket won't think is local.
    377 void BinderTest::fakeRemoteSocketPair(int *clientSocket, int *serverSocket, int *acceptedSocket) {
    378     *serverSocket = socket(AF_INET6, SOCK_STREAM, 0);
    379     struct sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_addr = sDstAddr };
    380     ASSERT_EQ(0, bind(*serverSocket, (struct sockaddr *) &server6, sizeof(server6)));
    381 
    382     socklen_t addrlen = sizeof(server6);
    383     ASSERT_EQ(0, getsockname(*serverSocket, (struct sockaddr *) &server6, &addrlen));
    384     ASSERT_EQ(0, listen(*serverSocket, 10));
    385 
    386     *clientSocket = socket(AF_INET6, SOCK_STREAM, 0);
    387     struct sockaddr_in6 client6 = { .sin6_family = AF_INET6, .sin6_addr = sSrcAddr };
    388     ASSERT_EQ(0, bind(*clientSocket, (struct sockaddr *) &client6, sizeof(client6)));
    389     ASSERT_EQ(0, connect(*clientSocket, (struct sockaddr *) &server6, sizeof(server6)));
    390     ASSERT_EQ(0, getsockname(*clientSocket, (struct sockaddr *) &client6, &addrlen));
    391 
    392     *acceptedSocket = accept(*serverSocket, (struct sockaddr *) &server6, &addrlen);
    393     ASSERT_NE(-1, *acceptedSocket);
    394 
    395     ASSERT_EQ(0, memcmp(&client6, &server6, sizeof(client6)));
    396 }
    397 
    398 void checkSocketpairOpen(int clientSocket, int acceptedSocket) {
    399     char buf[4096];
    400     EXPECT_EQ(4, write(clientSocket, "foo", sizeof("foo")));
    401     EXPECT_EQ(4, read(acceptedSocket, buf, sizeof(buf)));
    402     EXPECT_EQ(0, memcmp(buf, "foo", sizeof("foo")));
    403 }
    404 
    405 void checkSocketpairClosed(int clientSocket, int acceptedSocket) {
    406     // Check that the client socket was closed with ECONNABORTED.
    407     int ret = write(clientSocket, "foo", sizeof("foo"));
    408     int err = errno;
    409     EXPECT_EQ(-1, ret);
    410     EXPECT_EQ(ECONNABORTED, err);
    411 
    412     // Check that it sent a RST to the server.
    413     ret = write(acceptedSocket, "foo", sizeof("foo"));
    414     err = errno;
    415     EXPECT_EQ(-1, ret);
    416     EXPECT_EQ(ECONNRESET, err);
    417 }
    418 
    419 TEST_F(BinderTest, TestSocketDestroy) {
    420     int clientSocket, serverSocket, acceptedSocket;
    421     ASSERT_NO_FATAL_FAILURE(fakeRemoteSocketPair(&clientSocket, &serverSocket, &acceptedSocket));
    422 
    423     // Pick a random UID in the system UID range.
    424     constexpr int baseUid = AID_APP - 2000;
    425     static_assert(baseUid > 0, "Not enough UIDs? Please fix this test.");
    426     int uid = baseUid + 500 + arc4random_uniform(1000);
    427     EXPECT_EQ(0, fchown(clientSocket, uid, -1));
    428 
    429     // UID ranges that don't contain uid.
    430     std::vector<UidRange> uidRanges = {
    431         {baseUid + 42, baseUid + 449},
    432         {baseUid + 1536, AID_APP - 4},
    433         {baseUid + 498, uid - 1},
    434         {uid + 1, baseUid + 1520},
    435     };
    436     // A skip list that doesn't contain UID.
    437     std::vector<int32_t> skipUids { baseUid + 123, baseUid + 1600 };
    438 
    439     // Close sockets. Our test socket should be intact.
    440     EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
    441     checkSocketpairOpen(clientSocket, acceptedSocket);
    442 
    443     // UID ranges that do contain uid.
    444     uidRanges = {
    445         {baseUid + 42, baseUid + 449},
    446         {baseUid + 1536, AID_APP - 4},
    447         {baseUid + 498, baseUid + 1520},
    448     };
    449     // Add uid to the skip list.
    450     skipUids.push_back(uid);
    451 
    452     // Close sockets. Our test socket should still be intact because it's in the skip list.
    453     EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
    454     checkSocketpairOpen(clientSocket, acceptedSocket);
    455 
    456     // Now remove uid from skipUids, and close sockets. Our test socket should have been closed.
    457     skipUids.resize(skipUids.size() - 1);
    458     EXPECT_TRUE(mNetd->socketDestroy(uidRanges, skipUids).isOk());
    459     checkSocketpairClosed(clientSocket, acceptedSocket);
    460 
    461     close(clientSocket);
    462     close(serverSocket);
    463     close(acceptedSocket);
    464 }
    465 
    466 namespace {
    467 
    468 int netmaskToPrefixLength(const uint8_t *buf, size_t buflen) {
    469     if (buf == nullptr) return -1;
    470 
    471     int prefixLength = 0;
    472     bool endOfContiguousBits = false;
    473     for (unsigned int i = 0; i < buflen; i++) {
    474         const uint8_t value = buf[i];
    475 
    476         // Bad bit sequence: check for a contiguous set of bits from the high
    477         // end by verifying that the inverted value + 1 is a power of 2
    478         // (power of 2 iff. (v & (v - 1)) == 0).
    479         const uint8_t inverse = ~value + 1;
    480         if ((inverse & (inverse - 1)) != 0) return -1;
    481 
    482         prefixLength += (value == 0) ? 0 : CHAR_BIT - ffs(value) + 1;
    483 
    484         // Bogus netmask.
    485         if (endOfContiguousBits && value != 0) return -1;
    486 
    487         if (value != 0xff) endOfContiguousBits = true;
    488     }
    489 
    490     return prefixLength;
    491 }
    492 
    493 template<typename T>
    494 int netmaskToPrefixLength(const T *p) {
    495     return netmaskToPrefixLength(reinterpret_cast<const uint8_t*>(p), sizeof(T));
    496 }
    497 
    498 
    499 static bool interfaceHasAddress(
    500         const std::string &ifname, const char *addrString, int prefixLength) {
    501     struct addrinfo *addrinfoList = nullptr;
    502     ScopedAddrinfo addrinfoCleanup(addrinfoList);
    503 
    504     const struct addrinfo hints = {
    505         .ai_flags    = AI_NUMERICHOST,
    506         .ai_family   = AF_UNSPEC,
    507         .ai_socktype = SOCK_DGRAM,
    508     };
    509     if (getaddrinfo(addrString, nullptr, &hints, &addrinfoList) != 0 ||
    510         addrinfoList == nullptr || addrinfoList->ai_addr == nullptr) {
    511         return false;
    512     }
    513 
    514     struct ifaddrs *ifaddrsList = nullptr;
    515     ScopedIfaddrs ifaddrsCleanup(ifaddrsList);
    516 
    517     if (getifaddrs(&ifaddrsList) != 0) {
    518         return false;
    519     }
    520 
    521     for (struct ifaddrs *addr = ifaddrsList; addr != nullptr; addr = addr->ifa_next) {
    522         if (std::string(addr->ifa_name) != ifname ||
    523             addr->ifa_addr == nullptr ||
    524             addr->ifa_addr->sa_family != addrinfoList->ai_addr->sa_family) {
    525             continue;
    526         }
    527 
    528         switch (addr->ifa_addr->sa_family) {
    529         case AF_INET: {
    530             auto *addr4 = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_addr);
    531             auto *want = reinterpret_cast<const struct sockaddr_in*>(addrinfoList->ai_addr);
    532             if (memcmp(&addr4->sin_addr, &want->sin_addr, sizeof(want->sin_addr)) != 0) {
    533                 continue;
    534             }
    535 
    536             if (prefixLength < 0) return true;  // not checking prefix lengths
    537 
    538             if (addr->ifa_netmask == nullptr) return false;
    539             auto *nm = reinterpret_cast<const struct sockaddr_in*>(addr->ifa_netmask);
    540             EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin_addr));
    541             return (prefixLength == netmaskToPrefixLength(&nm->sin_addr));
    542         }
    543         case AF_INET6: {
    544             auto *addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_addr);
    545             auto *want = reinterpret_cast<const struct sockaddr_in6*>(addrinfoList->ai_addr);
    546             if (memcmp(&addr6->sin6_addr, &want->sin6_addr, sizeof(want->sin6_addr)) != 0) {
    547                 continue;
    548             }
    549 
    550             if (prefixLength < 0) return true;  // not checking prefix lengths
    551 
    552             if (addr->ifa_netmask == nullptr) return false;
    553             auto *nm = reinterpret_cast<const struct sockaddr_in6*>(addr->ifa_netmask);
    554             EXPECT_EQ(prefixLength, netmaskToPrefixLength(&nm->sin6_addr));
    555             return (prefixLength == netmaskToPrefixLength(&nm->sin6_addr));
    556         }
    557         default:
    558             // Cannot happen because we have already screened for matching
    559             // address families at the top of each iteration.
    560             continue;
    561         }
    562     }
    563 
    564     return false;
    565 }
    566 
    567 }  // namespace
    568 
    569 TEST_F(BinderTest, TestInterfaceAddRemoveAddress) {
    570     static const struct TestData {
    571         const char *addrString;
    572         const int   prefixLength;
    573         const bool  expectSuccess;
    574     } kTestData[] = {
    575         { "192.0.2.1", 24, true },
    576         { "192.0.2.2", 25, true },
    577         { "192.0.2.3", 32, true },
    578         { "192.0.2.4", 33, false },
    579         { "192.not.an.ip", 24, false },
    580         { "2001:db8::1", 64, true },
    581         { "2001:db8::2", 65, true },
    582         { "2001:db8::3", 128, true },
    583         { "2001:db8::4", 129, false },
    584         { "foo:bar::bad", 64, false },
    585     };
    586 
    587     for (unsigned int i = 0; i < arraysize(kTestData); i++) {
    588         const auto &td = kTestData[i];
    589 
    590         // [1.a] Add the address.
    591         binder::Status status = mNetd->interfaceAddAddress(
    592                 sTunIfName, td.addrString, td.prefixLength);
    593         if (td.expectSuccess) {
    594             EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
    595         } else {
    596             ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
    597             ASSERT_NE(0, status.serviceSpecificErrorCode());
    598         }
    599 
    600         // [1.b] Verify the addition meets the expectation.
    601         if (td.expectSuccess) {
    602             EXPECT_TRUE(interfaceHasAddress(sTunIfName, td.addrString, td.prefixLength));
    603         } else {
    604             EXPECT_FALSE(interfaceHasAddress(sTunIfName, td.addrString, -1));
    605         }
    606 
    607         // [2.a] Try to remove the address.  If it was not previously added, removing it fails.
    608         status = mNetd->interfaceDelAddress(sTunIfName, td.addrString, td.prefixLength);
    609         if (td.expectSuccess) {
    610             EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
    611         } else {
    612             ASSERT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
    613             ASSERT_NE(0, status.serviceSpecificErrorCode());
    614         }
    615 
    616         // [2.b] No matter what, the address should not be present.
    617         EXPECT_FALSE(interfaceHasAddress(sTunIfName, td.addrString, -1));
    618     }
    619 }
    620 
    621 TEST_F(BinderTest, TestSetProcSysNet) {
    622     static const struct TestData {
    623         const int family;
    624         const int which;
    625         const char *ifname;
    626         const char *parameter;
    627         const char *value;
    628         const int expectedReturnCode;
    629     } kTestData[] = {
    630         { INetd::IPV4, INetd::CONF, sTunIfName.c_str(), "arp_ignore", "1", 0 },
    631         { -1, INetd::CONF, sTunIfName.c_str(), "arp_ignore", "1", EAFNOSUPPORT },
    632         { INetd::IPV4, -1, sTunIfName.c_str(), "arp_ignore", "1", EINVAL },
    633         { INetd::IPV4, INetd::CONF, "..", "conf/lo/arp_ignore", "1", EINVAL },
    634         { INetd::IPV4, INetd::CONF, ".", "lo/arp_ignore", "1", EINVAL },
    635         { INetd::IPV4, INetd::CONF, sTunIfName.c_str(), "../all/arp_ignore", "1", EINVAL },
    636         { INetd::IPV6, INetd::NEIGH, sTunIfName.c_str(), "ucast_solicit", "7", 0 },
    637     };
    638 
    639     for (unsigned int i = 0; i < arraysize(kTestData); i++) {
    640         const auto &td = kTestData[i];
    641 
    642         const binder::Status status = mNetd->setProcSysNet(
    643                     td.family, td.which, td.ifname, td.parameter,
    644                     td.value);
    645 
    646         if (td.expectedReturnCode == 0) {
    647             SCOPED_TRACE(String8::format("test case %d should have passed", i));
    648             EXPECT_EQ(0, status.exceptionCode());
    649             EXPECT_EQ(0, status.serviceSpecificErrorCode());
    650         } else {
    651             SCOPED_TRACE(String8::format("test case %d should have failed", i));
    652             EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
    653             EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
    654         }
    655     }
    656 }
    657