Add unit for setAllowNetworkingForProcess

Bug: 150028556
Test: atest netdclient_test
Change-Id: I0342b2981179dd77bf6a210cb7f6fa6ca069c487
diff --git a/client/NetdClientTest.cpp b/client/NetdClientTest.cpp
index 126c7fd..20f601a 100644
--- a/client/NetdClientTest.cpp
+++ b/client/NetdClientTest.cpp
@@ -31,6 +31,16 @@
 // Keep in sync with FrameworkListener.cpp (500, "Command not recognized")
 constexpr char NOT_SUPPORT_MSG[] = "500 Command not recognized";
 
+int openDnsProxyFuncStub() {
+    return -1;
+};
+
+typedef int (*DnsOpenProxyType)();
+typedef int (*SocketFunctionType)(int, int, int);
+
+DnsOpenProxyType openDnsProxyFuncPtr = openDnsProxyFuncStub;
+SocketFunctionType socketFuncPtr = socket;
+
 void serverLoop(int dnsProxyFd) {
     while (true) {
         pollfd fds[1] = {{.fd = dnsProxyFd, .events = POLLIN}};
@@ -49,6 +59,35 @@
     }
 }
 
+void expectAllowNetworkingForProcess() {
+    // netdClientSocket
+    android::base::unique_fd ipv4(socketFuncPtr(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0)),
+            ipv6(socketFuncPtr(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0));
+    EXPECT_LE(3, ipv4);
+    EXPECT_LE(3, ipv6);
+
+    // dns_open_proxy
+    android::base::unique_fd dnsproxydSocket(openDnsProxyFuncPtr());
+    EXPECT_LE(3, dnsproxydSocket);
+}
+
+void expectNotAllowNetworkingForProcess() {
+    // netdClientSocket
+    android::base::unique_fd unixSocket(socketFuncPtr(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0));
+    EXPECT_LE(3, unixSocket);
+    android::base::unique_fd ipv4(socketFuncPtr(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0));
+    EXPECT_EQ(-1, ipv4);
+    EXPECT_EQ(errno, EPERM);
+    android::base::unique_fd ipv6(socketFuncPtr(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0));
+    EXPECT_EQ(-1, ipv6);
+    EXPECT_EQ(errno, EPERM);
+
+    // dns_open_proxy
+    android::base::unique_fd dnsproxydSocket(openDnsProxyFuncPtr());
+    EXPECT_EQ(-1, dnsproxydSocket);
+    EXPECT_EQ(errno, EPERM);
+}
+
 }  // namespace
 
 TEST(NetdClientTest, getNetworkForDnsInternal) {
@@ -92,3 +131,16 @@
     EXPECT_EQ(0, protectFromVpn(s));
     close(s);
 }
+
+TEST(NetdClientTest, setAllowNetworkingForProcess) {
+    netdClientInitDnsOpenProxy(&openDnsProxyFuncPtr);
+    netdClientInitSocket(&socketFuncPtr);
+    // At the beginning, we should be able to use socket since the default setting is allowing.
+    expectAllowNetworkingForProcess();
+    // Disable
+    setAllowNetworkingForProcess(false);
+    expectNotAllowNetworkingForProcess();
+    // Reset
+    setAllowNetworkingForProcess(true);
+    expectAllowNetworkingForProcess();
+}