blob: 6f2fc09d766f8b0ef9e0cc789c8524d97ace596b [file] [log] [blame]
Luke Huang63df9482019-05-25 18:24:03 +08001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <poll.h> /* poll */
18#include <sys/socket.h>
19
20#include <thread>
21
22#include <android-base/parseint.h>
23#include <android-base/unique_fd.h>
24#include <gtest/gtest.h>
25
26#include "NetdClient.h"
27#include "netdclient_priv.h"
28
29namespace {
30
31// Keep in sync with FrameworkListener.cpp (500, "Command not recognized")
32constexpr char NOT_SUPPORT_MSG[] = "500 Command not recognized";
33
34void serverLoop(int dnsProxyFd) {
35 while (true) {
36 pollfd fds[1] = {{.fd = dnsProxyFd, .events = POLLIN}};
37 enum { SERVERFD = 0 };
38
39 const int s = TEMP_FAILURE_RETRY(poll(fds, std::size(fds), -1));
40 if (s <= 0) break;
41
42 if (fds[SERVERFD].revents & POLLIN) {
43 char buf[4096];
44 TEMP_FAILURE_RETRY(read(fds[SERVERFD].fd, &buf, sizeof(buf)));
45 // TODO: verify command
46 TEMP_FAILURE_RETRY(write(fds[SERVERFD].fd, NOT_SUPPORT_MSG, sizeof(NOT_SUPPORT_MSG)));
47 }
48 }
49}
50
51} // namespace
52
53TEST(NetdClientTest, getNetworkForDnsInternal) {
54 // Test invalid fd
55 unsigned dnsNetId = 0;
56 const int invalidFd = -1;
57 EXPECT_EQ(-EBADF, getNetworkForDnsInternal(invalidFd, &dnsNetId));
58
59 // Test what the client does if the resolver does not support the "getdnsnetid" command.
60 android::base::unique_fd clientFd, serverFd;
61 ASSERT_TRUE(android::base::Socketpair(AF_UNIX, &clientFd, &serverFd));
62
63 std::thread serverThread = std::thread(serverLoop, serverFd.get());
64
65 EXPECT_EQ(-EOPNOTSUPP, getNetworkForDnsInternal(clientFd.get(), &dnsNetId));
66
67 clientFd.reset(); // Causes serverLoop() to exit
68 serverThread.join();
69}
70
71TEST(NetdClientTest, getNetworkForDns) {
72 // Test null input
73 unsigned* testNull = nullptr;
74 EXPECT_EQ(-EFAULT, getNetworkForDns(testNull));
75}