summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAndroid Build Coastguard Worker <android-build-coastguard-worker@google.com>2022-04-27 13:20:28 +0000
committerAndroid Build Coastguard Worker <android-build-coastguard-worker@google.com>2022-04-27 13:20:28 +0000
commit587095e6c45deb2d49622ba94d9e462940c5125f (patch)
tree3e2a4853bd4634fe9019889dc7fb0ef64a5628d0
parent0ce696aa0e0c6790be6ec899a31e4f356de757f7 (diff)
parentf7267cfcfc7db62b8365fcff621403c0dadcfd67 (diff)
downloadnetd-587095e6c45deb2d49622ba94d9e462940c5125f.tar.gz
Snap for 8505378 from f7267cfcfc7db62b8365fcff621403c0dadcfd67 to mainline-go-media-release
Change-Id: I7ab09bd29784d6cdf82a70ca3c3df7a01a2f0315
-rw-r--r--Android.bp1
-rw-r--r--client/Android.bp1
-rw-r--r--include/binder_utils/BinderUtil.h60
-rw-r--r--server/Android.bp13
-rw-r--r--server/BandwidthController.cpp12
-rw-r--r--server/BandwidthControllerTest.cpp2
-rw-r--r--server/ClatdController.cpp953
-rw-r--r--server/ClatdController.h127
-rw-r--r--server/ClatdControllerTest.cpp323
-rw-r--r--server/Controllers.cpp7
-rw-r--r--server/Controllers.h2
-rw-r--r--server/ControllersTest.cpp2
-rw-r--r--server/MDnsEventReporter.cpp97
-rw-r--r--server/MDnsEventReporter.h60
-rw-r--r--server/MDnsSdListener.cpp525
-rw-r--r--server/MDnsSdListener.h62
-rw-r--r--server/MDnsService.cpp120
-rw-r--r--server/MDnsService.h50
-rw-r--r--server/NdcDispatcher.cpp35
-rw-r--r--server/NdcDispatcher.h7
-rw-r--r--server/NetdNativeService.cpp69
-rw-r--r--server/RouteController.cpp61
-rw-r--r--server/RouteController.h10
-rw-r--r--server/TcUtils.cpp387
-rw-r--r--server/TcUtils.h49
-rw-r--r--server/TcUtilsTest.cpp212
-rw-r--r--server/main.cpp14
-rw-r--r--tests/Android.bp2
-rw-r--r--tests/binder_test.cpp185
29 files changed, 703 insertions, 2745 deletions
diff --git a/Android.bp b/Android.bp
index 9666c4c7..88379109 100644
--- a/Android.bp
+++ b/Android.bp
@@ -20,7 +20,6 @@ cc_library_headers {
export_include_dirs: ["include"],
apex_available: [
"//apex_available:platform",
- "com.android.tethering",
],
}
diff --git a/client/Android.bp b/client/Android.bp
index 1a6114b4..22cb5c15 100644
--- a/client/Android.bp
+++ b/client/Android.bp
@@ -42,7 +42,6 @@ cc_library {
},
apex_available: [
"//apex_available:platform",
- "com.android.tethering",
],
}
diff --git a/include/binder_utils/BinderUtil.h b/include/binder_utils/BinderUtil.h
index 469fa681..92754c81 100644
--- a/include/binder_utils/BinderUtil.h
+++ b/include/binder_utils/BinderUtil.h
@@ -16,8 +16,15 @@
#pragma once
+#include "NetdPermissions.h"
+
+#include <android-base/stringprintf.h>
#include <android-base/strings.h>
+#include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
+#include <binder/Status.h>
#include <fmt/format.h>
+#include <private/android_filesystem_config.h>
#ifdef ANDROID_BINDER_STATUS_H
#define IS_BINDER_OK(__ex__) (__ex__ == ::android::binder::Status::EX_NONE)
@@ -39,7 +46,7 @@
#endif
-std::string exceptionToString(int32_t exception) {
+inline std::string exceptionToString(int32_t exception) {
switch (exception) {
EXCEPTION_TO_STRING(EX_SECURITY, "SecurityException")
EXCEPTION_TO_STRING(EX_BAD_PARCELABLE, "BadParcelableException")
@@ -100,3 +107,54 @@ void binderCallLogFn(const LogType& log, const LogFn& logFn) {
// escape newline characters to avoid multiline log entries
logFn(::android::base::StringReplace(output, "\n", "\\n", true));
}
+
+// The input permissions should be equivalent that this function would return ok if any of them is
+// granted.
+inline android::binder::Status checkAnyPermission(const std::vector<const char*>& permissions) {
+ pid_t pid = android::IPCThreadState::self()->getCallingPid();
+ uid_t uid = android::IPCThreadState::self()->getCallingUid();
+
+ // TODO: Do the pure permission check in this function. Have another method
+ // (e.g. checkNetworkStackPermission) to wrap AID_SYSTEM and
+ // AID_NETWORK_STACK uid check.
+ // If the caller is the system UID, don't check permissions.
+ // Otherwise, if the system server's binder thread pool is full, and all the threads are
+ // blocked on a thread that's waiting for us to complete, we deadlock. http://b/69389492
+ //
+ // From a security perspective, there is currently no difference, because:
+ // 1. The system server has the NETWORK_STACK permission, which grants access to all the
+ // IPCs in this file.
+ // 2. AID_SYSTEM always has all permissions. See ActivityManager#checkComponentPermission.
+ if (uid == AID_SYSTEM) {
+ return android::binder::Status::ok();
+ }
+ // AID_NETWORK_STACK own MAINLINE_NETWORK_STACK permission, don't IPC to system server to check
+ // MAINLINE_NETWORK_STACK permission. Cross-process(netd, networkstack and system server)
+ // deadlock: http://b/149766727
+ if (uid == AID_NETWORK_STACK) {
+ for (const char* permission : permissions) {
+ if (std::strcmp(permission, PERM_MAINLINE_NETWORK_STACK) == 0) {
+ return android::binder::Status::ok();
+ }
+ }
+ }
+
+ for (const char* permission : permissions) {
+ if (checkPermission(android::String16(permission), pid, uid)) {
+ return android::binder::Status::ok();
+ }
+ }
+
+ auto err = android::base::StringPrintf(
+ "UID %d / PID %d does not have any of the following permissions: %s", uid, pid,
+ android::base::Join(permissions, ',').c_str());
+ return android::binder::Status::fromExceptionCode(android::binder::Status::EX_SECURITY,
+ err.c_str());
+}
+
+inline android::binder::Status statusFromErrcode(int ret) {
+ if (ret) {
+ return android::binder::Status::fromServiceSpecificError(-ret, strerror(-ret));
+ }
+ return android::binder::Status::ok();
+}
diff --git a/server/Android.bp b/server/Android.bp
index 809042ff..f29f6cfc 100644
--- a/server/Android.bp
+++ b/server/Android.bp
@@ -29,7 +29,6 @@ filegroup {
"NetdConstants.cpp",
"InterfaceController.cpp",
"NetlinkCommands.cpp",
- "TcUtils.cpp",
"SockDiag.cpp",
"XfrmController.cpp",
],
@@ -46,7 +45,6 @@ cc_library_static {
header_libs: ["bpf_connectivity_headers"],
srcs: [
"BandwidthController.cpp",
- "ClatdController.cpp",
"Controllers.cpp",
"NetdConstants.cpp",
"FirewallController.cpp",
@@ -56,7 +54,6 @@ cc_library_static {
"NFLogListener.cpp",
"NetlinkCommands.cpp",
"NetlinkManager.cpp",
- "TcUtils.cpp",
"RouteController.cpp",
"SockDiag.cpp",
"StrictController.cpp",
@@ -79,6 +76,7 @@ cc_library_static {
],
static_libs: [
"libip_checksum",
+ "libtcutils",
],
aidl: {
export_aidl_headers: true,
@@ -117,6 +115,7 @@ cc_binary {
"libselinux",
"libsysutils",
"libutils",
+ "mdns_aidl_interface-V1-cpp",
"netd_aidl_interface-V8-cpp",
"netd_event_listener_interface-V1-cpp",
"oemnetd_aidl_interface-cpp",
@@ -124,13 +123,16 @@ cc_binary {
static_libs: [
"libip_checksum",
"libnetd_server",
+ "libtcutils",
],
srcs: [
"DummyNetwork.cpp",
"EventReporter.cpp",
"FwmarkServer.cpp",
"LocalNetwork.cpp",
+ "MDnsEventReporter.cpp",
"MDnsSdListener.cpp",
+ "MDnsService.cpp",
"NetdCommand.cpp",
"NetdHwService.cpp",
"NetdNativeService.cpp",
@@ -170,7 +172,7 @@ cc_binary {
"libutils",
"libbinder",
"dnsresolver_aidl_interface-V7-cpp",
- "netd_aidl_interface-V6-cpp", // ndc is going to be deprecated. Keep it in v6 is enough.
+ "netd_aidl_interface-V8-cpp",
],
srcs: [
"ndc.cpp",
@@ -201,7 +203,6 @@ cc_test {
],
srcs: [
"BandwidthControllerTest.cpp",
- "ClatdControllerTest.cpp",
"ControllersTest.cpp",
"FirewallControllerTest.cpp",
"IdletimerControllerTest.cpp",
@@ -209,7 +210,6 @@ cc_test {
"IptablesBaseTest.cpp",
"IptablesRestoreControllerTest.cpp",
"NFLogListenerTest.cpp",
- "TcUtilsTest.cpp",
"RouteControllerTest.cpp",
"SockDiagTest.cpp",
"StrictControllerTest.cpp",
@@ -222,6 +222,7 @@ cc_test {
"libip_checksum",
"libnetd_server",
"libnetd_test_tun_interface",
+ "libtcutils",
"netd_aidl_interface-V8-cpp",
"netd_event_listener_interface-V1-cpp",
],
diff --git a/server/BandwidthController.cpp b/server/BandwidthController.cpp
index 5918dbcb..96a82e23 100644
--- a/server/BandwidthController.cpp
+++ b/server/BandwidthController.cpp
@@ -66,6 +66,9 @@ const char BandwidthController::LOCAL_RAW_PREROUTING[] = "bw_raw_PREROUTING";
const char BandwidthController::LOCAL_MANGLE_POSTROUTING[] = "bw_mangle_POSTROUTING";
const char BandwidthController::LOCAL_GLOBAL_ALERT[] = "bw_global_alert";
+// Sync from packages/modules/Connectivity/bpf_progs/clatd.c
+#define CLAT_MARK 0xdeadc1a7
+
auto BandwidthController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
using android::base::Join;
@@ -224,6 +227,8 @@ std::vector<std::string> getBasicAccountingCommands() {
"COMMIT",
"*raw",
+ // Drop duplicate ingress clat packets
+ StringPrintf("-A bw_raw_PREROUTING -m mark --mark 0x%x -j DROP", CLAT_MARK),
// Prevents IPSec double counting (Tunnel mode and Transport mode,
// respectively)
("-A bw_raw_PREROUTING -i " IPSEC_IFACE_PREFIX "+ -j RETURN"),
@@ -233,9 +238,7 @@ std::vector<std::string> getBasicAccountingCommands() {
// interface and later correct for overhead (+20 bytes/packet).
//
// Note: eBPF offloaded packets never hit base interface's ip6tables, and non
- // offloaded packets (which when using xt_qtaguid means all packets, because
- // clat eBPF offload does not work on xt_qtaguid devices) are dropped in
- // clat_raw_PREROUTING.
+ // offloaded packets are dropped up above due to being marked with CLAT_MARK
//
// Hence we will never double count and additional corrections are not needed.
// We can simply take the sum of base and stacked (+20B/pkt) interface counts.
@@ -249,9 +252,6 @@ std::vector<std::string> getBasicAccountingCommands() {
"-A bw_mangle_POSTROUTING -m policy --pol ipsec --dir out -j RETURN",
// Clear the uid billing done (egress) mark before sending this packet
StringPrintf("-A bw_mangle_POSTROUTING -j MARK --set-mark 0x0/0x%x", uidBillingMask),
- // Packets from the clat daemon have already been counted on egress through the
- // stacked v4-* interface.
- "-A bw_mangle_POSTROUTING -m owner --uid-owner clat -j RETURN",
// This is egress interface accounting: we account 464xlat traffic only on
// the clat interface (as offloaded packets never hit base interface's ip6tables)
// and later sum base and stacked with overhead (+20B/pkt) in higher layers
diff --git a/server/BandwidthControllerTest.cpp b/server/BandwidthControllerTest.cpp
index beb40fae..e7d29d23 100644
--- a/server/BandwidthControllerTest.cpp
+++ b/server/BandwidthControllerTest.cpp
@@ -187,6 +187,7 @@ TEST_F(BandwidthControllerTest, TestEnableBandwidthControl) {
"-I bw_happy_box -m bpf --object-pinned " XT_BPF_ALLOWLIST_PROG_PATH " -j RETURN\n"
"COMMIT\n"
"*raw\n"
+ "-A bw_raw_PREROUTING -m mark --mark 0xdeadc1a7 -j DROP\n"
"-A bw_raw_PREROUTING -i ipsec+ -j RETURN\n"
"-A bw_raw_PREROUTING -m policy --pol ipsec --dir in -j RETURN\n"
"-A bw_raw_PREROUTING -m bpf --object-pinned " XT_BPF_INGRESS_PROG_PATH "\n"
@@ -195,7 +196,6 @@ TEST_F(BandwidthControllerTest, TestEnableBandwidthControl) {
"-A bw_mangle_POSTROUTING -o ipsec+ -j RETURN\n"
"-A bw_mangle_POSTROUTING -m policy --pol ipsec --dir out -j RETURN\n"
"-A bw_mangle_POSTROUTING -j MARK --set-mark 0x0/0x100000\n"
- "-A bw_mangle_POSTROUTING -m owner --uid-owner clat -j RETURN\n"
"-A bw_mangle_POSTROUTING -m bpf --object-pinned " XT_BPF_EGRESS_PROG_PATH "\n"
"COMMIT\n";
// clang-format on
diff --git a/server/ClatdController.cpp b/server/ClatdController.cpp
deleted file mode 100644
index 7062bc72..00000000
--- a/server/ClatdController.cpp
+++ /dev/null
@@ -1,953 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <map>
-#include <string>
-
-#include <arpa/inet.h>
-#include <errno.h>
-#include <linux/if_packet.h>
-#include <linux/if_tun.h>
-#include <linux/ioctl.h>
-#include <net/if.h>
-#include <netinet/in.h>
-#include <spawn.h>
-#include <sys/types.h>
-#include <sys/wait.h>
-#include <unistd.h>
-
-#define LOG_TAG "ClatdController"
-#include <log/log.h>
-
-#include "ClatdController.h"
-#include "InterfaceController.h"
-
-#include <android/net/InterfaceConfigurationParcel.h>
-#include <netdutils/Status.h>
-
-#include "android-base/properties.h"
-#include "android-base/scopeguard.h"
-#include "android-base/stringprintf.h"
-#include "android-base/unique_fd.h"
-#include "bpf/BpfMap.h"
-#include "bpf_shared.h"
-#include "netdutils/DumpWriter.h"
-
-extern "C" {
-#include "checksum.h"
-}
-
-#include "Fwmark.h"
-#include "NetdConstants.h"
-#include "NetworkController.h"
-#include "TcUtils.h"
-#include "netid_client.h"
-
-// Sync from external/android-clat/clatd.{c, h}
-#define MAXMTU 65536
-#define PACKETLEN (MAXMTU + sizeof(struct tun_pi))
-/* 40 bytes IPv6 header - 20 bytes IPv4 header + 8 bytes fragment header */
-#define MTU_DELTA 28
-
-static const char* kClatdPath = "/apex/com.android.tethering/bin/for-system/clatd";
-
-// For historical reasons, start with 192.0.0.4, and after that, use all subsequent addresses in
-// 192.0.0.0/29 (RFC 7335).
-static const char* kV4AddrString = "192.0.0.4";
-static const in_addr kV4Addr = {inet_addr(kV4AddrString)};
-static const int kV4AddrLen = 29;
-
-using android::base::Result;
-using android::base::StringPrintf;
-using android::base::unique_fd;
-using android::bpf::BpfMap;
-using android::netdutils::DumpWriter;
-using android::netdutils::ScopedIndent;
-
-namespace android {
-namespace net {
-
-void ClatdController::init(void) {
- std::lock_guard guard(mutex);
-
- int rv = getClatEgress4MapFd();
- if (rv < 0) {
- ALOGE("getClatEgress4MapFd() failure: %s", strerror(-rv));
- return;
- }
- mClatEgress4Map.reset(rv);
-
- rv = getClatIngress6MapFd();
- if (rv < 0) {
- ALOGE("getClatIngress6MapFd() failure: %s", strerror(-rv));
- mClatEgress4Map.reset(-1);
- return;
- }
- mClatIngress6Map.reset(rv);
-
- mClatEgress4Map.clear();
- mClatIngress6Map.clear();
-}
-
-bool ClatdController::isIpv4AddressFree(in_addr_t addr) {
- int s = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
- if (s == -1) {
- return 0;
- }
-
- // Attempt to connect to the address. If the connection succeeds and getsockname returns the
- // same then the address is already assigned to the system and we can't use it.
- struct sockaddr_in sin = {
- .sin_family = AF_INET,
- .sin_port = htons(53),
- .sin_addr = {addr},
- };
- socklen_t len = sizeof(sin);
- bool inuse = connect(s, (struct sockaddr*)&sin, sizeof(sin)) == 0 &&
- getsockname(s, (struct sockaddr*)&sin, &len) == 0 && (size_t)len >= sizeof(sin) &&
- sin.sin_addr.s_addr == addr;
-
- close(s);
- return !inuse;
-}
-
-// Picks a free IPv4 address, starting from ip and trying all addresses in the prefix in order.
-// ip - the IP address from the configuration file
-// prefixlen - the length of the prefix from which addresses may be selected.
-// returns: the IPv4 address, or INADDR_NONE if no addresses were available
-in_addr_t ClatdController::selectIpv4Address(const in_addr ip, int16_t prefixlen) {
- // Don't accept prefixes that are too large because we scan addresses one by one.
- if (prefixlen < 16 || prefixlen > 32) {
- return INADDR_NONE;
- }
-
- // All these are in host byte order.
- in_addr_t mask = 0xffffffff >> (32 - prefixlen) << (32 - prefixlen);
- in_addr_t ipv4 = ntohl(ip.s_addr);
- in_addr_t first_ipv4 = ipv4;
- in_addr_t prefix = ipv4 & mask;
-
- // Pick the first IPv4 address in the pool, wrapping around if necessary.
- // So, for example, 192.0.0.4 -> 192.0.0.5 -> 192.0.0.6 -> 192.0.0.7 -> 192.0.0.0.
- do {
- if (isIpv4AddressFreeFunc(htonl(ipv4))) {
- return htonl(ipv4);
- }
- ipv4 = prefix | ((ipv4 + 1) & ~mask);
- } while (ipv4 != first_ipv4);
-
- return INADDR_NONE;
-}
-
-// Alters the bits in the IPv6 address to make them checksum neutral with v4 and nat64Prefix.
-void ClatdController::makeChecksumNeutral(in6_addr* v6, const in_addr v4,
- const in6_addr& nat64Prefix) {
- // Fill last 8 bytes of IPv6 address with random bits.
- arc4random_buf(&v6->s6_addr[8], 8);
-
- // Make the IID checksum-neutral. That is, make it so that:
- // checksum(Local IPv4 | Remote IPv4) = checksum(Local IPv6 | Remote IPv6)
- // in other words (because remote IPv6 = NAT64 prefix | Remote IPv4):
- // checksum(Local IPv4) = checksum(Local IPv6 | NAT64 prefix)
- // Do this by adjusting the two bytes in the middle of the IID.
-
- uint16_t middlebytes = (v6->s6_addr[11] << 8) + v6->s6_addr[12];
-
- uint32_t c1 = ip_checksum_add(0, &v4, sizeof(v4));
- uint32_t c2 = ip_checksum_add(0, &nat64Prefix, sizeof(nat64Prefix)) +
- ip_checksum_add(0, v6, sizeof(*v6));
-
- uint16_t delta = ip_checksum_adjust(middlebytes, c1, c2);
- v6->s6_addr[11] = delta >> 8;
- v6->s6_addr[12] = delta & 0xff;
-}
-
-// Picks a random interface ID that is checksum neutral with the IPv4 address and the NAT64 prefix.
-int ClatdController::generateIpv6Address(const char* iface, const in_addr v4,
- const in6_addr& nat64Prefix, in6_addr* v6) {
- unique_fd s(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
- if (s == -1) return -errno;
-
- if (setsockopt(s, SOL_SOCKET, SO_BINDTODEVICE, iface, strlen(iface) + 1) == -1) {
- return -errno;
- }
-
- sockaddr_in6 sin6 = {.sin6_family = AF_INET6, .sin6_addr = nat64Prefix};
- if (connect(s, reinterpret_cast<struct sockaddr*>(&sin6), sizeof(sin6)) == -1) {
- return -errno;
- }
-
- socklen_t len = sizeof(sin6);
- if (getsockname(s, reinterpret_cast<struct sockaddr*>(&sin6), &len) == -1) {
- return -errno;
- }
-
- *v6 = sin6.sin6_addr;
-
- if (IN6_IS_ADDR_UNSPECIFIED(v6) || IN6_IS_ADDR_LOOPBACK(v6) || IN6_IS_ADDR_LINKLOCAL(v6) ||
- IN6_IS_ADDR_SITELOCAL(v6) || IN6_IS_ADDR_ULA(v6)) {
- return -ENETUNREACH;
- }
-
- makeChecksumNeutral(v6, v4, nat64Prefix);
-
- return 0;
-}
-
-void ClatdController::maybeStartBpf(const ClatdTracker& tracker) {
- auto isEthernet = android::net::isEthernet(tracker.iface);
- if (!isEthernet.ok()) {
- ALOGE("isEthernet(%s[%d]) failure: %s", tracker.iface, tracker.ifIndex,
- isEthernet.error().message().c_str());
- return;
- }
-
- // This program will be attached to the v4-* interface which is a TUN and thus always rawip.
- int rv = getClatEgress4ProgFd(RAWIP);
- if (rv < 0) {
- ALOGE("getClatEgress4ProgFd(RAWIP) failure: %s", strerror(-rv));
- return;
- }
- unique_fd txRawIpProgFd(rv);
-
- rv = getClatIngress6ProgFd(isEthernet.value());
- if (rv < 0) {
- ALOGE("getClatIngress6ProgFd(%d) failure: %s", isEthernet.value(), strerror(-rv));
- return;
- }
- unique_fd rxProgFd(rv);
-
- ClatEgress4Key txKey = {
- .iif = tracker.v4ifIndex,
- .local4 = tracker.v4,
- };
- ClatEgress4Value txValue = {
- .oif = tracker.ifIndex,
- .local6 = tracker.v6,
- .pfx96 = tracker.pfx96,
- .oifIsEthernet = isEthernet.value(),
- };
-
- auto ret = mClatEgress4Map.writeValue(txKey, txValue, BPF_ANY);
- if (!ret.ok()) {
- ALOGE("mClatEgress4Map.writeValue failure: %s", strerror(ret.error().code()));
- return;
- }
-
- ClatIngress6Key rxKey = {
- .iif = tracker.ifIndex,
- .pfx96 = tracker.pfx96,
- .local6 = tracker.v6,
- };
- ClatIngress6Value rxValue = {
- // TODO: move all the clat code to eBPF and remove the tun interface entirely.
- .oif = tracker.v4ifIndex,
- .local4 = tracker.v4,
- };
-
- ret = mClatIngress6Map.writeValue(rxKey, rxValue, BPF_ANY);
- if (!ret.ok()) {
- ALOGE("mClatIngress6Map.writeValue failure: %s", strerror(ret.error().code()));
- ret = mClatEgress4Map.deleteValue(txKey);
- if (!ret.ok())
- ALOGE("mClatEgress4Map.deleteValue failure: %s", strerror(ret.error().code()));
- return;
- }
-
- // We do tc setup *after* populating the maps, so scanning through them
- // can always be used to tell us what needs cleanup.
-
- // Usually the clsact will be added in RouteController::addInterfaceToPhysicalNetwork.
- // But clat is started before the v4- interface is added to the network. The clat startup have
- // to add clsact of v4- tun interface first for adding bpf filter in maybeStartBpf.
- // TODO: move "qdisc add clsact" of v4- tun interface out from ClatdController.
- rv = tcQdiscAddDevClsact(tracker.v4ifIndex);
- if (rv) {
- ALOGE("tcQdiscAddDevClsact(%d[%s]) failure: %s", tracker.v4ifIndex, tracker.v4iface,
- strerror(-rv));
- ret = mClatEgress4Map.deleteValue(txKey);
- if (!ret.ok())
- ALOGE("mClatEgress4Map.deleteValue failure: %s", strerror(ret.error().code()));
- ret = mClatIngress6Map.deleteValue(rxKey);
- if (!ret.ok())
- ALOGE("mClatIngress6Map.deleteValue failure: %s", strerror(ret.error().code()));
- return;
- }
-
- rv = tcFilterAddDevEgressClatIpv4(tracker.v4ifIndex, txRawIpProgFd, RAWIP);
- if (rv) {
- ALOGE("tcFilterAddDevEgressClatIpv4(%d[%s], RAWIP) failure: %s", tracker.v4ifIndex,
- tracker.v4iface, strerror(-rv));
-
- // The v4- interface clsact is not deleted for unwinding error because once it is created
- // with interface addition, the lifetime is till interface deletion. Moreover, the clsact
- // has no clat filter now. It should not break anything.
-
- ret = mClatEgress4Map.deleteValue(txKey);
- if (!ret.ok())
- ALOGE("mClatEgress4Map.deleteValue failure: %s", strerror(ret.error().code()));
- ret = mClatIngress6Map.deleteValue(rxKey);
- if (!ret.ok())
- ALOGE("mClatIngress6Map.deleteValue failure: %s", strerror(ret.error().code()));
- return;
- }
-
- rv = tcFilterAddDevIngressClatIpv6(tracker.ifIndex, rxProgFd, isEthernet.value());
- if (rv) {
- ALOGE("tcFilterAddDevIngressClatIpv6(%d[%s], %d) failure: %s", tracker.ifIndex,
- tracker.iface, isEthernet.value(), strerror(-rv));
- rv = tcFilterDelDevEgressClatIpv4(tracker.v4ifIndex);
- if (rv) {
- ALOGE("tcFilterDelDevEgressClatIpv4(%d[%s]) failure: %s", tracker.v4ifIndex,
- tracker.v4iface, strerror(-rv));
- }
-
- // The v4- interface clsact is not deleted. See the reason in the error unwinding code of
- // the egress filter attaching of v4- tun interface.
-
- ret = mClatEgress4Map.deleteValue(txKey);
- if (!ret.ok())
- ALOGE("mClatEgress4Map.deleteValue failure: %s", strerror(ret.error().code()));
- ret = mClatIngress6Map.deleteValue(rxKey);
- if (!ret.ok())
- ALOGE("mClatIngress6Map.deleteValue failure: %s", strerror(ret.error().code()));
- return;
- }
-
- // success
-}
-
-void ClatdController::setIptablesDropRule(bool add, const char* iface, const char* pfx96Str,
- const char* v6Str) {
- std::string cmd = StringPrintf(
- "*raw\n"
- "%s %s -i %s -s %s/96 -d %s -j DROP\n"
- "COMMIT\n",
- (add ? "-A" : "-D"), LOCAL_RAW_PREROUTING, iface, pfx96Str, v6Str);
-
- iptablesRestoreFunction(V6, cmd);
-}
-
-void ClatdController::maybeStopBpf(const ClatdTracker& tracker) {
- int rv = tcFilterDelDevIngressClatIpv6(tracker.ifIndex);
- if (rv < 0) {
- ALOGE("tcFilterDelDevIngressClatIpv6(%d[%s]) failure: %s", tracker.ifIndex, tracker.iface,
- strerror(-rv));
- }
-
- rv = tcFilterDelDevEgressClatIpv4(tracker.v4ifIndex);
- if (rv < 0) {
- ALOGE("tcFilterDelDevEgressClatIpv4(%d[%s]) failure: %s", tracker.v4ifIndex,
- tracker.v4iface, strerror(-rv));
- }
-
- // We cleanup the maps last, so scanning through them can be used to
- // determine what still needs cleanup.
-
- ClatEgress4Key txKey = {
- .iif = tracker.v4ifIndex,
- .local4 = tracker.v4,
- };
-
- auto ret = mClatEgress4Map.deleteValue(txKey);
- if (!ret.ok()) ALOGE("mClatEgress4Map.deleteValue failure: %s", strerror(ret.error().code()));
-
- ClatIngress6Key rxKey = {
- .iif = tracker.ifIndex,
- .pfx96 = tracker.pfx96,
- .local6 = tracker.v6,
- };
-
- ret = mClatIngress6Map.deleteValue(rxKey);
- if (!ret.ok()) ALOGE("mClatIngress6Map.deleteValue failure: %s", strerror(ret.error().code()));
-}
-
-// Finds the tracker of the clatd running on interface |interface|, or nullptr if clatd has not been
-// started on |interface|.
-ClatdController::ClatdTracker* ClatdController::getClatdTracker(const std::string& interface) {
- auto it = mClatdTrackers.find(interface);
- return (it == mClatdTrackers.end() ? nullptr : &it->second);
-}
-
-// Initializes a ClatdTracker for the specified interface.
-int ClatdController::ClatdTracker::init(unsigned networkId, const std::string& interface,
- const std::string& v4interface,
- const std::string& nat64Prefix) {
- fwmark.netId = networkId;
- fwmark.explicitlySelected = true;
- fwmark.protectedFromVpn = true;
- fwmark.permission = PERMISSION_SYSTEM;
-
- snprintf(fwmarkString, sizeof(fwmarkString), "0x%x", fwmark.intValue);
- strlcpy(iface, interface.c_str(), sizeof(iface));
- ifIndex = if_nametoindex(iface);
- strlcpy(v4iface, v4interface.c_str(), sizeof(v4iface));
- v4ifIndex = if_nametoindex(v4iface);
-
- // Pass in everything that clatd needs: interface, a fwmark for outgoing packets, the NAT64
- // prefix, and the IPv4 and IPv6 addresses.
- // Validate the prefix and strip off the prefix length.
- uint8_t family;
- uint8_t prefixLen;
- int res = parsePrefix(nat64Prefix.c_str(), &family, &pfx96, sizeof(pfx96), &prefixLen);
- // clatd only supports /96 prefixes.
- if (res != sizeof(pfx96)) return res;
- if (family != AF_INET6) return -EAFNOSUPPORT;
- if (prefixLen != 96) return -EINVAL;
- if (!inet_ntop(AF_INET6, &pfx96, pfx96String, sizeof(pfx96String))) return -errno;
-
- // Pick an IPv4 address.
- // TODO: this picks the address based on other addresses that are assigned to interfaces, but
- // the address is only actually assigned to an interface once clatd starts up. So we could end
- // up with two clatd instances with the same IPv4 address.
- // Stop doing this and instead pick a free one from the kV4Addr pool.
- v4 = {selectIpv4Address(kV4Addr, kV4AddrLen)};
- if (v4.s_addr == INADDR_NONE) {
- ALOGE("No free IPv4 address in %s/%d", kV4AddrString, kV4AddrLen);
- return -EADDRNOTAVAIL;
- }
- if (!inet_ntop(AF_INET, &v4, v4Str, sizeof(v4Str))) return -errno;
-
- // Generate a checksum-neutral IID.
- if (generateIpv6Address(iface, v4, pfx96, &v6)) {
- ALOGE("Unable to find global source address on %s for %s", iface, pfx96String);
- return -EADDRNOTAVAIL;
- }
- if (!inet_ntop(AF_INET6, &v6, v6Str, sizeof(v6Str))) return -errno;
-
- ALOGD("starting clatd on %s v4=%s v6=%s pfx96=%s", iface, v4Str, v6Str, pfx96String);
- return 0;
-}
-
-/* function: configure_tun_ip
- * configures the ipv4 address on the tunnel interface
- * v4iface - tunnel interface name
- * v4Str - tunnel ipv4 address
- * mtu - mtu of tun device
- * returns: 0 on success, -errno on failure
- */
-int ClatdController::configure_tun_ip(const char* v4iface, const char* v4Str, int mtu) {
- ALOGI("Using IPv4 address %s on %s", v4Str, v4iface);
-
- // Configure the interface before bringing it up. As soon as we bring the interface up, the
- // framework will be notified and will assume the interface's configuration has been finalized.
- std::string mtuStr = std::to_string(mtu);
- if (int res = InterfaceController::setMtu(v4iface, mtuStr.c_str())) {
- ALOGE("setMtu %s failed (%s)", v4iface, strerror(-res));
- return res;
- }
-
- InterfaceConfigurationParcel ifConfig;
- ifConfig.ifName = std::string(v4iface);
- ifConfig.ipv4Addr = std::string(v4Str);
- ifConfig.prefixLength = 32;
- ifConfig.hwAddr = std::string("");
- ifConfig.flags = std::vector<std::string>{std::string(String8(INetd::IF_STATE_UP().string()))};
- const auto& status = InterfaceController::setCfg(ifConfig);
- if (!status.ok()) {
- ALOGE("configure_tun_ip/setCfg failed: %s", strerror(status.code()));
- return -status.code();
- }
-
- return 0;
-}
-
-/* function: add_anycast_address
- * adds an anycast IPv6 address to an interface, returns 0 on success and <0 on failure
- * sock - the socket to add the address to
- * addr - the IP address to add
- * ifindex - index of interface to add the address to
- * returns: 0 on success, -errno on failure
- */
-int ClatdController::add_anycast_address(int sock, struct in6_addr* addr, int ifindex) {
- struct ipv6_mreq mreq = {*addr, ifindex};
- int ret = setsockopt(sock, SOL_IPV6, IPV6_JOIN_ANYCAST, &mreq, sizeof(mreq));
- if (ret) {
- ret = errno;
- ALOGE("setsockopt(IPV6_JOIN_ANYCAST): %s", strerror(errno));
- return -ret;
- }
-
- return 0;
-}
-
-/* function: configure_packet_socket
- * Binds the packet socket and attaches the receive filter to it.
- * sock - the socket to configure
- * addr - the IP address to filter
- * ifindex - index of interface to add the filter to
- * returns: 0 on success, -errno on failure
- */
-int ClatdController::configure_packet_socket(int sock, in6_addr* addr, int ifindex) {
- uint32_t* ipv6 = addr->s6_addr32;
-
- // clang-format off
- struct sock_filter filter_code[] = {
- // Load the first four bytes of the IPv6 destination address (starts 24 bytes in).
- // Compare it against the first four bytes of our IPv6 address, in host byte order (BPF loads
- // are always in host byte order). If it matches, continue with next instruction (JMP 0). If it
- // doesn't match, jump ahead to statement that returns 0 (ignore packet). Repeat for the other
- // three words of the IPv6 address, and if they all match, return PACKETLEN (accept packet).
- BPF_STMT(BPF_LD | BPF_W | BPF_ABS, 24),
- BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htonl(ipv6[0]), 0, 7),
- BPF_STMT(BPF_LD | BPF_W | BPF_ABS, 28),
- BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htonl(ipv6[1]), 0, 5),
- BPF_STMT(BPF_LD | BPF_W | BPF_ABS, 32),
- BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htonl(ipv6[2]), 0, 3),
- BPF_STMT(BPF_LD | BPF_W | BPF_ABS, 36),
- BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htonl(ipv6[3]), 0, 1),
- BPF_STMT(BPF_RET | BPF_K, PACKETLEN),
- BPF_STMT(BPF_RET | BPF_K, 0),
- };
- // clang-format on
- struct sock_fprog filter = {sizeof(filter_code) / sizeof(filter_code[0]), filter_code};
-
- if (setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter))) {
- int res = errno;
- ALOGE("attach packet filter failed: %s", strerror(errno));
- return -res;
- }
-
- struct sockaddr_ll sll = {
- .sll_family = AF_PACKET,
- .sll_protocol = htons(ETH_P_IPV6),
- .sll_ifindex = ifindex,
- .sll_pkttype =
- PACKET_OTHERHOST, // The 464xlat IPv6 address is not assigned to the kernel.
- };
- if (bind(sock, (struct sockaddr*)&sll, sizeof(sll))) {
- int res = errno;
- ALOGE("binding packet socket: %s", strerror(errno));
- return -res;
- }
-
- return 0;
-}
-
-/* function: configure_clat_ipv6_address
- * picks the clat IPv6 address and configures packet translation to use it.
- * tunnel - tun device data
- * interface - uplink interface name
- * returns: 0 on success, -errno on failure
- */
-int ClatdController::configure_clat_ipv6_address(struct ClatdTracker* tracker,
- struct tun_data* tunnel) {
- ALOGI("Using IPv6 address %s on %s", tracker->v6Str, tracker->iface);
-
- // Start translating packets to the new prefix.
- // TODO: return if error. b/212679140 needs to be fixed first.
- add_anycast_address(tunnel->write_fd6, &tracker->v6, tracker->ifIndex);
-
- // Update our packet socket filter to reflect the new 464xlat IP address.
- if (int res = configure_packet_socket(tunnel->read_fd6, &tracker->v6, tracker->ifIndex)) {
- // Things aren't going to work. Bail out and hope we have better luck next time.
- // We don't log an error here because configure_packet_socket has already done so.
- return res;
- }
-
- return 0;
-}
-
-/* function: detect mtu
- * returns: mtu on success, -errno on failure
- */
-int ClatdController::detect_mtu(const struct in6_addr* plat_subnet, uint32_t plat_suffix,
- uint32_t mark) {
- // Create an IPv6 UDP socket.
- unique_fd s(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
- if (s < 0) {
- int ret = errno;
- ALOGE("socket(AF_INET6, SOCK_DGRAM, 0) failed: %s", strerror(errno));
- return -ret;
- }
-
- // Socket's mark affects routing decisions (network selection)
- if ((mark != MARK_UNSET) && setsockopt(s, SOL_SOCKET, SO_MARK, &mark, sizeof(mark))) {
- int ret = errno;
- ALOGE("setsockopt(SOL_SOCKET, SO_MARK) failed: %s", strerror(errno));
- return -ret;
- }
-
- // Try to connect udp socket to plat_subnet(96 bits):plat_suffix(32 bits)
- struct sockaddr_in6 dst = {
- .sin6_family = AF_INET6,
- .sin6_addr = *plat_subnet,
- };
- dst.sin6_addr.s6_addr32[3] = plat_suffix;
- if (connect(s, (struct sockaddr*)&dst, sizeof(dst))) {
- int ret = errno;
- ALOGE("connect() failed: %s", strerror(errno));
- return -ret;
- }
-
- // Fetch the socket's IPv6 mtu - this is effectively fetching mtu from routing table
- int mtu;
- socklen_t sz_mtu = sizeof(mtu);
- if (getsockopt(s, SOL_IPV6, IPV6_MTU, &mtu, &sz_mtu)) {
- int ret = errno;
- ALOGE("getsockopt(SOL_IPV6, IPV6_MTU) failed: %s", strerror(errno));
- return -ret;
- }
- if (sz_mtu != sizeof(mtu)) {
- ALOGE("getsockopt(SOL_IPV6, IPV6_MTU) returned unexpected size: %d", sz_mtu);
- return -EFAULT;
- }
-
- return mtu;
-}
-
-/* function: configure_interface
- * reads the configuration and applies it to the interface
- * tracker - clat tracker
- * tunnel - tun device data
- * returns: 0 on success, -errno on failure
- */
-int ClatdController::configure_interface(struct ClatdTracker* tracker, struct tun_data* tunnel) {
- int res = detect_mtu(&tracker->pfx96, htonl(0x08080808), tracker->fwmark.intValue);
- if (res < 0) return -res;
-
- int mtu = res;
- // clamp to minimum ipv6 mtu - this probably cannot ever trigger
- if (mtu < 1280) mtu = 1280;
- // clamp to buffer size
- if (mtu > MAXMTU) mtu = MAXMTU;
- // decrease by ipv6(40) + ipv6 fragmentation header(8) vs ipv4(20) overhead of 28 bytes
- mtu -= MTU_DELTA;
- ALOGI("ipv4 mtu is %d", mtu);
-
- if (int ret = configure_tun_ip(tracker->v4iface, tracker->v4Str, mtu)) return ret;
- if (int ret = configure_clat_ipv6_address(tracker, tunnel)) return ret;
-
- return 0;
-}
-
-int ClatdController::startClatd(const std::string& interface, const std::string& nat64Prefix,
- std::string* v6Str) {
- std::lock_guard guard(mutex);
-
- // 1. fail if pre-existing tracker already exists
- ClatdTracker* existing = getClatdTracker(interface);
- if (existing != nullptr) {
- ALOGE("clatd pid=%d already started on %s", existing->pid, interface.c_str());
- return -EBUSY;
- }
-
- // 2. get network id associated with this external interface
- unsigned networkId = mNetCtrl->getNetworkForInterface(interface.c_str());
- if (networkId == NETID_UNSET) {
- ALOGE("Interface %s not assigned to any netId", interface.c_str());
- return -ENODEV;
- }
-
- // 3. open the tun device in non blocking mode as required by clatd
- int res = open("/dev/net/tun", O_RDWR | O_NONBLOCK | O_CLOEXEC);
- if (res == -1) {
- res = errno;
- ALOGE("open of tun device failed (%s)", strerror(res));
- return -res;
- }
- unique_fd tmpTunFd(res);
-
- // 4. create the v4-... tun interface
- std::string v4interface("v4-");
- v4interface += interface;
-
- struct ifreq ifr = {
- .ifr_flags = IFF_TUN,
- };
- strlcpy(ifr.ifr_name, v4interface.c_str(), sizeof(ifr.ifr_name));
-
- res = ioctl(tmpTunFd, TUNSETIFF, &ifr, sizeof(ifr));
- if (res == -1) {
- res = errno;
- ALOGE("ioctl(TUNSETIFF) failed (%s)", strerror(res));
- return -res;
- }
-
- // disable IPv6 on it - failing to do so is not a critical error
- res = InterfaceController::setEnableIPv6(v4interface.c_str(), 0);
- if (res) ALOGE("setEnableIPv6 %s failed (%s)", v4interface.c_str(), strerror(res));
-
- // 5. initialize tracker object
- ClatdTracker tracker;
- int ret = tracker.init(networkId, interface, v4interface, nat64Prefix);
- if (ret) return ret;
-
- // 6. create a throwaway socket to reserve a file descriptor number
- res = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0);
- if (res == -1) {
- res = errno;
- ALOGE("socket(ipv6/udp) failed (%s)", strerror(res));
- return -res;
- }
- unique_fd passedTunFd(res);
-
- // 7. this is the FD we'll pass to clatd on the cli, so need it as a string
- char passedTunFdStr[INT32_STRLEN];
- snprintf(passedTunFdStr, sizeof(passedTunFdStr), "%d", passedTunFd.get());
-
- // 8. create a raw socket for clatd sending packets to the tunnel
- res = socket(AF_INET6, SOCK_RAW | SOCK_NONBLOCK | SOCK_CLOEXEC, IPPROTO_RAW);
- if (res < 0) {
- res = errno;
- ALOGE("raw socket failed: %s", strerror(errno));
- return -res;
- }
- unique_fd tmpRawSock(res);
-
- const int mark = tracker.fwmark.intValue;
- if (mark != MARK_UNSET &&
- setsockopt(tmpRawSock, SOL_SOCKET, SO_MARK, &mark, sizeof(mark)) < 0) {
- res = errno;
- ALOGE("could not set mark on raw socket: %s", strerror(errno));
- return -res;
- }
-
- // create a throwaway socket to reserve a file descriptor number
- res = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0);
- if (res == -1) {
- res = errno;
- ALOGE("socket(ipv6/udp) failed (%s) for raw socket", strerror(res));
- return -res;
- }
- unique_fd passedRawSock(res);
-
- // this is the raw socket FD we'll pass to clatd on the cli, so need it as a string
- char passedRawSockStr[INT32_STRLEN];
- snprintf(passedRawSockStr, sizeof(passedRawSockStr), "%d", passedRawSock.get());
-
- // 9. create a packet socket for clatd sending packets to the tunnel
- // Will eventually be bound to htons(ETH_P_IPV6) protocol,
- // but only after appropriate bpf filter is attached.
- res = socket(AF_PACKET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
- if (res < 0) {
- res = errno;
- ALOGE("packet socket failed: %s", strerror(errno));
- return -res;
- }
- unique_fd tmpPacketSock(res);
-
- // create a throwaway socket to reserve a file descriptor number
- res = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0);
- if (res == -1) {
- res = errno;
- ALOGE("socket(ipv6/udp) failed (%s) for packet socket", strerror(res));
- return -res;
- }
- unique_fd passedPacketSock(res);
-
- // this is the packet socket FD we'll pass to clatd on the cli, so need it as a string
- char passedPacketSockStr[INT32_STRLEN];
- snprintf(passedPacketSockStr, sizeof(passedPacketSock), "%d", passedPacketSock.get());
-
- // 10. configure tun and clat interface
- struct tun_data tunnel = {.fd4 = tmpTunFd, .read_fd6 = tmpPacketSock, .write_fd6 = tmpRawSock};
- res = configure_interface(&tracker, &tunnel);
- if (res) {
- ALOGE("configure interface failed: %s", strerror(res));
- return -res;
- }
-
- // 11. we're going to use this as argv[0] to clatd to make ps output more useful
- std::string progname("clatd-");
- progname += tracker.iface;
-
- // clang-format off
- const char* args[] = {progname.c_str(),
- "-i", tracker.iface,
- "-p", tracker.pfx96String,
- "-4", tracker.v4Str,
- "-6", tracker.v6Str,
- "-t", passedTunFdStr,
- "-r", passedPacketSockStr,
- "-w", passedRawSockStr,
- nullptr};
- // clang-format on
-
- // 12. register vfork requirement
- posix_spawnattr_t attr;
- res = posix_spawnattr_init(&attr);
- if (res) {
- ALOGE("posix_spawnattr_init failed (%s)", strerror(res));
- return -res;
- }
- const android::base::ScopeGuard attrGuard = [&] { posix_spawnattr_destroy(&attr); };
- res = posix_spawnattr_setflags(&attr, POSIX_SPAWN_USEVFORK);
- if (res) {
- ALOGE("posix_spawnattr_setflags failed (%s)", strerror(res));
- return -res;
- }
-
- // 13. register dup2() action: this is what 'clears' the CLOEXEC flag
- // on the tun fd that we want the child clatd process to inherit
- // (this will happen after the vfork, and before the execve)
- posix_spawn_file_actions_t fa;
- res = posix_spawn_file_actions_init(&fa);
- if (res) {
- ALOGE("posix_spawn_file_actions_init failed (%s)", strerror(res));
- return -res;
- }
- const android::base::ScopeGuard faGuard = [&] { posix_spawn_file_actions_destroy(&fa); };
- res = posix_spawn_file_actions_adddup2(&fa, tmpTunFd, passedTunFd);
- if (res) {
- ALOGE("posix_spawn_file_actions_adddup2 tun fd failed (%s)", strerror(res));
- return -res;
- }
- res = posix_spawn_file_actions_adddup2(&fa, tmpPacketSock, passedPacketSock);
- if (res) {
- ALOGE("posix_spawn_file_actions_adddup2 packet socket failed (%s)", strerror(res));
- return -res;
- }
- res = posix_spawn_file_actions_adddup2(&fa, tmpRawSock, passedRawSock);
- if (res) {
- ALOGE("posix_spawn_file_actions_adddup2 raw socket failed (%s)", strerror(res));
- return -res;
- }
-
- // 14. add the drop rule for iptables.
- setIptablesDropRule(true, tracker.iface, tracker.pfx96String, tracker.v6Str);
-
- // 15. actually perform vfork/dup2/execve
- res = posix_spawn(&tracker.pid, kClatdPath, &fa, &attr, (char* const*)args, nullptr);
- if (res) {
- ALOGE("posix_spawn failed (%s)", strerror(res));
- return -res;
- }
-
- // 16. configure eBPF offload - if possible
- maybeStartBpf(tracker);
-
- mClatdTrackers[interface] = tracker;
- ALOGD("clatd started on %s", interface.c_str());
-
- *v6Str = tracker.v6Str;
- return 0;
-}
-
-int ClatdController::stopClatd(const std::string& interface) {
- std::lock_guard guard(mutex);
- ClatdTracker* tracker = getClatdTracker(interface);
-
- if (tracker == nullptr) {
- ALOGE("clatd already stopped");
- return -ENODEV;
- }
-
- ALOGD("Stopping clatd pid=%d on %s", tracker->pid, interface.c_str());
-
- maybeStopBpf(*tracker);
-
- ::stopProcess(tracker->pid, "clatd");
-
- setIptablesDropRule(false, tracker->iface, tracker->pfx96String, tracker->v6Str);
- mClatdTrackers.erase(interface);
-
- ALOGD("clatd on %s stopped", interface.c_str());
-
- return 0;
-}
-
-void ClatdController::dumpEgress(DumpWriter& dw) {
- if (!mClatEgress4Map.isValid()) return; // if unsupported just don't dump anything
-
- ScopedIndent bpfIndent(dw);
- dw.println("BPF egress map: iif(iface) v4Addr -> v6Addr nat64Prefix oif(iface)");
-
- ScopedIndent bpfDetailIndent(dw);
- const auto printClatMap = [&dw](const ClatEgress4Key& key, const ClatEgress4Value& value,
- const BpfMap<ClatEgress4Key, ClatEgress4Value>&) {
- char iifStr[IFNAMSIZ] = "?";
- char local4Str[INET_ADDRSTRLEN] = "?";
- char local6Str[INET6_ADDRSTRLEN] = "?";
- char pfx96Str[INET6_ADDRSTRLEN] = "?";
- char oifStr[IFNAMSIZ] = "?";
-
- if_indextoname(key.iif, iifStr);
- inet_ntop(AF_INET, &key.local4, local4Str, sizeof(local4Str));
- inet_ntop(AF_INET6, &value.local6, local6Str, sizeof(local6Str));
- inet_ntop(AF_INET6, &value.pfx96, pfx96Str, sizeof(pfx96Str));
- if_indextoname(value.oif, oifStr);
-
- dw.println("%u(%s) %s -> %s %s/96 %u(%s) %s", key.iif, iifStr, local4Str, local6Str,
- pfx96Str, value.oif, oifStr, value.oifIsEthernet ? "ether" : "rawip");
- return Result<void>();
- };
- auto res = mClatEgress4Map.iterateWithValue(printClatMap);
- if (!res.ok()) {
- dw.println("Error printing BPF map: %s", res.error().message().c_str());
- }
-}
-
-void ClatdController::dumpIngress(DumpWriter& dw) {
- if (!mClatIngress6Map.isValid()) return; // if unsupported just don't dump anything
-
- ScopedIndent bpfIndent(dw);
- dw.println("BPF ingress map: iif(iface) nat64Prefix v6Addr -> v4Addr oif(iface)");
-
- ScopedIndent bpfDetailIndent(dw);
- const auto printClatMap = [&dw](const ClatIngress6Key& key, const ClatIngress6Value& value,
- const BpfMap<ClatIngress6Key, ClatIngress6Value>&) {
- char iifStr[IFNAMSIZ] = "?";
- char pfx96Str[INET6_ADDRSTRLEN] = "?";
- char local6Str[INET6_ADDRSTRLEN] = "?";
- char local4Str[INET_ADDRSTRLEN] = "?";
- char oifStr[IFNAMSIZ] = "?";
-
- if_indextoname(key.iif, iifStr);
- inet_ntop(AF_INET6, &key.pfx96, pfx96Str, sizeof(pfx96Str));
- inet_ntop(AF_INET6, &key.local6, local6Str, sizeof(local6Str));
- inet_ntop(AF_INET, &value.local4, local4Str, sizeof(local4Str));
- if_indextoname(value.oif, oifStr);
-
- dw.println("%u(%s) %s/96 %s -> %s %u(%s)", key.iif, iifStr, pfx96Str, local6Str, local4Str,
- value.oif, oifStr);
- return Result<void>();
- };
- auto res = mClatIngress6Map.iterateWithValue(printClatMap);
- if (!res.ok()) {
- dw.println("Error printing BPF map: %s", res.error().message().c_str());
- }
-}
-
-void ClatdController::dumpTrackers(DumpWriter& dw) {
- ScopedIndent trackerIndent(dw);
- dw.println("Trackers: iif[iface] nat64Prefix v6Addr -> v4Addr v4iif[v4iface] [fwmark]");
-
- ScopedIndent trackerDetailIndent(dw);
- for (const auto& pair : mClatdTrackers) {
- const ClatdTracker& tracker = pair.second;
- dw.println("%u[%s] %s/96 %s -> %s %u[%s] [%s]", tracker.ifIndex, tracker.iface,
- tracker.pfx96String, tracker.v6Str, tracker.v4Str, tracker.v4ifIndex,
- tracker.v4iface, tracker.fwmarkString);
- }
-}
-
-void ClatdController::dump(DumpWriter& dw) {
- std::lock_guard guard(mutex);
-
- ScopedIndent clatdIndent(dw);
- dw.println("ClatdController");
-
- dumpTrackers(dw);
- dumpIngress(dw);
- dumpEgress(dw);
-}
-
-auto ClatdController::isIpv4AddressFreeFunc = isIpv4AddressFree;
-auto ClatdController::iptablesRestoreFunction = execIptablesRestore;
-
-} // namespace net
-} // namespace android
diff --git a/server/ClatdController.h b/server/ClatdController.h
deleted file mode 100644
index 04694705..00000000
--- a/server/ClatdController.h
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _CLATD_CONTROLLER_H
-#define _CLATD_CONTROLLER_H
-
-#include <map>
-#include <mutex>
-#include <string>
-
-#include <linux/if.h>
-#include <netinet/in.h>
-
-#include <android-base/thread_annotations.h>
-
-#include "Fwmark.h"
-#include "NetdConstants.h"
-#include "bpf/BpfMap.h"
-#include "bpf_shared.h"
-#include "netdutils/DumpWriter.h"
-
-namespace android {
-namespace net {
-
-class NetworkController;
-
-class ClatdController {
- public:
- explicit ClatdController(NetworkController* controller) EXCLUDES(mutex)
- : mNetCtrl(controller){};
- virtual ~ClatdController() EXCLUDES(mutex){};
-
- /* First thing init/startClatd/stopClatd/dump do is grab the mutex. */
- void init(void) EXCLUDES(mutex);
-
- int startClatd(const std::string& interface, const std::string& nat64Prefix,
- std::string* v6Addr) EXCLUDES(mutex);
- int stopClatd(const std::string& interface) EXCLUDES(mutex);
-
- void dump(netdutils::DumpWriter& dw) EXCLUDES(mutex);
-
- static constexpr const char LOCAL_RAW_PREROUTING[] = "clat_raw_PREROUTING";
-
- // Public struct ClatdTracker and tun_data for testing. gtest/TEST_F macro changes the class
- // name. In TEST_F(ClatdControllerTest..), can't access struct ClatdTracker and tun_data.
- // TODO: probably use gtest/FRIEND_TEST macro.
- struct ClatdTracker {
- pid_t pid = -1;
- unsigned ifIndex;
- char iface[IFNAMSIZ];
- unsigned v4ifIndex;
- char v4iface[IFNAMSIZ];
- Fwmark fwmark;
- char fwmarkString[UINT32_STRLEN];
- in_addr v4;
- char v4Str[INET_ADDRSTRLEN];
- in6_addr v6;
- char v6Str[INET6_ADDRSTRLEN];
- in6_addr pfx96;
- char pfx96String[INET6_ADDRSTRLEN];
-
- int init(unsigned networkId, const std::string& interface, const std::string& v4interface,
- const std::string& nat64Prefix);
- };
-
- // Public for testing. See above reason in struct ClatdTracker.
- struct tun_data {
- int read_fd6, write_fd6, fd4;
- };
-
- private:
- std::mutex mutex;
-
- const NetworkController* mNetCtrl GUARDED_BY(mutex);
- std::map<std::string, ClatdTracker> mClatdTrackers GUARDED_BY(mutex);
- ClatdTracker* getClatdTracker(const std::string& interface) REQUIRES(mutex);
-
- void dumpEgress(netdutils::DumpWriter& dw) REQUIRES(mutex);
- void dumpIngress(netdutils::DumpWriter& dw) REQUIRES(mutex);
- void dumpTrackers(netdutils::DumpWriter& dw) REQUIRES(mutex);
-
- static in_addr_t selectIpv4Address(const in_addr ip, int16_t prefixlen);
- static int generateIpv6Address(const char* iface, const in_addr v4, const in6_addr& nat64Prefix,
- in6_addr* v6);
- static void makeChecksumNeutral(in6_addr* v6, const in_addr v4, const in6_addr& nat64Prefix);
-
- bpf::BpfMap<ClatEgress4Key, ClatEgress4Value> mClatEgress4Map GUARDED_BY(mutex);
- bpf::BpfMap<ClatIngress6Key, ClatIngress6Value> mClatIngress6Map GUARDED_BY(mutex);
-
- void maybeStartBpf(const ClatdTracker& tracker) REQUIRES(mutex);
- void maybeStopBpf(const ClatdTracker& tracker) REQUIRES(mutex);
- void setIptablesDropRule(bool add, const char* iface, const char* pfx96Str, const char* v6Str)
- REQUIRES(mutex);
-
- int detect_mtu(const struct in6_addr* plat_subnet, uint32_t plat_suffix, uint32_t mark);
- int configure_interface(struct ClatdTracker* tracker, struct tun_data* tunnel) REQUIRES(mutex);
- int configure_tun_ip(const char* v4iface, const char* v4Str, int mtu) REQUIRES(mutex);
- int configure_clat_ipv6_address(struct ClatdTracker* tracker, struct tun_data* tunnel)
- REQUIRES(mutex);
- int add_anycast_address(int sock, struct in6_addr* addr, int ifindex) REQUIRES(mutex);
- int configure_packet_socket(int sock, in6_addr* addr, int ifindex) REQUIRES(mutex);
-
- // For testing.
- friend class ClatdControllerTest;
-
- static bool (*isIpv4AddressFreeFunc)(in_addr_t);
- static bool isIpv4AddressFree(in_addr_t addr);
- static int (*iptablesRestoreFunction)(IptablesTarget target, const std::string& commands);
-};
-
-} // namespace net
-} // namespace android
-
-#endif
diff --git a/server/ClatdControllerTest.cpp b/server/ClatdControllerTest.cpp
deleted file mode 100644
index 2c904df4..00000000
--- a/server/ClatdControllerTest.cpp
+++ /dev/null
@@ -1,323 +0,0 @@
-/*
- * Copyright 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * ClatdControllerTest.cpp - unit tests for ClatdController.cpp
- */
-
-#include <arpa/inet.h>
-#include <netinet/in.h>
-#include <string>
-
-#include <gtest/gtest.h>
-
-#include <android-base/stringprintf.h>
-#include <android-base/strings.h>
-#include <linux/if_packet.h>
-#include <netutils/ifc.h>
-
-extern "C" {
-#include <checksum.h>
-}
-
-#include "ClatdController.h"
-#include "IptablesBaseTest.h"
-#include "NetworkController.h"
-#include "tun_interface.h"
-
-static const char kIPv4LocalAddr[] = "192.0.0.4";
-
-namespace android {
-namespace net {
-
-using android::base::StringPrintf;
-using android::net::TunInterface;
-
-// Mock functions for isIpv4AddressFree.
-bool neverFree(in_addr_t /* addr */) {
- return 0;
-}
-bool alwaysFree(in_addr_t /* addr */) {
- return 1;
-}
-bool only2Free(in_addr_t addr) {
- return (ntohl(addr) & 0xff) == 2;
-}
-bool over6Free(in_addr_t addr) {
- return (ntohl(addr) & 0xff) >= 6;
-}
-bool only10Free(in_addr_t addr) {
- return (ntohl(addr) & 0xff) == 10;
-}
-
-class ClatdControllerTest : public IptablesBaseTest {
- public:
- ClatdControllerTest() : mClatdCtrl(nullptr) {
- ClatdController::iptablesRestoreFunction = fakeExecIptablesRestore;
- }
-
- void SetUp() { resetIpv4AddressFreeFunc(); }
-
- protected:
- ClatdController mClatdCtrl;
- void setIptablesDropRule(bool a, const char* b, const char* c, const char* d) {
- std::lock_guard guard(mClatdCtrl.mutex);
- return mClatdCtrl.setIptablesDropRule(a, b, c, d);
- }
- void setIpv4AddressFreeFunc(bool (*func)(in_addr_t)) {
- ClatdController::isIpv4AddressFreeFunc = func;
- }
- void resetIpv4AddressFreeFunc() {
- ClatdController::isIpv4AddressFreeFunc = ClatdController::isIpv4AddressFree;
- }
- in_addr_t selectIpv4Address(const in_addr a, int16_t b) {
- return ClatdController::selectIpv4Address(a, b);
- }
- void makeChecksumNeutral(in6_addr* a, const in_addr b, const in6_addr& c) {
- ClatdController::makeChecksumNeutral(a, b, c);
- }
- int detect_mtu(const struct in6_addr* a, uint32_t b, uint32_t c) {
- return mClatdCtrl.detect_mtu(a, b, c);
- }
- int configure_tun_ip(const char* a, const char* b, int c) {
- std::lock_guard guard(mClatdCtrl.mutex);
- return mClatdCtrl.configure_tun_ip(a, b, c);
- }
- int configure_clat_ipv6_address(ClatdController::ClatdTracker* a,
- ClatdController::tun_data* b) {
- std::lock_guard guard(mClatdCtrl.mutex);
- return mClatdCtrl.configure_clat_ipv6_address(a, b);
- }
-};
-
-TEST_F(ClatdControllerTest, SelectIpv4Address) {
- struct in_addr addr;
-
- inet_pton(AF_INET, kIPv4LocalAddr, &addr);
-
- // If no addresses are free, return INADDR_NONE.
- setIpv4AddressFreeFunc(neverFree);
- EXPECT_EQ(INADDR_NONE, selectIpv4Address(addr, 29));
- EXPECT_EQ(INADDR_NONE, selectIpv4Address(addr, 16));
-
- // If the configured address is free, pick that. But a prefix that's too big is invalid.
- setIpv4AddressFreeFunc(alwaysFree);
- EXPECT_EQ(inet_addr(kIPv4LocalAddr), selectIpv4Address(addr, 29));
- EXPECT_EQ(inet_addr(kIPv4LocalAddr), selectIpv4Address(addr, 20));
- EXPECT_EQ(INADDR_NONE, selectIpv4Address(addr, 15));
-
- // A prefix length of 32 works, but anything above it is invalid.
- EXPECT_EQ(inet_addr(kIPv4LocalAddr), selectIpv4Address(addr, 32));
- EXPECT_EQ(INADDR_NONE, selectIpv4Address(addr, 33));
-
- // If another address is free, pick it.
- setIpv4AddressFreeFunc(over6Free);
- EXPECT_EQ(inet_addr("192.0.0.6"), selectIpv4Address(addr, 29));
-
- // Check that we wrap around to addresses that are lower than the first address.
- setIpv4AddressFreeFunc(only2Free);
- EXPECT_EQ(inet_addr("192.0.0.2"), selectIpv4Address(addr, 29));
- EXPECT_EQ(INADDR_NONE, selectIpv4Address(addr, 30));
-
- // If a free address exists outside the prefix, we don't pick it.
- setIpv4AddressFreeFunc(only10Free);
- EXPECT_EQ(INADDR_NONE, selectIpv4Address(addr, 29));
- EXPECT_EQ(inet_addr("192.0.0.10"), selectIpv4Address(addr, 24));
-
- // Now try using the real function which sees if IP addresses are free using bind().
- // Assume that the machine running the test has the address 127.0.0.1, but not 8.8.8.8.
- resetIpv4AddressFreeFunc();
- addr.s_addr = inet_addr("8.8.8.8");
- EXPECT_EQ(inet_addr("8.8.8.8"), selectIpv4Address(addr, 29));
-
- addr.s_addr = inet_addr("127.0.0.1");
- EXPECT_EQ(inet_addr("127.0.0.2"), selectIpv4Address(addr, 29));
-}
-
-TEST_F(ClatdControllerTest, MakeChecksumNeutral) {
- // We can't test generateIPv6Address here since it requires manipulating routing, which we can't
- // do without talking to the real netd on the system.
- uint32_t rand = arc4random_uniform(0xffffffff);
- uint16_t rand1 = rand & 0xffff;
- uint16_t rand2 = (rand >> 16) & 0xffff;
- std::string v6PrefixStr = StringPrintf("2001:db8:%x:%x", rand1, rand2);
- std::string v6InterfaceAddrStr = StringPrintf("%s::%x:%x", v6PrefixStr.c_str(), rand2, rand1);
- std::string nat64PrefixStr = StringPrintf("2001:db8:%x:%x::", rand2, rand1);
-
- in_addr v4 = {inet_addr(kIPv4LocalAddr)};
- in6_addr v6InterfaceAddr;
- ASSERT_TRUE(inet_pton(AF_INET6, v6InterfaceAddrStr.c_str(), &v6InterfaceAddr));
- in6_addr nat64Prefix;
- ASSERT_TRUE(inet_pton(AF_INET6, nat64PrefixStr.c_str(), &nat64Prefix));
-
- // Generate a boatload of random IIDs.
- int onebits = 0;
- uint64_t prev_iid = 0;
- for (int i = 0; i < 100000; i++) {
- in6_addr v6 = v6InterfaceAddr;
- makeChecksumNeutral(&v6, v4, nat64Prefix);
-
- // Check the generated IP address is in the same prefix as the interface IPv6 address.
- EXPECT_EQ(0, memcmp(&v6, &v6InterfaceAddr, 8));
-
- // Check that consecutive IIDs are not the same.
- uint64_t iid = *(uint64_t*)(&v6.s6_addr[8]);
- ASSERT_TRUE(iid != prev_iid)
- << "Two consecutive random IIDs are the same: " << std::showbase << std::hex << iid
- << "\n";
- prev_iid = iid;
-
- // Check that the IID is checksum-neutral with the NAT64 prefix and the
- // local prefix.
- uint16_t c1 = ip_checksum_finish(ip_checksum_add(0, &v4, sizeof(v4)));
- uint16_t c2 = ip_checksum_finish(ip_checksum_add(0, &nat64Prefix, sizeof(nat64Prefix)) +
- ip_checksum_add(0, &v6, sizeof(v6)));
-
- if (c1 != c2) {
- char v6Str[INET6_ADDRSTRLEN];
- inet_ntop(AF_INET6, &v6, v6Str, sizeof(v6Str));
- FAIL() << "Bad IID: " << v6Str << " not checksum-neutral with " << kIPv4LocalAddr
- << " and " << nat64PrefixStr.c_str() << std::showbase << std::hex
- << "\n IPv4 checksum: " << c1 << "\n IPv6 checksum: " << c2 << "\n";
- }
-
- // Check that IIDs are roughly random and use all the bits by counting the
- // total number of bits set to 1 in a random sample of 100000 generated IIDs.
- onebits += __builtin_popcountll(*(uint64_t*)&iid);
- }
- EXPECT_LE(3190000, onebits);
- EXPECT_GE(3210000, onebits);
-}
-
-TEST_F(ClatdControllerTest, AddIptablesRule) {
- setIptablesDropRule(true, "wlan0", "64:ff9b::", "2001:db8::1:2:3:4");
- expectIptablesRestoreCommands((ExpectedIptablesCommands){
- {V6,
- "*raw\n"
- "-A clat_raw_PREROUTING -i wlan0 -s 64:ff9b::/96 -d 2001:db8::1:2:3:4 -j DROP\n"
- "COMMIT\n"}});
-}
-
-TEST_F(ClatdControllerTest, RemoveIptablesRule) {
- setIptablesDropRule(false, "wlan0", "64:ff9b::", "2001:db8::a:b:c:d");
- expectIptablesRestoreCommands((ExpectedIptablesCommands){
- {V6,
- "*raw\n"
- "-D clat_raw_PREROUTING -i wlan0 -s 64:ff9b::/96 -d 2001:db8::a:b:c:d -j DROP\n"
- "COMMIT\n"}});
-}
-
-TEST_F(ClatdControllerTest, DetectMtu) {
- // ::1 with bottom 32 bits set to 1 is still ::1 which routes via lo with mtu of 64KiB
- ASSERT_EQ(detect_mtu(&in6addr_loopback, htonl(1), 0 /*MARK_UNSET*/), 65536);
-}
-
-// Get the first IPv4 address for a given interface name
-in_addr* getinterface_ip(const char* interface) {
- ifaddrs *ifaddr, *ifa;
- in_addr* retval = nullptr;
-
- if (getifaddrs(&ifaddr) == -1) return nullptr;
-
- for (ifa = ifaddr; ifa != nullptr; ifa = ifa->ifa_next) {
- if (ifa->ifa_addr == nullptr) continue;
-
- if ((strcmp(ifa->ifa_name, interface) == 0) && (ifa->ifa_addr->sa_family == AF_INET)) {
- retval = (in_addr*)malloc(sizeof(in_addr));
- if (retval) {
- const sockaddr_in* sin = reinterpret_cast<sockaddr_in*>(ifa->ifa_addr);
- *retval = sin->sin_addr;
- }
- break;
- }
- }
-
- freeifaddrs(ifaddr);
- return retval;
-}
-
-TEST_F(ClatdControllerTest, ConfigureTunIpManual) {
- // Create an interface for configure_tun_ip to configure and bring up.
- TunInterface v4Iface;
- ASSERT_EQ(0, v4Iface.init());
-
- configure_tun_ip(v4Iface.name().c_str(), "192.0.2.1" /* v4Str */, 1472 /* mtu */);
- in_addr* ip = getinterface_ip(v4Iface.name().c_str());
- ASSERT_NE(nullptr, ip);
- EXPECT_EQ(inet_addr("192.0.2.1"), ip->s_addr);
- free(ip);
-
- v4Iface.destroy();
-}
-
-ClatdController::tun_data makeTunData() {
- // Create some fake but realistic-looking sockets so configure_clat_ipv6_address doesn't balk.
- return {
- .read_fd6 = socket(AF_PACKET, SOCK_DGRAM | SOCK_CLOEXEC, htons(ETH_P_IPV6)),
- .write_fd6 = socket(AF_INET6, SOCK_RAW | SOCK_NONBLOCK | SOCK_CLOEXEC, IPPROTO_RAW),
- .fd4 = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0),
- };
-}
-
-void cleanupTunData(ClatdController::tun_data* tunnel) {
- close(tunnel->write_fd6);
- close(tunnel->read_fd6);
- close(tunnel->fd4);
-}
-
-TEST_F(ClatdControllerTest, ConfigureIpv6Address) {
- // Create an interface for configure_clat_ipv6_address to attach socket filter to.
- TunInterface v6Iface;
- ASSERT_EQ(0, v6Iface.init());
- ClatdController::tun_data tunnel = makeTunData();
-
- // Only initialize valid value to configure_clat_ipv6_address() required fields
- // {ifIndex, v6, v6Str}. The uninitialized fields have initialized with invalid
- // value just in case.
- ClatdController::ClatdTracker tracker = {
- .pid = -1, // unused
- .ifIndex = 0, // initialize later
- .iface = "", // unused
- .v4ifIndex = 0, // unused
- .v4iface = "", // unused
- .fwmark.intValue = 0, // unused
- .fwmarkString = "0x0", // unused
- .v4 = {}, // unused
- .v4Str = "", // unused
- .v6 = {}, // initialize later
- .v6Str = "", // initialize later
- .pfx96 = {}, // unused
- .pfx96String = "", // unused
- };
- tracker.ifIndex = static_cast<unsigned int>(v6Iface.ifindex());
- const char* addrStr = "2001:db8::f00";
- ASSERT_EQ(1, inet_pton(AF_INET6, addrStr, &tracker.v6));
- strlcpy(tracker.v6Str, addrStr, sizeof(tracker.v6Str));
-
- ASSERT_EQ(0, configure_clat_ipv6_address(&tracker, &tunnel));
-
- // Check that the packet socket is bound to the interface. We can't check the socket filter
- // because there is no way to fetch it from the kernel.
- sockaddr_ll sll;
- socklen_t len = sizeof(sll);
- ASSERT_EQ(0, getsockname(tunnel.read_fd6, reinterpret_cast<sockaddr*>(&sll), &len));
- EXPECT_EQ(htons(ETH_P_IPV6), sll.sll_protocol);
- EXPECT_EQ(sll.sll_ifindex, v6Iface.ifindex());
-
- v6Iface.destroy();
- cleanupTunData(&tunnel);
-}
-
-} // namespace net
-} // namespace android
diff --git a/server/Controllers.cpp b/server/Controllers.cpp
index 7eef04c0..0df6b0ee 100644
--- a/server/Controllers.cpp
+++ b/server/Controllers.cpp
@@ -75,7 +75,6 @@ static const std::vector<const char*> FILTER_OUTPUT = {
static const std::vector<const char*> RAW_PREROUTING = {
IdletimerController::LOCAL_RAW_PREROUTING,
- ClatdController::LOCAL_RAW_PREROUTING,
BandwidthController::LOCAL_RAW_PREROUTING,
TetherController::LOCAL_RAW_PREROUTING,
};
@@ -192,8 +191,7 @@ void Controllers::createChildChains(IptablesTarget target, const char* table,
}
Controllers::Controllers()
- : clatdCtrl(&netCtrl),
- wakeupCtrl(
+ : wakeupCtrl(
[this](const WakeupController::ReportArgs& args) {
const auto listener = eventReporter.getNetdEventListener();
if (listener == nullptr) {
@@ -279,9 +277,6 @@ void Controllers::init() {
initIptablesRules();
Stopwatch s;
- clatdCtrl.init();
- gLog.info("Initializing ClatdController: %" PRId64 "us", s.getTimeAndResetUs());
-
bandwidthCtrl.enableBandwidthControl();
gLog.info("Enabling bandwidth control: %" PRId64 "us", s.getTimeAndResetUs());
diff --git a/server/Controllers.h b/server/Controllers.h
index d1e3ea3d..8b51ddf1 100644
--- a/server/Controllers.h
+++ b/server/Controllers.h
@@ -18,7 +18,6 @@
#define _CONTROLLERS_H__
#include "BandwidthController.h"
-#include "ClatdController.h"
#include "EventReporter.h"
#include "FirewallController.h"
#include "IdletimerController.h"
@@ -46,7 +45,6 @@ class Controllers {
BandwidthController bandwidthCtrl;
IdletimerController idletimerCtrl;
FirewallController firewallCtrl;
- ClatdController clatdCtrl;
StrictController strictCtrl;
EventReporter eventReporter;
IptablesRestoreController iptablesRestoreCtrl;
diff --git a/server/ControllersTest.cpp b/server/ControllersTest.cpp
index e6487e33..9033a1d3 100644
--- a/server/ControllersTest.cpp
+++ b/server/ControllersTest.cpp
@@ -98,8 +98,6 @@ TEST_F(ControllersTest, TestInitIptablesRules) {
"-F PREROUTING\n"
":idletimer_raw_PREROUTING -\n"
"-A PREROUTING -j idletimer_raw_PREROUTING\n"
- ":clat_raw_PREROUTING -\n"
- "-A PREROUTING -j clat_raw_PREROUTING\n"
":bw_raw_PREROUTING -\n"
"-A PREROUTING -j bw_raw_PREROUTING\n"
":tetherctrl_raw_PREROUTING -\n"
diff --git a/server/MDnsEventReporter.cpp b/server/MDnsEventReporter.cpp
new file mode 100644
index 00000000..db9021ae
--- /dev/null
+++ b/server/MDnsEventReporter.cpp
@@ -0,0 +1,97 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "MDnsEventReporter"
+
+#include "MDnsEventReporter.h"
+
+using android::net::mdns::aidl::IMDnsEventListener;
+
+MDnsEventReporter& MDnsEventReporter::getInstance() {
+ // It should be initialized only once.
+ static MDnsEventReporter instance;
+ return instance;
+}
+
+const MDnsEventReporter::EventListenerSet& MDnsEventReporter::getEventListeners() const {
+ return getEventListenersImpl();
+}
+
+int MDnsEventReporter::addEventListener(const android::sp<IMDnsEventListener>& listener) {
+ return addEventListenerImpl(listener);
+}
+
+int MDnsEventReporter::removeEventListener(const android::sp<IMDnsEventListener>& listener) {
+ return removeEventListenerImpl(listener);
+}
+
+const MDnsEventReporter::EventListenerSet& MDnsEventReporter::getEventListenersImpl() const {
+ std::lock_guard lock(mMutex);
+ return mEventListeners;
+}
+
+int MDnsEventReporter::addEventListenerImpl(const android::sp<IMDnsEventListener>& listener) {
+ if (listener == nullptr) {
+ ALOGE("The event listener should not be null");
+ return -EINVAL;
+ }
+
+ std::lock_guard lock(mMutex);
+
+ for (const auto& it : mEventListeners) {
+ if (android::IInterface::asBinder(it).get() ==
+ android::IInterface::asBinder(listener).get()) {
+ ALOGW("The event listener was already subscribed");
+ return -EEXIST;
+ }
+ }
+
+ // Create the death listener.
+ class DeathRecipient : public android::IBinder::DeathRecipient {
+ public:
+ DeathRecipient(MDnsEventReporter* eventReporter,
+ const android::sp<IMDnsEventListener>& listener)
+ : mEventReporter(eventReporter), mListener(listener) {}
+ ~DeathRecipient() override = default;
+ void binderDied(const android::wp<android::IBinder>& /* who */) override {
+ mEventReporter->removeEventListenerImpl(mListener);
+ }
+
+ private:
+ MDnsEventReporter* mEventReporter;
+ android::sp<IMDnsEventListener> mListener;
+ };
+
+ android::sp<android::IBinder::DeathRecipient> deathRecipient =
+ new DeathRecipient(this, listener);
+
+ android::IInterface::asBinder(listener)->linkToDeath(deathRecipient);
+
+ mEventListeners.insert(listener);
+ return 0;
+}
+
+int MDnsEventReporter::removeEventListenerImpl(const android::sp<IMDnsEventListener>& listener) {
+ if (listener == nullptr) {
+ ALOGE("The event listener should not be null");
+ return -EINVAL;
+ }
+
+ std::lock_guard lock(mMutex);
+
+ mEventListeners.erase(listener);
+ return 0;
+}
diff --git a/server/MDnsEventReporter.h b/server/MDnsEventReporter.h
new file mode 100644
index 00000000..e49c3e3f
--- /dev/null
+++ b/server/MDnsEventReporter.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <android-base/thread_annotations.h>
+#include <android/net/mdns/aidl/IMDnsEventListener.h>
+
+#include <set>
+
+class MDnsEventReporter final {
+ public:
+ MDnsEventReporter(const MDnsEventReporter&) = delete;
+ MDnsEventReporter& operator=(const MDnsEventReporter&) = delete;
+
+ using EventListenerSet = std::set<android::sp<android::net::mdns::aidl::IMDnsEventListener>>;
+
+ // Get the instance of the singleton MDnsEventReporter.
+ static MDnsEventReporter& getInstance();
+
+ // Return registered binder services from the singleton MDnsEventReporter. This method is
+ // threadsafe.
+ const EventListenerSet& getEventListeners() const;
+
+ // Add the binder to the singleton MDnsEventReporter. This method is threadsafe.
+ int addEventListener(const android::sp<android::net::mdns::aidl::IMDnsEventListener>& listener);
+
+ // Remove the binder from the singleton MDnsEventReporter. This method is threadsafe.
+ int removeEventListener(
+ const android::sp<android::net::mdns::aidl::IMDnsEventListener>& listener);
+
+ private:
+ MDnsEventReporter() = default;
+ ~MDnsEventReporter() = default;
+
+ mutable std::mutex mMutex;
+ EventListenerSet mEventListeners GUARDED_BY(mMutex);
+
+ int addEventListenerImpl(
+ const android::sp<android::net::mdns::aidl::IMDnsEventListener>& listener)
+ EXCLUDES(mMutex);
+ int removeEventListenerImpl(
+ const android::sp<android::net::mdns::aidl::IMDnsEventListener>& listener)
+ EXCLUDES(mMutex);
+ const EventListenerSet& getEventListenersImpl() const EXCLUDES(mMutex);
+ void handleEventBinderDied(const void* who) EXCLUDES(mMutex);
+};
diff --git a/server/MDnsSdListener.cpp b/server/MDnsSdListener.cpp
index b17d3431..16364008 100644
--- a/server/MDnsSdListener.cpp
+++ b/server/MDnsSdListener.cpp
@@ -37,11 +37,11 @@
#include <cutils/properties.h>
#include <log/log.h>
-#include <netdutils/ResponseCode.h>
#include <netdutils/ThreadUtil.h>
#include <sysutils/SocketClient.h>
#include "Controllers.h"
+#include "MDnsEventReporter.h"
#include "netid_client.h"
using android::net::gCtls;
@@ -53,15 +53,11 @@ using android::net::gCtls;
constexpr char RESCAN[] = "1";
-using android::netdutils::ResponseCode;
-
-static int ifaceNameToI(const char* iface) {
- if (iface != nullptr) {
- return if_nametoindex(iface);
- }
-
- return 0;
-}
+using android::net::mdns::aidl::DiscoveryInfo;
+using android::net::mdns::aidl::GetAddressInfo;
+using android::net::mdns::aidl::IMDnsEventListener;
+using android::net::mdns::aidl::RegistrationInfo;
+using android::net::mdns::aidl::ResolutionInfo;
static unsigned ifaceIndexToNetId(uint32_t interfaceIndex) {
char interfaceName[IFNAMSIZ] = {};
@@ -76,50 +72,32 @@ static unsigned ifaceIndexToNetId(uint32_t interfaceIndex) {
return netId;
}
-MDnsSdListener::MDnsSdListener() : FrameworkListener(SOCKET_NAME, true) {
- Monitor *m = new Monitor();
- registerCmd(new Handler(m, this));
-}
-
-MDnsSdListener::Handler::Handler(Monitor *m, MDnsSdListener *listener) :
- NetdCommand("mdnssd") {
- if (DBG) ALOGD("MDnsSdListener::Hander starting up");
- mMonitor = m;
- mListener = listener;
-}
-
-MDnsSdListener::Handler::~Handler() {}
-
-void MDnsSdListener::Handler::discover(SocketClient* cli, uint32_t ifIndex, const char* regType,
- const char* domain, const int requestId,
- const int requestFlags) {
+int MDnsSdListener::discover(uint32_t ifIndex, const char* regType, const char* domain,
+ const int requestId, const int requestFlags) {
if (VDBG) {
- ALOGD("discover(%d, %s, %s, %d, %d)", ifIndex, regType, domain, requestId, requestFlags);
+ ALOGD("discover(%d, %s, %s, %d, %d)", ifIndex, regType, domain ? domain : "null", requestId,
+ requestFlags);
}
- Context *context = new Context(requestId, mListener);
- DNSServiceRef *ref = mMonitor->allocateServiceRef(requestId, context);
+ Context* context = new Context(requestId);
+ DNSServiceRef* ref = mMonitor.allocateServiceRef(requestId, context);
if (ref == nullptr) {
ALOGE("requestId %d already in use during discover call", requestId);
- cli->sendMsg(ResponseCode::CommandParameterError,
- "RequestId already in use during discover call", false);
- return;
+ return -EBUSY;
}
if (VDBG) ALOGD("using ref %p", ref);
- DNSServiceFlags nativeFlags = iToFlags(requestFlags);
- DNSServiceErrorType result = DNSServiceBrowse(ref, nativeFlags, ifIndex, regType, domain,
+ DNSServiceErrorType result = DNSServiceBrowse(ref, requestFlags, ifIndex, regType, domain,
&MDnsSdListenerDiscoverCallback, context);
if (result != kDNSServiceErr_NoError) {
ALOGE("Discover request %d got an error from DNSServiceBrowse %d", requestId, result);
- mMonitor->freeServiceRef(requestId);
- cli->sendMsg(ResponseCode::CommandParameterError,
- "Discover request got an error from DNSServiceBrowse", false);
- return;
+ mMonitor.freeServiceRef(requestId);
+ // Return kDNSServiceErr_* directly instead of transferring to an UNIX error.
+ // This can help caller to know what going wrong from mdnsresponder side.
+ return -result;
}
- mMonitor->startMonitoring(requestId);
+ mMonitor.startMonitoring(requestId);
if (VDBG) ALOGD("discover successful");
- cli->sendMsg(ResponseCode::CommandOkay, "Discover operation started", false);
- return;
+ return 0;
}
void MDnsSdListenerDiscoverCallback(DNSServiceRef /* sdRef */, DNSServiceFlags flags,
@@ -128,134 +106,127 @@ void MDnsSdListenerDiscoverCallback(DNSServiceRef /* sdRef */, DNSServiceFlags f
const char* replyDomain, void* inContext) {
MDnsSdListener::Context *context = reinterpret_cast<MDnsSdListener::Context *>(inContext);
int refNumber = context->mRefNumber;
+ const auto& listeners = MDnsEventReporter::getInstance().getEventListeners();
+ if (listeners.empty()) {
+ ALOGI("Discover callback not sent since no IMDnsEventListener receiver is available.");
+ return;
+ }
- if (errorCode != kDNSServiceErr_NoError) {
- char* msg;
- asprintf(&msg, "%d %d", refNumber, errorCode);
- context->mListener->sendBroadcast(ResponseCode::ServiceDiscoveryFailed, msg, false);
- if (DBG) ALOGE("discover failure for %d, error= %d", refNumber, errorCode);
- free(msg);
- } else {
- int respCode;
- char *quotedServiceName = SocketClient::quoteArg(serviceName);
+ DiscoveryInfo info;
+ info.id = refNumber;
+ info.serviceName = serviceName;
+ info.registrationType = regType;
+ info.interfaceIdx = ifIndex;
+ // If the network is not found, still send the event and let
+ // the service decide what to do with a callback with an empty network
+ info.netId = ifaceIndexToNetId(ifIndex);
+ if (errorCode == kDNSServiceErr_NoError) {
if (flags & kDNSServiceFlagsAdd) {
if (VDBG) {
ALOGD("Discover found new serviceName %s, regType %s and domain %s for %d",
- serviceName, regType, replyDomain, refNumber);
+ serviceName, regType, replyDomain, refNumber);
}
- respCode = ResponseCode::ServiceDiscoveryServiceAdded;
+ info.result = IMDnsEventListener::SERVICE_FOUND;
} else {
if (VDBG) {
- ALOGD("Discover lost serviceName %s, regType %s and domain %s for %d",
- serviceName, regType, replyDomain, refNumber);
+ ALOGD("Discover lost serviceName %s, regType %s and domain %s for %d", serviceName,
+ regType, replyDomain, refNumber);
}
- respCode = ResponseCode::ServiceDiscoveryServiceRemoved;
+ info.result = IMDnsEventListener::SERVICE_LOST;
}
- unsigned netId = ifaceIndexToNetId(ifIndex);
- // If the network is not found, still send the broadcast back and let
- // the service decide what to do with a callback with an empty network
- char* msg;
- asprintf(&msg, "%d %s %s %s %" PRIu32 " %u", refNumber, quotedServiceName, regType,
- replyDomain, ifIndex, netId);
- context->mListener->sendBroadcast(respCode, msg, false);
- free(msg);
- free(quotedServiceName);
+ } else {
+ if (DBG) ALOGE("discover failure for %d, error= %d", refNumber, errorCode);
+ info.result = IMDnsEventListener::SERVICE_DISCOVERY_FAILED;
}
-}
-void MDnsSdListener::Handler::stop(SocketClient *cli, int argc, char **argv, const char *str) {
- if (argc != 3) {
- char *msg;
- asprintf(&msg, "Invalid number of arguments to %s", str);
- cli->sendMsg(ResponseCode::CommandParameterError, msg, false);
- free(msg);
- return;
+ for (const auto& it : listeners) {
+ it->onServiceDiscoveryStatus(info);
}
- int requestId = strtol(argv[2], nullptr, 10);
- DNSServiceRef *ref = mMonitor->lookupServiceRef(requestId);
+}
+
+int MDnsSdListener::stop(int requestId) {
+ DNSServiceRef* ref = mMonitor.lookupServiceRef(requestId);
if (ref == nullptr) {
- if (DBG) ALOGE("%s stop used unknown requestId %d", str, requestId);
- cli->sendMsg(ResponseCode::CommandParameterError, "Unknown requestId", false);
- return;
+ if (DBG) ALOGE("Stop used unknown requestId %d", requestId);
+ return -ESRCH;
}
- if (VDBG) ALOGD("Stopping %s with ref %p", str, ref);
- mMonitor->deallocateServiceRef(ref);
- mMonitor->freeServiceRef(requestId);
- char *msg;
- asprintf(&msg, "%s stopped", str);
- cli->sendMsg(ResponseCode::CommandOkay, msg, false);
- free(msg);
+ if (VDBG) ALOGD("Stopping operation with ref %p", ref);
+ mMonitor.deallocateServiceRef(ref);
+ mMonitor.freeServiceRef(requestId);
+ return 0;
}
-void MDnsSdListener::Handler::serviceRegister(SocketClient *cli, int requestId,
- const char *interfaceName, const char *serviceName, const char *serviceType,
- const char *domain, const char *host, int port, int txtLen, void *txtRecord) {
+int MDnsSdListener::serviceRegister(int requestId, const char* serviceName, const char* serviceType,
+ const char* domain, const char* host, int port,
+ const std::vector<unsigned char>& txtRecord, uint32_t ifIndex) {
if (VDBG) {
- ALOGD("serviceRegister(%d, %s, %s, %s, %s, %s, %d, %d, <binary>)", requestId,
- interfaceName, serviceName, serviceType, domain, host, port, txtLen);
+ ALOGD("serviceRegister(%d, %d, %s, %s, %s, %s, %d, <binary>)", requestId, ifIndex,
+ serviceName, serviceType, domain ? domain : "null", host ? host : "null", port);
}
- Context *context = new Context(requestId, mListener);
- DNSServiceRef *ref = mMonitor->allocateServiceRef(requestId, context);
- port = htons(port);
+ Context* context = new Context(requestId);
+ DNSServiceRef* ref = mMonitor.allocateServiceRef(requestId, context);
if (ref == nullptr) {
ALOGE("requestId %d already in use during register call", requestId);
- cli->sendMsg(ResponseCode::CommandParameterError,
- "RequestId already in use during register call", false);
- return;
+ return -EBUSY;
}
+ port = htons(port);
DNSServiceFlags nativeFlags = 0;
- int interfaceInt = ifaceNameToI(interfaceName);
- DNSServiceErrorType result = DNSServiceRegister(ref, interfaceInt, nativeFlags, serviceName,
- serviceType, domain, host, port, txtLen, txtRecord, &MDnsSdListenerRegisterCallback,
- context);
+ DNSServiceErrorType result = DNSServiceRegister(
+ ref, nativeFlags, ifIndex, serviceName, serviceType, domain, host, port,
+ txtRecord.size(), &txtRecord.front(), &MDnsSdListenerRegisterCallback, context);
if (result != kDNSServiceErr_NoError) {
ALOGE("service register request %d got an error from DNSServiceRegister %d", requestId,
result);
- mMonitor->freeServiceRef(requestId);
- cli->sendMsg(ResponseCode::CommandParameterError,
- "serviceRegister request got an error from DNSServiceRegister", false);
- return;
+ mMonitor.freeServiceRef(requestId);
+ // Return kDNSServiceErr_* directly instead of transferring to an UNIX error.
+ // This can help caller to know what going wrong from mdnsresponder side.
+ return -result;
}
- mMonitor->startMonitoring(requestId);
+ mMonitor.startMonitoring(requestId);
if (VDBG) ALOGD("serviceRegister successful");
- cli->sendMsg(ResponseCode::CommandOkay, "serviceRegister started", false);
- return;
+ return 0;
}
void MDnsSdListenerRegisterCallback(DNSServiceRef /* sdRef */, DNSServiceFlags /* flags */,
- DNSServiceErrorType errorCode, const char *serviceName, const char * /* regType */,
- const char * /* domain */, void *inContext) {
- MDnsSdListener::Context *context = reinterpret_cast<MDnsSdListener::Context *>(inContext);
- char *msg;
+ DNSServiceErrorType errorCode, const char* serviceName,
+ const char* regType, const char* /* domain */,
+ void* inContext) {
+ MDnsSdListener::Context* context = reinterpret_cast<MDnsSdListener::Context*>(inContext);
int refNumber = context->mRefNumber;
- if (errorCode != kDNSServiceErr_NoError) {
- asprintf(&msg, "%d %d", refNumber, errorCode);
- context->mListener->sendBroadcast(ResponseCode::ServiceRegistrationFailed, msg, false);
- if (DBG) ALOGE("register failure for %d, error= %d", refNumber, errorCode);
- } else {
- char *quotedServiceName = SocketClient::quoteArg(serviceName);
- asprintf(&msg, "%d %s", refNumber, quotedServiceName);
- free(quotedServiceName);
- context->mListener->sendBroadcast(ResponseCode::ServiceRegistrationSucceeded, msg, false);
+ const auto& listeners = MDnsEventReporter::getInstance().getEventListeners();
+ if (listeners.empty()) {
+ ALOGI("Register callback not sent since no IMDnsEventListener receiver is available.");
+ return;
+ }
+
+ RegistrationInfo info;
+ info.id = refNumber;
+ info.serviceName = serviceName;
+ info.registrationType = regType;
+ if (errorCode == kDNSServiceErr_NoError) {
if (VDBG) ALOGD("register succeeded for %d as %s", refNumber, serviceName);
+ info.result = IMDnsEventListener::SERVICE_REGISTERED;
+ } else {
+ if (DBG) ALOGE("register failure for %d, error= %d", refNumber, errorCode);
+ info.result = IMDnsEventListener::SERVICE_REGISTRATION_FAILED;
+ }
+
+ for (const auto& it : listeners) {
+ it->onServiceRegistrationStatus(info);
}
- free(msg);
}
-void MDnsSdListener::Handler::resolveService(SocketClient* cli, int requestId, uint32_t ifIndex,
- const char* serviceName, const char* regType,
- const char* domain) {
+int MDnsSdListener::resolveService(int requestId, uint32_t ifIndex, const char* serviceName,
+ const char* regType, const char* domain) {
if (VDBG) {
ALOGD("resolveService(%d, %d, %s, %s, %s)", requestId, ifIndex, serviceName, regType,
domain);
}
- Context *context = new Context(requestId, mListener);
- DNSServiceRef *ref = mMonitor->allocateServiceRef(requestId, context);
+ Context* context = new Context(requestId);
+ DNSServiceRef* ref = mMonitor.allocateServiceRef(requestId, context);
if (ref == nullptr) {
ALOGE("request Id %d already in use during resolve call", requestId);
- cli->sendMsg(ResponseCode::CommandParameterError,
- "RequestId already in use during resolve call", false);
- return;
+ return -EBUSY;
}
DNSServiceFlags nativeFlags = 0;
DNSServiceErrorType result = DNSServiceResolve(ref, nativeFlags, ifIndex, serviceName, regType,
@@ -263,15 +234,14 @@ void MDnsSdListener::Handler::resolveService(SocketClient* cli, int requestId, u
if (result != kDNSServiceErr_NoError) {
ALOGE("service resolve request %d on iface %d: got an error from DNSServiceResolve %d",
requestId, ifIndex, result);
- mMonitor->freeServiceRef(requestId);
- cli->sendMsg(ResponseCode::CommandParameterError,
- "resolveService got an error from DNSServiceResolve", false);
- return;
+ mMonitor.freeServiceRef(requestId);
+ // Return kDNSServiceErr_* directly instead of transferring to an UNIX error.
+ // This can help caller to know what going wrong from mdnsresponder side.
+ return -result;
}
- mMonitor->startMonitoring(requestId);
+ mMonitor.startMonitoring(requestId);
if (VDBG) ALOGD("resolveService successful");
- cli->sendMsg(ResponseCode::CommandOkay, "resolveService started", false);
- return;
+ return 0;
}
void MDnsSdListenerResolveCallback(DNSServiceRef /* sdRef */, DNSServiceFlags /* flags */,
@@ -279,49 +249,46 @@ void MDnsSdListenerResolveCallback(DNSServiceRef /* sdRef */, DNSServiceFlags /*
const char* fullname, const char* hosttarget, uint16_t port,
uint16_t txtLen, const unsigned char* txtRecord,
void* inContext) {
- MDnsSdListener::Context *context = reinterpret_cast<MDnsSdListener::Context *>(inContext);
- char *msg;
+ MDnsSdListener::Context* context = reinterpret_cast<MDnsSdListener::Context*>(inContext);
int refNumber = context->mRefNumber;
+ const auto& listeners = MDnsEventReporter::getInstance().getEventListeners();
+ if (listeners.empty()) {
+ ALOGI("Resolve callback not sent since no IMDnsEventListener receiver is available.");
+ return;
+ }
port = ntohs(port);
- if (errorCode != kDNSServiceErr_NoError) {
- asprintf(&msg, "%d %d", refNumber, errorCode);
- context->mListener->sendBroadcast(ResponseCode::ServiceResolveFailed, msg, false);
- if (DBG) ALOGE("resolve failure for %d, error= %d", refNumber, errorCode);
- } else {
- char *quotedFullName = SocketClient::quoteArg(fullname);
- char *quotedHostTarget = SocketClient::quoteArg(hosttarget);
-
- // Base 64 encodes every 3 bytes into 4 characters, but then adds padding to the next
- // multiple of 4 and a \0
- size_t dstLength = CEIL(CEIL(txtLen * 4, 3), 4) * 4 + 1;
-
- char *dst = (char *)malloc(dstLength);
- b64_ntop(txtRecord, txtLen, dst, dstLength);
-
- asprintf(&msg, "%d %s %s %d %d \"%s\" %d", refNumber, quotedFullName, quotedHostTarget,
- port, txtLen, dst, ifIndex);
- free(quotedFullName);
- free(quotedHostTarget);
- free(dst);
- context->mListener->sendBroadcast(ResponseCode::ServiceResolveSuccess, msg, false);
+
+ ResolutionInfo info;
+ info.id = refNumber;
+ info.port = port;
+ info.serviceFullName = fullname;
+ info.hostname = hosttarget;
+ info.txtRecord = std::vector<unsigned char>(txtRecord, txtRecord + txtLen);
+ info.interfaceIdx = ifIndex;
+ if (errorCode == kDNSServiceErr_NoError) {
if (VDBG) {
- ALOGD("resolve succeeded for %d finding %s at %s:%d with txtLen %d",
- refNumber, fullname, hosttarget, port, txtLen);
+ ALOGD("resolve succeeded for %d finding %s at %s:%d with txtLen %d", refNumber,
+ fullname, hosttarget, port, txtLen);
}
+ info.result = IMDnsEventListener::SERVICE_RESOLVED;
+ } else {
+ if (DBG) ALOGE("resolve failure for %d, error= %d", refNumber, errorCode);
+ info.result = IMDnsEventListener::SERVICE_RESOLUTION_FAILED;
+ }
+
+ for (const auto& it : listeners) {
+ it->onServiceResolutionStatus(info);
}
- free(msg);
}
-void MDnsSdListener::Handler::getAddrInfo(SocketClient* cli, int requestId, uint32_t ifIndex,
- uint32_t protocol, const char* hostname) {
+int MDnsSdListener::getAddrInfo(int requestId, uint32_t ifIndex, uint32_t protocol,
+ const char* hostname) {
if (VDBG) ALOGD("getAddrInfo(%d, %u %d, %s)", requestId, ifIndex, protocol, hostname);
- Context *context = new Context(requestId, mListener);
- DNSServiceRef *ref = mMonitor->allocateServiceRef(requestId, context);
+ Context* context = new Context(requestId);
+ DNSServiceRef* ref = mMonitor.allocateServiceRef(requestId, context);
if (ref == nullptr) {
ALOGE("request ID %d already in use during getAddrInfo call", requestId);
- cli->sendMsg(ResponseCode::CommandParameterError,
- "RequestId already in use during getAddrInfo call", false);
- return;
+ return -EBUSY;
}
DNSServiceFlags nativeFlags = 0;
DNSServiceErrorType result =
@@ -330,215 +297,68 @@ void MDnsSdListener::Handler::getAddrInfo(SocketClient* cli, int requestId, uint
if (result != kDNSServiceErr_NoError) {
ALOGE("getAddrInfo request %d got an error from DNSServiceGetAddrInfo %d", requestId,
result);
- mMonitor->freeServiceRef(requestId);
- cli->sendMsg(ResponseCode::CommandParameterError,
- "getAddrInfo request got an error from DNSServiceGetAddrInfo", false);
- return;
+ mMonitor.freeServiceRef(requestId);
+ // Return kDNSServiceErr_* directly instead of transferring to an UNIX error.
+ // This can help caller to know what going wrong from mdnsresponder side.
+ return -result;
}
- mMonitor->startMonitoring(requestId);
+ mMonitor.startMonitoring(requestId);
if (VDBG) ALOGD("getAddrInfo successful");
- cli->sendMsg(ResponseCode::CommandOkay, "getAddrInfo started", false);
- return;
+ return 0;
}
void MDnsSdListenerGetAddrInfoCallback(DNSServiceRef /* sdRef */, DNSServiceFlags /* flags */,
uint32_t ifIndex, DNSServiceErrorType errorCode,
const char* hostname, const struct sockaddr* const sa,
- uint32_t ttl, void* inContext) {
+ uint32_t /* ttl */, void* inContext) {
MDnsSdListener::Context *context = reinterpret_cast<MDnsSdListener::Context *>(inContext);
int refNumber = context->mRefNumber;
- unsigned netId = ifaceIndexToNetId(ifIndex);
- // If the network is not found, still send a callback with an empty network
- // and let the service decide what to do with it
+ const auto& listeners = MDnsEventReporter::getInstance().getEventListeners();
+ if (listeners.empty()) {
+ ALOGI("Get address callback not sent since no IMDnsEventListener receiver is available.");
+ return;
+ }
- if (errorCode != kDNSServiceErr_NoError) {
- char *msg;
- asprintf(&msg, "%d %d", refNumber, errorCode);
- context->mListener->sendBroadcast(ResponseCode::ServiceGetAddrInfoFailed, msg, false);
- if (DBG) ALOGE("getAddrInfo failure for %d, error= %d", refNumber, errorCode);
- free(msg);
- } else {
+ GetAddressInfo info;
+ info.id = refNumber;
+ info.hostname = hostname;
+ info.interfaceIdx = ifIndex;
+ // If the network is not found, still send the event with an empty network
+ // and let the service decide what to do with it
+ info.netId = ifaceIndexToNetId(ifIndex);
+ if (errorCode == kDNSServiceErr_NoError) {
char addr[INET6_ADDRSTRLEN];
- char *msg;
- char *quotedHostname = SocketClient::quoteArg(hostname);
if (sa->sa_family == AF_INET) {
inet_ntop(sa->sa_family, &(((struct sockaddr_in *)sa)->sin_addr), addr, sizeof(addr));
} else {
inet_ntop(sa->sa_family, &(((struct sockaddr_in6 *)sa)->sin6_addr), addr, sizeof(addr));
}
- asprintf(&msg, "%d %s %d %s %" PRIu32 " %u", refNumber, quotedHostname, ttl, addr, ifIndex,
- netId);
- free(quotedHostname);
- context->mListener->sendBroadcast(ResponseCode::ServiceGetAddrInfoSuccess, msg, false);
+ info.address = addr;
if (VDBG) {
- ALOGD("getAddrInfo succeeded for %d: %s", refNumber, msg);
+ ALOGD("getAddrInfo succeeded for %d:", refNumber);
}
- free(msg);
- }
-}
-
-void MDnsSdListener::Handler::setHostname(SocketClient *cli, int requestId,
- const char *hostname) {
- if (VDBG) ALOGD("setHostname(%d, %s)", requestId, hostname);
- Context *context = new Context(requestId, mListener);
- DNSServiceRef *ref = mMonitor->allocateServiceRef(requestId, context);
- if (ref == nullptr) {
- ALOGE("request Id %d already in use during setHostname call", requestId);
- cli->sendMsg(ResponseCode::CommandParameterError,
- "RequestId already in use during setHostname call", false);
- return;
+ info.result = IMDnsEventListener::SERVICE_GET_ADDR_SUCCESS;
+ } else {
+ if (DBG) ALOGE("getAddrInfo failure for %d, error= %d", refNumber, errorCode);
+ info.result = IMDnsEventListener::SERVICE_GET_ADDR_FAILED;
}
- DNSServiceFlags nativeFlags = 0;
- DNSServiceErrorType result = DNSSetHostname(ref, nativeFlags, hostname,
- &MDnsSdListenerSetHostnameCallback, context);
- if (result != kDNSServiceErr_NoError) {
- ALOGE("setHostname request %d got an error from DNSSetHostname %d", requestId, result);
- mMonitor->freeServiceRef(requestId);
- cli->sendMsg(ResponseCode::CommandParameterError,
- "setHostname got an error from DNSSetHostname", false);
- return;
+ for (const auto& it : listeners) {
+ it->onGettingServiceAddressStatus(info);
}
- mMonitor->startMonitoring(requestId);
- if (VDBG) ALOGD("setHostname successful");
- cli->sendMsg(ResponseCode::CommandOkay, "setHostname started", false);
- return;
}
-void MDnsSdListenerSetHostnameCallback(DNSServiceRef /* sdRef */, DNSServiceFlags /* flags */,
- DNSServiceErrorType errorCode, const char *hostname, void *inContext) {
- MDnsSdListener::Context *context = reinterpret_cast<MDnsSdListener::Context *>(inContext);
- char *msg;
- int refNumber = context->mRefNumber;
- if (errorCode != kDNSServiceErr_NoError) {
- asprintf(&msg, "%d %d", refNumber, errorCode);
- context->mListener->sendBroadcast(ResponseCode::ServiceSetHostnameFailed, msg, false);
- if (DBG) ALOGE("setHostname failure for %d, error= %d", refNumber, errorCode);
- } else {
- char *quotedHostname = SocketClient::quoteArg(hostname);
- asprintf(&msg, "%d %s", refNumber, quotedHostname);
- free(quotedHostname);
- context->mListener->sendBroadcast(ResponseCode::ServiceSetHostnameSuccess, msg, false);
- if (VDBG) ALOGD("setHostname succeeded for %d. Set to %s", refNumber, hostname);
+int MDnsSdListener::startDaemon() {
+ if (!mMonitor.startService()) {
+ ALOGE("Failed to start: Service already running");
+ return -EBUSY;
}
- free(msg);
-}
-
-DNSServiceFlags MDnsSdListener::Handler::iToFlags(int /* i */) {
- return 0;
-}
-
-int MDnsSdListener::Handler::flagsToI(DNSServiceFlags /* flags */) {
return 0;
}
-int MDnsSdListener::Handler::runCommand(SocketClient *cli,
- int argc, char **argv) {
- if (argc < 2) {
- char* msg = nullptr;
- asprintf( &msg, "Invalid number of arguments to mdnssd: %i", argc);
- ALOGW("%s", msg);
- cli->sendMsg(ResponseCode::CommandParameterError, msg, false);
- free(msg);
- return -1;
- }
-
- char* cmd = argv[1];
-
- if (strcmp(cmd, "discover") == 0) {
- if (argc != 5) {
- cli->sendMsg(ResponseCode::CommandParameterError,
- "Invalid number of arguments to mdnssd discover", false);
- return 0;
- }
- int requestId = strtol(argv[2], nullptr, 10);
- char *serviceType = argv[3];
- uint32_t interfaceIdx = atoi(argv[4]);
- discover(cli, interfaceIdx, serviceType, nullptr, requestId, 0);
- } else if (strcmp(cmd, "stop-discover") == 0) {
- stop(cli, argc, argv, "discover");
- } else if (strcmp(cmd, "register") == 0) {
- if (argc != 7) {
- cli->sendMsg(ResponseCode::CommandParameterError,
- "Invalid number of arguments to mdnssd register", false);
- return 0;
- }
- int requestId = atoi(argv[2]);
- char *serviceName = argv[3];
- char *serviceType = argv[4];
- int port = strtol(argv[5], nullptr, 10);
- char *interfaceName = nullptr; // will use all
- char *domain = nullptr; // will use default
- char *host = nullptr; // will use default hostname
-
- // TXT record length is <= 1300, see NsdServiceInfo.setAttribute
- char dst[1300];
-
- int length = b64_pton(argv[6], (u_char *)dst, 1300);
-
- if (length < 0) {
- cli->sendMsg(ResponseCode::CommandParameterError,
- "Could not decode txtRecord", false);
- return 0;
- }
-
- serviceRegister(cli, requestId, interfaceName, serviceName,
- serviceType, domain, host, port, length, dst);
- } else if (strcmp(cmd, "stop-register") == 0) {
- stop(cli, argc, argv, "register");
- } else if (strcmp(cmd, "resolve") == 0) {
- if (argc != 7) {
- cli->sendMsg(ResponseCode::CommandParameterError,
- "Invalid number of arguments to mdnssd resolve", false);
- return 0;
- }
- int requestId = atoi(argv[2]);
- char *serviceName = argv[3];
- char *regType = argv[4];
- char *domain = argv[5];
- uint32_t interfaceIdx = atoi(argv[6]);
- resolveService(cli, requestId, interfaceIdx, serviceName, regType, domain);
- } else if (strcmp(cmd, "stop-resolve") == 0) {
- stop(cli, argc, argv, "resolve");
- } else if (strcmp(cmd, "start-service") == 0) {
- if (mMonitor->startService()) {
- cli->sendMsg(ResponseCode::CommandOkay, "Service Started", false);
- } else {
- cli->sendMsg(ResponseCode::ServiceStartFailed, "Service already running", false);
- }
- } else if (strcmp(cmd, "stop-service") == 0) {
- if (mMonitor->stopService()) {
- cli->sendMsg(ResponseCode::CommandOkay, "Service Stopped", false);
- } else {
- cli->sendMsg(ResponseCode::ServiceStopFailed, "Service still in use", false);
- }
- } else if (strcmp(cmd, "sethostname") == 0) {
- if (argc != 4) {
- cli->sendMsg(ResponseCode::CommandParameterError,
- "Invalid number of arguments to mdnssd sethostname", false);
- return 0;
- }
- int requestId = strtol(argv[2], nullptr, 10);
- char *hostname = argv[3];
- setHostname(cli, requestId, hostname);
- } else if (strcmp(cmd, "stop-sethostname") == 0) {
- stop(cli, argc, argv, "sethostname");
- } else if (strcmp(cmd, "getaddrinfo") == 0) {
- if (argc != 5) {
- cli->sendMsg(ResponseCode::CommandParameterError,
- "Invalid number of arguments to mdnssd getaddrinfo", false);
- return 0;
- }
- int requestId = atoi(argv[2]);
- char *hostname = argv[3];
- uint32_t ifIndex = atoi(argv[4]);
- int protocol = 0; // intelligient heuristic (both v4 + v6)
- getAddrInfo(cli, requestId, ifIndex, protocol, hostname);
- } else if (strcmp(cmd, "stop-getaddrinfo") == 0) {
- stop(cli, argc, argv, "getaddrinfo");
- } else {
- if (VDBG) ALOGE("Unknown cmd %s", cmd);
- cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown mdnssd cmd", false);
- return 0;
+int MDnsSdListener::stopDaemon() {
+ if (!mMonitor.stopService()) {
+ ALOGE("Failed to stop: Service still in use");
+ return -EBUSY;
}
return 0;
}
@@ -619,6 +439,7 @@ void MDnsSdListener::Monitor::run() {
while (1) {
if (VDBG) ALOGD("Going to poll with pollCount %d", pollCount);
int pollResults = poll(mPollFds, pollCount, 10000000);
+ if (VDBG) ALOGD("pollResults=%d", pollResults);
if (pollResults < 0) {
ALOGE("Error in poll - got %d", errno);
} else if (pollResults > 0) {
diff --git a/server/MDnsSdListener.h b/server/MDnsSdListener.h
index 48860dd6..f9c2e87e 100644
--- a/server/MDnsSdListener.h
+++ b/server/MDnsSdListener.h
@@ -47,28 +47,39 @@ void MDnsSdListenerGetAddrInfoCallback(DNSServiceRef sdRef, DNSServiceFlags flag
const struct sockaddr* const sa, uint32_t ttl,
void* inContext);
-class MDnsSdListener : public FrameworkListener {
+class MDnsSdListener {
public:
- MDnsSdListener();
- virtual ~MDnsSdListener() {}
-
static constexpr const char* SOCKET_NAME = "mdns";
class Context {
public:
- MDnsSdListener *mListener;
int mRefNumber;
- Context(int refNumber, MDnsSdListener *m) {
- mRefNumber = refNumber;
- mListener = m;
- }
+ Context(int refNumber) { mRefNumber = refNumber; }
~Context() {
}
};
-private:
+ int stop(int requestId);
+
+ int discover(uint32_t ifIndex, const char* regType, const char* domain, const int requestId,
+ const int requestFlags);
+
+ int serviceRegister(int requestId, const char* serviceName, const char* serviceType,
+ const char* domain, const char* host, int port,
+ const std::vector<unsigned char>& txtRecord, uint32_t ifIndex);
+
+ int resolveService(int requestId, uint32_t ifIndex, const char* serviceName,
+ const char* regType, const char* domain);
+
+ int getAddrInfo(int requestId, uint32_t ifIndex, uint32_t protocol, const char* hostname);
+
+ int startDaemon();
+
+ int stopDaemon();
+
+ private:
class Monitor {
public:
Monitor();
@@ -104,36 +115,7 @@ private:
int mCtrlSocketPair[2];
std::mutex mMutex;
};
-
- class Handler : public NetdCommand {
- public:
- Handler(Monitor *m, MDnsSdListener *listener);
- virtual ~Handler();
- int runCommand(SocketClient *c, int argc, char** argv);
-
- MDnsSdListener *mListener; // needed for broadcast purposes
- private:
- void stop(SocketClient *cli, int argc, char **argv, const char *str);
-
- void discover(SocketClient* cli, uint32_t ifIndex, const char* regType, const char* domain,
- const int requestNumber, const int requestFlags);
-
- void serviceRegister(SocketClient *cli, int requestId, const char *interfaceName,
- const char *serviceName, const char *serviceType, const char *domain,
- const char *host, int port, int textLen, void *txtRecord);
-
- void resolveService(SocketClient* cli, int requestId, uint32_t ifIndex,
- const char* serviceName, const char* regType, const char* domain);
-
- void setHostname(SocketClient *cli, int requestId, const char *hostname);
-
- void getAddrInfo(SocketClient* cli, int requestId, uint32_t ifIndex, uint32_t protocol,
- const char* hostname);
-
- DNSServiceFlags iToFlags(int i);
- int flagsToI(DNSServiceFlags flags);
- Monitor *mMonitor;
- };
+ Monitor mMonitor;
};
#endif
diff --git a/server/MDnsService.cpp b/server/MDnsService.cpp
new file mode 100644
index 00000000..1c1dfca7
--- /dev/null
+++ b/server/MDnsService.cpp
@@ -0,0 +1,120 @@
+/**
+ * Copyright (c) 2022, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "MDnsService"
+
+#include "MDnsService.h"
+
+#include "binder_utils/BinderUtil.h"
+#include "binder_utils/NetdPermissions.h"
+
+#include <android-base/strings.h>
+#include <binder/Status.h>
+
+#include <string>
+#include <vector>
+
+using android::net::mdns::aidl::DiscoveryInfo;
+using android::net::mdns::aidl::GetAddressInfo;
+using android::net::mdns::aidl::IMDnsEventListener;
+using android::net::mdns::aidl::RegistrationInfo;
+using android::net::mdns::aidl::ResolutionInfo;
+
+namespace android::net {
+
+// TODO: DnsResolver has same macro definition but returns ScopedAStatus. Move these macros to
+// BinderUtil.h to do the same permission check.
+#define ENFORCE_ANY_PERMISSION(...) \
+ do { \
+ binder::Status status = checkAnyPermission({__VA_ARGS__}); \
+ if (!status.isOk()) { \
+ return status; \
+ } \
+ } while (0)
+
+#define ENFORCE_NETWORK_STACK_PERMISSIONS() \
+ ENFORCE_ANY_PERMISSION(PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK)
+
+status_t MDnsService::start() {
+ IPCThreadState::self()->disableBackgroundScheduling(true);
+ const status_t ret = BinderService<MDnsService>::publish();
+ if (ret != android::OK) {
+ return ret;
+ }
+ return android::OK;
+}
+
+binder::Status MDnsService::startDaemon() {
+ ENFORCE_NETWORK_STACK_PERMISSIONS();
+ int res = mListener.startDaemon();
+ return statusFromErrcode(res);
+}
+
+binder::Status MDnsService::stopDaemon() {
+ ENFORCE_NETWORK_STACK_PERMISSIONS();
+ int res = mListener.stopDaemon();
+ return statusFromErrcode(res);
+}
+
+binder::Status MDnsService::registerService(const RegistrationInfo& info) {
+ ENFORCE_NETWORK_STACK_PERMISSIONS();
+ int res = mListener.serviceRegister(
+ info.id, info.serviceName.c_str(), info.registrationType.c_str(), nullptr /* domain */,
+ nullptr /* host */, info.port, info.txtRecord, info.interfaceIdx);
+ return statusFromErrcode(res);
+}
+
+binder::Status MDnsService::discover(const DiscoveryInfo& info) {
+ ENFORCE_NETWORK_STACK_PERMISSIONS();
+ int res = mListener.discover(info.interfaceIdx, info.registrationType.c_str(),
+ nullptr /* domain */, info.id, 0 /* requestFlags */);
+ return statusFromErrcode(res);
+}
+
+binder::Status MDnsService::resolve(const ResolutionInfo& info) {
+ ENFORCE_NETWORK_STACK_PERMISSIONS();
+ int res = mListener.resolveService(info.id, info.interfaceIdx, info.serviceName.c_str(),
+ info.registrationType.c_str(), info.domain.c_str());
+ return statusFromErrcode(res);
+}
+
+binder::Status MDnsService::getServiceAddress(const GetAddressInfo& info) {
+ ENFORCE_NETWORK_STACK_PERMISSIONS();
+ int res = mListener.getAddrInfo(info.id, info.interfaceIdx, 0 /* protocol */,
+ info.hostname.c_str());
+ return statusFromErrcode(res);
+}
+
+binder::Status MDnsService::stopOperation(int32_t id) {
+ ENFORCE_NETWORK_STACK_PERMISSIONS();
+ int res = mListener.stop(id);
+ return statusFromErrcode(res);
+}
+
+binder::Status MDnsService::registerEventListener(const android::sp<IMDnsEventListener>& listener) {
+ ENFORCE_NETWORK_STACK_PERMISSIONS();
+ int res = MDnsEventReporter::getInstance().addEventListener(listener);
+ return statusFromErrcode(res);
+}
+
+binder::Status MDnsService::unregisterEventListener(
+ const android::sp<IMDnsEventListener>& listener) {
+ ENFORCE_NETWORK_STACK_PERMISSIONS();
+ int res = MDnsEventReporter::getInstance().removeEventListener(listener);
+ return statusFromErrcode(res);
+}
+
+} // namespace android::net
diff --git a/server/MDnsService.h b/server/MDnsService.h
new file mode 100644
index 00000000..fc3eca6b
--- /dev/null
+++ b/server/MDnsService.h
@@ -0,0 +1,50 @@
+/**
+ * Copyright (c) 2022, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include "MDnsEventReporter.h"
+#include "MDnsSdListener.h"
+
+#include <android/net/mdns/aidl/BnMDns.h>
+#include <binder/BinderService.h>
+
+namespace android::net {
+
+class MDnsService : public BinderService<MDnsService>, public android::net::mdns::aidl::BnMDns {
+ public:
+ static status_t start();
+ static char const* getServiceName() { return "mdns"; }
+
+ binder::Status startDaemon() override;
+ binder::Status stopDaemon() override;
+ binder::Status registerService(
+ const ::android::net::mdns::aidl::RegistrationInfo& info) override;
+ binder::Status discover(const ::android::net::mdns::aidl::DiscoveryInfo& info) override;
+ binder::Status resolve(const ::android::net::mdns::aidl::ResolutionInfo& info) override;
+ binder::Status getServiceAddress(
+ const ::android::net::mdns::aidl::GetAddressInfo& info) override;
+ binder::Status stopOperation(int32_t id) override;
+ binder::Status registerEventListener(
+ const android::sp<android::net::mdns::aidl::IMDnsEventListener>& listener) override;
+ binder::Status unregisterEventListener(
+ const android::sp<android::net::mdns::aidl::IMDnsEventListener>& listener) override;
+
+ private:
+ MDnsSdListener mListener;
+};
+
+} // namespace android::net
diff --git a/server/NdcDispatcher.cpp b/server/NdcDispatcher.cpp
index 80ad7fb6..303d0ddb 100644
--- a/server/NdcDispatcher.cpp
+++ b/server/NdcDispatcher.cpp
@@ -136,7 +136,6 @@ NdcDispatcher::NdcDispatcher() {
registerCmd(new BandwidthControlCmd());
registerCmd(new IdletimerControlCmd());
registerCmd(new FirewallCmd());
- registerCmd(new ClatdCmd());
registerCmd(new NetworkCommand());
registerCmd(new StrictCmd());
}
@@ -844,40 +843,6 @@ int NdcDispatcher::FirewallCmd::runCommand(NdcClient* cli, int argc, char** argv
return 0;
}
-NdcDispatcher::ClatdCmd::ClatdCmd() : NdcNetdCommand("clatd") {}
-
-int NdcDispatcher::ClatdCmd::runCommand(NdcClient* cli, int argc, char** argv) const {
- int rc = 0;
- if (argc < 3) {
- cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
- return 0;
- }
-
- std::string v6Addr;
-
- if (!strcmp(argv[1], "stop")) {
- rc = !mNetd->clatdStop(argv[2]).isOk();
- } else if (!strcmp(argv[1], "start")) {
- if (argc < 4) {
- cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing argument", false);
- return 0;
- }
- rc = !mNetd->clatdStart(argv[2], argv[3], &v6Addr).isOk();
- } else {
- cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown clatd cmd", false);
- return 0;
- }
-
- if (!rc) {
- cli->sendMsg(ResponseCode::CommandOkay,
- std::string(("Clatd operation succeeded ") + v6Addr).c_str(), false);
- } else {
- cli->sendMsg(ResponseCode::OperationFailed, "Clatd operation failed", false);
- }
-
- return 0;
-}
-
NdcDispatcher::StrictCmd::StrictCmd() : NdcNetdCommand("strict") {}
int NdcDispatcher::StrictCmd::sendGenericOkFail(NdcClient* cli, int cond) const {
diff --git a/server/NdcDispatcher.h b/server/NdcDispatcher.h
index 5732e224..2b011162 100644
--- a/server/NdcDispatcher.h
+++ b/server/NdcDispatcher.h
@@ -137,13 +137,6 @@ class NdcDispatcher {
static int parseChildChain(const char* arg);
};
- class ClatdCmd : public NdcNetdCommand {
- public:
- ClatdCmd();
- virtual ~ClatdCmd() {}
- int runCommand(NdcClient* cli, int argc, char** argv) const;
- };
-
class StrictCmd : public NdcNetdCommand {
public:
StrictCmd();
diff --git a/server/NetdNativeService.cpp b/server/NetdNativeService.cpp
index 317d830d..466d8ba7 100644
--- a/server/NetdNativeService.cpp
+++ b/server/NetdNativeService.cpp
@@ -67,48 +67,6 @@ namespace net {
namespace {
const char OPT_SHORT[] = "--short";
-// The input permissions should be equivalent that this function would return ok if any of them is
-// granted.
-binder::Status checkAnyPermission(const std::vector<const char*>& permissions) {
- pid_t pid = IPCThreadState::self()->getCallingPid();
- uid_t uid = IPCThreadState::self()->getCallingUid();
-
- // TODO: Do the pure permission check in this function. Have another method
- // (e.g. checkNetworkStackPermission) to wrap AID_SYSTEM and
- // AID_NETWORK_STACK uid check.
- // If the caller is the system UID, don't check permissions.
- // Otherwise, if the system server's binder thread pool is full, and all the threads are
- // blocked on a thread that's waiting for us to complete, we deadlock. http://b/69389492
- //
- // From a security perspective, there is currently no difference, because:
- // 1. The system server has the NETWORK_STACK permission, which grants access to all the
- // IPCs in this file.
- // 2. AID_SYSTEM always has all permissions. See ActivityManager#checkComponentPermission.
- if (uid == AID_SYSTEM) {
- return binder::Status::ok();
- }
- // AID_NETWORK_STACK own MAINLINE_NETWORK_STACK permission, don't IPC to system server to check
- // MAINLINE_NETWORK_STACK permission. Cross-process(netd, networkstack and system server)
- // deadlock: http://b/149766727
- if (uid == AID_NETWORK_STACK) {
- for (const char* permission : permissions) {
- if (std::strcmp(permission, PERM_MAINLINE_NETWORK_STACK) == 0) {
- return binder::Status::ok();
- }
- }
- }
-
- for (const char* permission : permissions) {
- if (checkPermission(String16(permission), pid, uid)) {
- return binder::Status::ok();
- }
- }
-
- auto err = StringPrintf("UID %d / PID %d does not have any of the following permissions: %s",
- uid, pid, android::base::Join(permissions, ',').c_str());
- return binder::Status::fromExceptionCode(binder::Status::EX_SECURITY, err.c_str());
-}
-
#define ENFORCE_ANY_PERMISSION(...) \
do { \
binder::Status status = checkAnyPermission({__VA_ARGS__}); \
@@ -153,13 +111,6 @@ binder::Status asBinderStatus(const base::Result<T> result) {
result.error().message().c_str());
}
-inline binder::Status statusFromErrcode(int ret) {
- if (ret) {
- return binder::Status::fromServiceSpecificError(-ret, strerror(-ret));
- }
- return binder::Status::ok();
-}
-
bool contains(const Vector<String16>& words, const String16& word) {
for (const auto& w : words) {
if (w == word) return true;
@@ -218,9 +169,6 @@ status_t NetdNativeService::dump(int fd, const Vector<String16> &args) {
gCtls->xfrmCtrl.dump(dw);
dw.blankline();
- gCtls->clatdCtrl.dump(dw);
- dw.blankline();
-
gCtls->tetherCtrl.dump(dw);
dw.blankline();
@@ -802,17 +750,20 @@ binder::Status NetdNativeService::strictUidCleartextPenalty(int32_t uid, int32_t
return statusFromErrcode(res);
}
-binder::Status NetdNativeService::clatdStart(const std::string& ifName,
- const std::string& nat64Prefix, std::string* v6Addr) {
+// TODO: remark @deprecated in INetd.aidl.
+binder::Status NetdNativeService::clatdStart(const std::string& /* ifName */,
+ const std::string& /* nat64Prefix */,
+ std::string* /* v6Addr */) {
ENFORCE_ANY_PERMISSION(PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
- int res = gCtls->clatdCtrl.startClatd(ifName.c_str(), nat64Prefix, v6Addr);
- return statusFromErrcode(res);
+ // deprecated
+ return binder::Status::fromExceptionCode(binder::Status::EX_UNSUPPORTED_OPERATION);
}
-binder::Status NetdNativeService::clatdStop(const std::string& ifName) {
+// TODO: remark @deprecated in INetd.aidl.
+binder::Status NetdNativeService::clatdStop(const std::string& /* ifName */) {
ENFORCE_ANY_PERMISSION(PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
- int res = gCtls->clatdCtrl.stopClatd(ifName.c_str());
- return statusFromErrcode(res);
+ // deprecated
+ return binder::Status::fromExceptionCode(binder::Status::EX_UNSUPPORTED_OPERATION);
}
binder::Status NetdNativeService::ipfwdEnabled(bool* status) {
diff --git a/server/RouteController.cpp b/server/RouteController.cpp
index 1e7d69a0..5ed33cdd 100644
--- a/server/RouteController.cpp
+++ b/server/RouteController.cpp
@@ -653,64 +653,9 @@ int RouteController::modifyVpnLocalExclusionRule(bool add, const char* physicalI
fwmark.permission = PERMISSION_NONE;
mask.permission = PERMISSION_NONE;
- if (int ret = modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_LOCAL_ROUTES, table,
- fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE, INVALID_UID,
- INVALID_UID)) {
- return ret;
- }
- return modifyVpnLocalExclusionRoutes(add, physicalInterface);
-}
-
-// TODO: Update the local exclusion routes based on what actual subnet the network is.
-int RouteController::modifyVpnLocalExclusionRoutes(bool add, const char* interface) {
- for (size_t i = 0; i < ARRAY_SIZE(LOCAL_EXCLUSION_ROUTES_V4); ++i) {
- if (int err = modifyVpnLocalExclusionRoute(add, interface, LOCAL_EXCLUSION_ROUTES_V4[i])) {
- return err;
- }
- }
-
- // Stop setting v6 routes if the v6 is disabled on the interface.
- std::string disable_ipv6;
- if (int err = InterfaceController::getParameter("ipv6", "conf", interface, "disable_ipv6",
- &disable_ipv6)) {
- ALOGE("Error getting %s v6 route configuration: %s", interface, strerror(-err));
- }
-
- if (!disable_ipv6.compare("1")) {
- return 0;
- }
-
- for (size_t i = 0; i < ARRAY_SIZE(LOCAL_EXCLUSION_ROUTES_V6); ++i) {
- if (int err = modifyVpnLocalExclusionRoute(add, interface, LOCAL_EXCLUSION_ROUTES_V6[i])) {
- return err;
- }
- }
- return 0;
-}
-
-int RouteController::modifyVpnLocalExclusionRoute(bool add, const char* interface,
- const char* destination) {
- uint32_t table = getRouteTableForInterface(interface, true /* local */);
- if (table == RT_TABLE_UNSPEC) {
- return -ESRCH;
- }
-
- if (int ret = modifyIpRoute(add ? RTM_NEWROUTE : RTM_DELROUTE,
- add ? NETLINK_ROUTE_CREATE_FLAGS : NETLINK_REQUEST_FLAGS, table,
- interface, destination, nullptr, 0 /* mtu */, 0 /* priority */)) {
- // Trying to delete a route that already deleted or trying to remove route on a non-exist
- // interface shouldn't cause an error. ENODEV happens in an IPv6 only network with clatd
- // started. Clat will be stopped first before calling destroying network, so the clat
- // interface is removed first before destroying the network. While trying to find the index
- // from the interface for removing the route during network destroying process, it will
- // cause an ENODEV since the interface has been removed already. This expected error should
- // not fail the follow up routing clean up.
- if (add || (ret != -ESRCH && ret != -ENODEV)) {
- return ret;
- }
- }
-
- return 0;
+ return modifyIpRule(add ? RTM_NEWRULE : RTM_DELRULE, RULE_PRIORITY_LOCAL_ROUTES, table,
+ fwmark.intValue, mask.intValue, IIF_LOOPBACK, OIF_NONE, INVALID_UID,
+ INVALID_UID);
}
// A rule to enable split tunnel VPNs.
diff --git a/server/RouteController.h b/server/RouteController.h
index 6de07dd1..9b04cfd2 100644
--- a/server/RouteController.h
+++ b/server/RouteController.h
@@ -79,13 +79,6 @@ constexpr int32_t RULE_PRIORITY_DEFAULT_NETWORK = 30000;
constexpr int32_t RULE_PRIORITY_UNREACHABLE = 32000;
// clang-format on
-constexpr const char* LOCAL_EXCLUSION_ROUTES_V4[] = {
- "169.254.0.0/16", // Link-local, RFC3927
-};
-constexpr const char* LOCAL_EXCLUSION_ROUTES_V6[] = {
- "fe80::/10" // Link-local, RFC-4291
-};
-
class UidRanges;
class RouteController {
@@ -228,9 +221,6 @@ public:
bool modifyNonUidBasedRules, bool excludeLocalRoutes);
static void updateTableNamesFile() EXCLUDES(sInterfaceToTableLock);
static int modifyVpnLocalExclusionRule(bool add, const char* physicalInterface);
- static int modifyVpnLocalExclusionRoutes(bool add, const char* interface);
- static int modifyVpnLocalExclusionRoute(bool add, const char* interface,
- const char* destination);
};
// Public because they are called by by RouteControllerTest.cpp.
diff --git a/server/TcUtils.cpp b/server/TcUtils.cpp
deleted file mode 100644
index b86e86b0..00000000
--- a/server/TcUtils.cpp
+++ /dev/null
@@ -1,387 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "TcUtils"
-
-#include "TcUtils.h"
-
-#include <arpa/inet.h>
-#include <linux/if.h>
-#include <linux/if_arp.h>
-#include <linux/netlink.h>
-#include <linux/pkt_cls.h>
-#include <linux/pkt_sched.h>
-#include <sys/ioctl.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include <log/log.h>
-
-#include "NetlinkCommands.h"
-#include "android-base/unique_fd.h"
-
-namespace android {
-namespace net {
-
-using std::max;
-
-static int doSIOCGIF(const std::string& interface, int opt) {
- base::unique_fd ufd(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
-
- if (ufd < 0) {
- const int err = errno;
- ALOGE("socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0)");
- return -err;
- };
-
- struct ifreq ifr = {};
- // We use strncpy() instead of strlcpy() since kernel has to be able
- // to handle non-zero terminated junk passed in by userspace anyway,
- // and this way too long interface names (more than IFNAMSIZ-1 = 15
- // characters plus terminating NULL) will not get truncated to 15
- // characters and zero-terminated and thus potentially erroneously
- // match a truncated interface if one were to exist.
- strncpy(ifr.ifr_name, interface.c_str(), sizeof(ifr.ifr_name));
-
- if (ioctl(ufd, opt, &ifr, sizeof(ifr))) return -errno;
-
- if (opt == SIOCGIFHWADDR) return ifr.ifr_hwaddr.sa_family;
- if (opt == SIOCGIFMTU) return ifr.ifr_mtu;
- return -EINVAL;
-}
-
-int hardwareAddressType(const std::string& interface) {
- return doSIOCGIF(interface, SIOCGIFHWADDR);
-}
-
-int deviceMTU(const std::string& interface) {
- return doSIOCGIF(interface, SIOCGIFMTU);
-}
-
-base::Result<bool> isEthernet(const std::string& interface) {
- int rv = hardwareAddressType(interface);
- if (rv < 0) {
- errno = -rv;
- return ErrnoErrorf("Get hardware address type of interface {} failed", interface);
- }
-
- switch (rv) {
- case ARPHRD_ETHER:
- return true;
- case ARPHRD_NONE:
- case ARPHRD_RAWIP: // in Linux 4.14+ rmnet support was upstreamed and this is 519
- case 530: // this is ARPHRD_RAWIP on some Android 4.9 kernels with rmnet
- return false;
- default:
- errno = EAFNOSUPPORT; // Address family not supported
- return ErrnoErrorf("Unknown hardware address type {} on interface {}", rv, interface);
- }
-}
-
-// TODO: use //system/netd/server/NetlinkCommands.cpp:openNetlinkSocket(protocol)
-// and //system/netd/server/SockDiag.cpp:checkError(fd)
-static int sendAndProcessNetlinkResponse(const void* req, int len) {
- base::unique_fd fd(socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE));
- if (fd == -1) {
- const int err = errno;
- ALOGE("socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE)");
- return -err;
- }
-
- static constexpr int on = 1;
- int rv = setsockopt(fd, SOL_NETLINK, NETLINK_CAP_ACK, &on, sizeof(on));
- if (rv) ALOGE("setsockopt(fd, SOL_NETLINK, NETLINK_CAP_ACK, %d)", on);
-
- // this is needed to get valid strace netlink parsing, it allocates the pid
- rv = bind(fd, (const struct sockaddr*)&KERNEL_NLADDR, sizeof(KERNEL_NLADDR));
- if (rv) {
- const int err = errno;
- ALOGE("bind(fd, {AF_NETLINK, 0, 0})");
- return -err;
- }
-
- // we do not want to receive messages from anyone besides the kernel
- rv = connect(fd, (const struct sockaddr*)&KERNEL_NLADDR, sizeof(KERNEL_NLADDR));
- if (rv) {
- const int err = errno;
- ALOGE("connect(fd, {AF_NETLINK, 0, 0})");
- return -err;
- }
-
- rv = send(fd, req, len, 0);
- if (rv == -1) return -errno;
- if (rv != len) return -EMSGSIZE;
-
- struct {
- nlmsghdr h;
- nlmsgerr e;
- char buf[256];
- } resp = {};
-
- rv = recv(fd, &resp, sizeof(resp), MSG_TRUNC);
-
- if (rv == -1) {
- const int err = errno;
- ALOGE("recv() failed");
- return -err;
- }
-
- if (rv < (int)NLMSG_SPACE(sizeof(struct nlmsgerr))) {
- ALOGE("recv() returned short packet: %d", rv);
- return -EMSGSIZE;
- }
-
- if (resp.h.nlmsg_len != (unsigned)rv) {
- ALOGE("recv() returned invalid header length: %d != %d", resp.h.nlmsg_len, rv);
- return -EBADMSG;
- }
-
- if (resp.h.nlmsg_type != NLMSG_ERROR) {
- ALOGE("recv() did not return NLMSG_ERROR message: %d", resp.h.nlmsg_type);
- return -EBADMSG;
- }
-
- return resp.e.error; // returns 0 on success
-}
-
-// ADD: nlMsgType=RTM_NEWQDISC nlMsgFlags=NLM_F_EXCL|NLM_F_CREATE
-// REPLACE: nlMsgType=RTM_NEWQDISC nlMsgFlags=NLM_F_CREATE|NLM_F_REPLACE
-// DEL: nlMsgType=RTM_DELQDISC nlMsgFlags=0
-int doTcQdiscClsact(int ifIndex, uint16_t nlMsgType, uint16_t nlMsgFlags) {
- // This is the name of the qdisc we are attaching.
- // Some hoop jumping to make this compile time constant with known size,
- // so that the structure declaration is well defined at compile time.
-#define CLSACT "clsact"
- // sizeof() includes the terminating NULL
- static constexpr size_t ASCIIZ_LEN_CLSACT = sizeof(CLSACT);
-
- const struct {
- nlmsghdr n;
- tcmsg t;
- struct {
- nlattr attr;
- char str[NLMSG_ALIGN(ASCIIZ_LEN_CLSACT)];
- } kind;
- } req = {
- .n =
- {
- .nlmsg_len = sizeof(req),
- .nlmsg_type = nlMsgType,
- .nlmsg_flags = static_cast<__u16>(NETLINK_REQUEST_FLAGS | nlMsgFlags),
- },
- .t =
- {
- .tcm_family = AF_UNSPEC,
- .tcm_ifindex = ifIndex,
- .tcm_handle = TC_H_MAKE(TC_H_CLSACT, 0),
- .tcm_parent = TC_H_CLSACT,
- },
- .kind =
- {
- .attr =
- {
- .nla_len = NLA_HDRLEN + ASCIIZ_LEN_CLSACT,
- .nla_type = TCA_KIND,
- },
- .str = CLSACT,
- },
- };
-#undef CLSACT
-
- return sendAndProcessNetlinkResponse(&req, sizeof(req));
-}
-
-// tc filter add dev .. in/egress prio 4 protocol ipv6/ip bpf object-pinned /sys/fs/bpf/...
-// direct-action
-int tcFilterAddDevBpf(int ifIndex, bool ingress, uint16_t proto, int bpfFd, bool ethernet) {
- // This is the name of the filter we're attaching (ie. this is the 'bpf'
- // packet classifier enabled by kernel config option CONFIG_NET_CLS_BPF.
- //
- // We go through some hoops in order to make this compile time constants
- // so that we can define the struct further down the function with the
- // field for this sized correctly already during the build.
-#define BPF "bpf"
- // sizeof() includes the terminating NULL
- static constexpr size_t ASCIIZ_LEN_BPF = sizeof(BPF);
-
- // This is to replicate program name suffix used by 'tc' Linux cli
- // when it attaches programs.
-#define FSOBJ_SUFFIX ":[*fsobj]"
-
- // This macro expands (from header files) to:
- // prog_clatd_schedcls_ingress6_clat_rawip:[*fsobj]
- // and is the name of the pinned ingress ebpf program for ARPHRD_RAWIP interfaces.
- // (also compatible with anything that has 0 size L2 header)
- static constexpr char name_clat_rx_rawip[] = CLAT_INGRESS6_PROG_RAWIP_NAME FSOBJ_SUFFIX;
-
- // This macro expands (from header files) to:
- // prog_clatd_schedcls_ingress6_clat_ether:[*fsobj]
- // and is the name of the pinned ingress ebpf program for ARPHRD_ETHER interfaces.
- // (also compatible with anything that has standard ethernet header)
- static constexpr char name_clat_rx_ether[] = CLAT_INGRESS6_PROG_ETHER_NAME FSOBJ_SUFFIX;
-
- // This macro expands (from header files) to:
- // prog_clatd_schedcls_egress4_clat_rawip:[*fsobj]
- // and is the name of the pinned egress ebpf program for ARPHRD_RAWIP interfaces.
- // (also compatible with anything that has 0 size L2 header)
- static constexpr char name_clat_tx_rawip[] = CLAT_EGRESS4_PROG_RAWIP_NAME FSOBJ_SUFFIX;
-
- // This macro expands (from header files) to:
- // prog_clatd_schedcls_egress4_clat_ether:[*fsobj]
- // and is the name of the pinned egress ebpf program for ARPHRD_ETHER interfaces.
- // (also compatible with anything that has standard ethernet header)
- static constexpr char name_clat_tx_ether[] = CLAT_EGRESS4_PROG_ETHER_NAME FSOBJ_SUFFIX;
-
-#undef FSOBJ_SUFFIX
-
- // The actual name we'll use is determined at run time via 'ethernet' and 'ingress'
- // booleans. We need to compile time allocate enough space in the struct
- // hence this macro magic to make sure we have enough space for either
- // possibility. In practice some of these are actually the same size.
- static constexpr size_t ASCIIZ_MAXLEN_NAME = max({
- sizeof(name_clat_rx_rawip),
- sizeof(name_clat_rx_ether),
- sizeof(name_clat_tx_rawip),
- sizeof(name_clat_tx_ether),
- });
-
- // These are not compile time constants: 'name' is used in strncpy below
- const char* const name_clat_rx = ethernet ? name_clat_rx_ether : name_clat_rx_rawip;
- const char* const name_clat_tx = ethernet ? name_clat_tx_ether : name_clat_tx_rawip;
- const char* const name = ingress ? name_clat_rx : name_clat_tx;
-
- struct {
- nlmsghdr n;
- tcmsg t;
- struct {
- nlattr attr;
- char str[NLMSG_ALIGN(ASCIIZ_LEN_BPF)];
- } kind;
- struct {
- nlattr attr;
- struct {
- nlattr attr;
- __u32 u32;
- } fd;
- struct {
- nlattr attr;
- char str[NLMSG_ALIGN(ASCIIZ_MAXLEN_NAME)];
- } name;
- struct {
- nlattr attr;
- __u32 u32;
- } flags;
- } options;
- } req = {
- .n =
- {
- .nlmsg_len = sizeof(req),
- .nlmsg_type = RTM_NEWTFILTER,
- .nlmsg_flags = NETLINK_REQUEST_FLAGS | NLM_F_EXCL | NLM_F_CREATE,
- },
- .t =
- {
- .tcm_family = AF_UNSPEC,
- .tcm_ifindex = ifIndex,
- .tcm_handle = TC_H_UNSPEC,
- .tcm_parent = TC_H_MAKE(TC_H_CLSACT,
- ingress ? TC_H_MIN_INGRESS : TC_H_MIN_EGRESS),
- .tcm_info = static_cast<__u32>((PRIO_CLAT << 16) | htons(proto)),
- },
- .kind =
- {
- .attr =
- {
- .nla_len = sizeof(req.kind),
- .nla_type = TCA_KIND,
- },
- .str = BPF,
- },
- .options =
- {
- .attr =
- {
- .nla_len = sizeof(req.options),
- .nla_type = NLA_F_NESTED | TCA_OPTIONS,
- },
- .fd =
- {
- .attr =
- {
- .nla_len = sizeof(req.options.fd),
- .nla_type = TCA_BPF_FD,
- },
- .u32 = static_cast<__u32>(bpfFd),
- },
- .name =
- {
- .attr =
- {
- .nla_len = sizeof(req.options.name),
- .nla_type = TCA_BPF_NAME,
- },
- // Visible via 'tc filter show', but
- // is overwritten by strncpy below
- .str = "placeholder",
- },
- .flags =
- {
- .attr =
- {
- .nla_len = sizeof(req.options.flags),
- .nla_type = TCA_BPF_FLAGS,
- },
- .u32 = TCA_BPF_FLAG_ACT_DIRECT,
- },
- },
- };
-#undef BPF
-
- strncpy(req.options.name.str, name, sizeof(req.options.name.str));
-
- return sendAndProcessNetlinkResponse(&req, sizeof(req));
-}
-
-// tc filter del dev .. in/egress prio 4 protocol ..
-int tcFilterDelDev(int ifIndex, bool ingress, uint16_t prio, uint16_t proto) {
- const struct {
- nlmsghdr n;
- tcmsg t;
- } req = {
- .n =
- {
- .nlmsg_len = sizeof(req),
- .nlmsg_type = RTM_DELTFILTER,
- .nlmsg_flags = NETLINK_REQUEST_FLAGS,
- },
- .t =
- {
- .tcm_family = AF_UNSPEC,
- .tcm_ifindex = ifIndex,
- .tcm_handle = TC_H_UNSPEC,
- .tcm_parent = TC_H_MAKE(TC_H_CLSACT,
- ingress ? TC_H_MIN_INGRESS : TC_H_MIN_EGRESS),
- .tcm_info = (static_cast<uint32_t>(prio) << 16) |
- static_cast<uint32_t>(htons(proto)),
- },
- };
-
- return sendAndProcessNetlinkResponse(&req, sizeof(req));
-}
-
-} // namespace net
-} // namespace android
diff --git a/server/TcUtils.h b/server/TcUtils.h
index 212838ed..d205c04b 100644
--- a/server/TcUtils.h
+++ b/server/TcUtils.h
@@ -21,6 +21,7 @@
#include <linux/if_ether.h>
#include <linux/if_link.h>
#include <linux/rtnetlink.h>
+#include <tcutils/tcutils.h>
#include <string>
@@ -42,38 +43,25 @@ constexpr bool INGRESS = true;
// The priority of clat hook - must be after tethering.
constexpr uint16_t PRIO_CLAT = 4;
-// this returns an ARPHRD_* constant or a -errno
-int hardwareAddressType(const std::string& interface);
-
-// return MTU or -errno
-int deviceMTU(const std::string& interface);
-
-base::Result<bool> isEthernet(const std::string& interface);
+inline base::Result<bool> isEthernet(const std::string& interface) {
+ bool result = false;
+ if (int error = ::android::isEthernet(interface.c_str(), result)) {
+ errno = error;
+ return ErrnoErrorf("isEthernet failed for interface {}", interface);
+ }
+ return result;
+}
inline int getClatEgress4MapFd(void) {
const int fd = bpf::mapRetrieveRW(CLAT_EGRESS4_MAP_PATH);
return (fd == -1) ? -errno : fd;
}
-inline int getClatEgress4ProgFd(bool with_ethernet_header) {
- const int fd = bpf::retrieveProgram(with_ethernet_header ? CLAT_EGRESS4_PROG_ETHER_PATH
- : CLAT_EGRESS4_PROG_RAWIP_PATH);
- return (fd == -1) ? -errno : fd;
-}
-
inline int getClatIngress6MapFd(void) {
const int fd = bpf::mapRetrieveRW(CLAT_INGRESS6_MAP_PATH);
return (fd == -1) ? -errno : fd;
}
-inline int getClatIngress6ProgFd(bool with_ethernet_header) {
- const int fd = bpf::retrieveProgram(with_ethernet_header ? CLAT_INGRESS6_PROG_ETHER_PATH
- : CLAT_INGRESS6_PROG_RAWIP_PATH);
- return (fd == -1) ? -errno : fd;
-}
-
-int doTcQdiscClsact(int ifIndex, uint16_t nlMsgType, uint16_t nlMsgFlags);
-
inline int tcQdiscAddDevClsact(int ifIndex) {
return doTcQdiscClsact(ifIndex, RTM_NEWQDISC, NLM_F_EXCL | NLM_F_CREATE);
}
@@ -86,31 +74,24 @@ inline int tcQdiscDelDevClsact(int ifIndex) {
return doTcQdiscClsact(ifIndex, RTM_DELQDISC, 0);
}
-// tc filter add dev .. in/egress prio 4 protocol ipv6/ip bpf object-pinned /sys/fs/bpf/...
-// direct-action
-int tcFilterAddDevBpf(int ifIndex, bool ingress, uint16_t proto, int bpfFd, bool ethernet);
-
// tc filter add dev .. ingress prio 4 protocol ipv6 bpf object-pinned /sys/fs/bpf/... direct-action
-inline int tcFilterAddDevIngressClatIpv6(int ifIndex, int bpfFd, bool ethernet) {
- return tcFilterAddDevBpf(ifIndex, INGRESS, ETH_P_IPV6, bpfFd, ethernet);
+inline int tcFilterAddDevIngressClatIpv6(int ifIndex, const std::string& bpfProgPath) {
+ return tcAddBpfFilter(ifIndex, INGRESS, PRIO_CLAT, ETH_P_IPV6, bpfProgPath.c_str());
}
// tc filter add dev .. egress prio 4 protocol ip bpf object-pinned /sys/fs/bpf/... direct-action
-inline int tcFilterAddDevEgressClatIpv4(int ifIndex, int bpfFd, bool ethernet) {
- return tcFilterAddDevBpf(ifIndex, EGRESS, ETH_P_IP, bpfFd, ethernet);
+inline int tcFilterAddDevEgressClatIpv4(int ifIndex, const std::string& bpfProgPath) {
+ return tcAddBpfFilter(ifIndex, EGRESS, PRIO_CLAT, ETH_P_IP, bpfProgPath.c_str());
}
-// tc filter del dev .. in/egress prio .. protocol ..
-int tcFilterDelDev(int ifIndex, bool ingress, uint16_t prio, uint16_t proto);
-
// tc filter del dev .. ingress prio 4 protocol ipv6
inline int tcFilterDelDevIngressClatIpv6(int ifIndex) {
- return tcFilterDelDev(ifIndex, INGRESS, PRIO_CLAT, ETH_P_IPV6);
+ return tcDeleteFilter(ifIndex, INGRESS, PRIO_CLAT, ETH_P_IPV6);
}
// tc filter del dev .. egress prio 4 protocol ip
inline int tcFilterDelDevEgressClatIpv4(int ifIndex) {
- return tcFilterDelDev(ifIndex, EGRESS, PRIO_CLAT, ETH_P_IP);
+ return tcDeleteFilter(ifIndex, EGRESS, PRIO_CLAT, ETH_P_IP);
}
} // namespace net
diff --git a/server/TcUtilsTest.cpp b/server/TcUtilsTest.cpp
deleted file mode 100644
index ee292061..00000000
--- a/server/TcUtilsTest.cpp
+++ /dev/null
@@ -1,212 +0,0 @@
-/*
- * Copyright 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * TcUtilsTest.cpp - unit tests for TcUtils.cpp
- */
-
-#include <gtest/gtest.h>
-
-#include "TcUtils.h"
-
-#include <linux/if_arp.h>
-#include <stdlib.h>
-#include <sys/wait.h>
-
-#include "bpf/BpfUtils.h"
-#include "bpf_shared.h"
-
-namespace android {
-namespace net {
-
-class TcUtilsTest : public ::testing::Test {
- public:
- void SetUp() {}
-};
-
-TEST_F(TcUtilsTest, HardwareAddressTypeOfNonExistingIf) {
- ASSERT_EQ(-ENODEV, hardwareAddressType("not_existing_if"));
-}
-
-TEST_F(TcUtilsTest, HardwareAddressTypeOfLoopback) {
- ASSERT_EQ(ARPHRD_LOOPBACK, hardwareAddressType("lo"));
-}
-
-// If wireless 'wlan0' interface exists it should be Ethernet.
-TEST_F(TcUtilsTest, HardwareAddressTypeOfWireless) {
- int type = hardwareAddressType("wlan0");
- if (type == -ENODEV) return;
-
- ASSERT_EQ(ARPHRD_ETHER, type);
-}
-
-// If cellular 'rmnet_data0' interface exists it should
-// *probably* not be Ethernet and instead be RawIp.
-TEST_F(TcUtilsTest, HardwareAddressTypeOfCellular) {
- int type = hardwareAddressType("rmnet_data0");
- if (type == -ENODEV) return;
-
- ASSERT_NE(ARPHRD_ETHER, type);
-
- // ARPHRD_RAWIP is 530 on some pre-4.14 Qualcomm devices.
- if (type == 530) return;
-
- ASSERT_EQ(ARPHRD_RAWIP, type);
-}
-
-TEST_F(TcUtilsTest, IsEthernetOfNonExistingIf) {
- auto res = isEthernet("not_existing_if");
- ASSERT_FALSE(res.ok());
- ASSERT_EQ(ENODEV, res.error().code());
-}
-
-TEST_F(TcUtilsTest, IsEthernetOfLoopback) {
- auto res = isEthernet("lo");
- ASSERT_FALSE(res.ok());
- ASSERT_EQ(EAFNOSUPPORT, res.error().code());
-}
-
-// If wireless 'wlan0' interface exists it should be Ethernet.
-// See also HardwareAddressTypeOfWireless.
-TEST_F(TcUtilsTest, IsEthernetOfWireless) {
- auto res = isEthernet("wlan0");
- if (!res.ok() && res.error().code() == ENODEV) return;
-
- ASSERT_RESULT_OK(res);
- ASSERT_TRUE(res.value());
-}
-
-// If cellular 'rmnet_data0' interface exists it should
-// *probably* not be Ethernet and instead be RawIp.
-// See also HardwareAddressTypeOfCellular.
-TEST_F(TcUtilsTest, IsEthernetOfCellular) {
- auto res = isEthernet("rmnet_data0");
- if (!res.ok() && res.error().code() == ENODEV) return;
-
- ASSERT_RESULT_OK(res);
- ASSERT_FALSE(res.value());
-}
-
-TEST_F(TcUtilsTest, DeviceMTUOfNonExistingIf) {
- ASSERT_EQ(-ENODEV, deviceMTU("not_existing_if"));
-}
-
-TEST_F(TcUtilsTest, DeviceMTUofLoopback) {
- ASSERT_EQ(65536, deviceMTU("lo"));
-}
-
-TEST_F(TcUtilsTest, GetClatEgress4MapFd) {
- int fd = getClatEgress4MapFd();
- ASSERT_GE(fd, 3); // 0,1,2 - stdin/out/err, thus fd >= 3
- EXPECT_EQ(FD_CLOEXEC, fcntl(fd, F_GETFD));
- close(fd);
-}
-
-TEST_F(TcUtilsTest, GetClatEgress4RawIpProgFd) {
- int fd = getClatEgress4ProgFd(RAWIP);
- ASSERT_GE(fd, 3);
- EXPECT_EQ(FD_CLOEXEC, fcntl(fd, F_GETFD));
- close(fd);
-}
-
-TEST_F(TcUtilsTest, GetClatEgress4EtherProgFd) {
- int fd = getClatEgress4ProgFd(ETHER);
- ASSERT_GE(fd, 3);
- EXPECT_EQ(FD_CLOEXEC, fcntl(fd, F_GETFD));
- close(fd);
-}
-
-TEST_F(TcUtilsTest, GetClatIngress6MapFd) {
- int fd = getClatIngress6MapFd();
- ASSERT_GE(fd, 3); // 0,1,2 - stdin/out/err, thus fd >= 3
- EXPECT_EQ(FD_CLOEXEC, fcntl(fd, F_GETFD));
- close(fd);
-}
-
-TEST_F(TcUtilsTest, GetClatIngress6RawIpProgFd) {
- int fd = getClatIngress6ProgFd(RAWIP);
- ASSERT_GE(fd, 3);
- EXPECT_EQ(FD_CLOEXEC, fcntl(fd, F_GETFD));
- close(fd);
-}
-
-TEST_F(TcUtilsTest, GetClatIngress6EtherProgFd) {
- int fd = getClatIngress6ProgFd(ETHER);
- ASSERT_GE(fd, 3);
- EXPECT_EQ(FD_CLOEXEC, fcntl(fd, F_GETFD));
- close(fd);
-}
-
-// See Linux kernel source in include/net/flow.h
-#define LOOPBACK_IFINDEX 1
-
-TEST_F(TcUtilsTest, AttachReplaceDetachClsactLo) {
- // This attaches and detaches a configuration-less and thus no-op clsact
- // qdisc to loopback interface (and it takes fractions of a second)
- EXPECT_EQ(0, tcQdiscAddDevClsact(LOOPBACK_IFINDEX));
- EXPECT_EQ(0, tcQdiscReplaceDevClsact(LOOPBACK_IFINDEX));
- EXPECT_EQ(0, tcQdiscDelDevClsact(LOOPBACK_IFINDEX));
- EXPECT_EQ(-EINVAL, tcQdiscDelDevClsact(LOOPBACK_IFINDEX));
-}
-
-static void checkAttachDetachBpfFilterClsactLo(const bool ingress, const bool ethernet) {
- // Older kernels return EINVAL instead of ENOENT due to lacking proper error propagation...
- const int errNOENT = android::bpf::isAtLeastKernelVersion(4, 19, 0) ? ENOENT : EINVAL;
-
- int clatBpfFd = ingress ? getClatIngress6ProgFd(ethernet) : getClatEgress4ProgFd(ethernet);
- ASSERT_GE(clatBpfFd, 3);
-
- // This attaches and detaches a clsact plus ebpf program to loopback
- // interface, but it should not affect traffic by virtue of us not
- // actually populating the ebpf control map.
- // Furthermore: it only takes fractions of a second.
- EXPECT_EQ(-EINVAL, tcFilterDelDevIngressClatIpv6(LOOPBACK_IFINDEX));
- EXPECT_EQ(-EINVAL, tcFilterDelDevEgressClatIpv4(LOOPBACK_IFINDEX));
- EXPECT_EQ(0, tcQdiscAddDevClsact(LOOPBACK_IFINDEX));
- EXPECT_EQ(-errNOENT, tcFilterDelDevIngressClatIpv6(LOOPBACK_IFINDEX));
- EXPECT_EQ(-errNOENT, tcFilterDelDevEgressClatIpv4(LOOPBACK_IFINDEX));
- if (ingress) {
- EXPECT_EQ(0, tcFilterAddDevIngressClatIpv6(LOOPBACK_IFINDEX, clatBpfFd, ethernet));
- EXPECT_EQ(0, tcFilterDelDevIngressClatIpv6(LOOPBACK_IFINDEX));
- } else {
- EXPECT_EQ(0, tcFilterAddDevEgressClatIpv4(LOOPBACK_IFINDEX, clatBpfFd, ethernet));
- EXPECT_EQ(0, tcFilterDelDevEgressClatIpv4(LOOPBACK_IFINDEX));
- }
- EXPECT_EQ(-errNOENT, tcFilterDelDevIngressClatIpv6(LOOPBACK_IFINDEX));
- EXPECT_EQ(-errNOENT, tcFilterDelDevEgressClatIpv4(LOOPBACK_IFINDEX));
- EXPECT_EQ(0, tcQdiscDelDevClsact(LOOPBACK_IFINDEX));
- EXPECT_EQ(-EINVAL, tcFilterDelDevIngressClatIpv6(LOOPBACK_IFINDEX));
- EXPECT_EQ(-EINVAL, tcFilterDelDevEgressClatIpv4(LOOPBACK_IFINDEX));
-
- close(clatBpfFd);
-}
-
-TEST_F(TcUtilsTest, CheckAttachBpfFilterRawIpClsactEgressLo) {
- checkAttachDetachBpfFilterClsactLo(EGRESS, RAWIP);
-}
-
-TEST_F(TcUtilsTest, CheckAttachBpfFilterEthernetClsactEgressLo) {
- checkAttachDetachBpfFilterClsactLo(EGRESS, ETHER);
-}
-
-TEST_F(TcUtilsTest, CheckAttachBpfFilterRawIpClsactIngressLo) {
- checkAttachDetachBpfFilterClsactLo(INGRESS, RAWIP);
-}
-
-TEST_F(TcUtilsTest, CheckAttachBpfFilterEthernetClsactIngressLo) {
- checkAttachDetachBpfFilterClsactLo(INGRESS, ETHER);
-}
-
-} // namespace net
-} // namespace android
diff --git a/server/main.cpp b/server/main.cpp
index fd1544c6..0e81d4e5 100644
--- a/server/main.cpp
+++ b/server/main.cpp
@@ -40,6 +40,7 @@
#include "Controllers.h"
#include "FwmarkServer.h"
#include "MDnsSdListener.h"
+#include "MDnsService.h"
#include "NFLogListener.h"
#include "NetdConstants.h"
#include "NetdHwService.h"
@@ -58,6 +59,7 @@ using android::net::FwmarkServer;
using android::net::gCtls;
using android::net::gLog;
using android::net::makeNFLogListener;
+using android::net::MDnsService;
using android::net::NetdHwService;
using android::net::NetdNativeService;
using android::net::NetlinkManager;
@@ -177,12 +179,6 @@ int main() {
exit(1);
}
- MDnsSdListener mdnsl;
- if (mdnsl.startListener()) {
- ALOGE("Unable to start MDnsSdListener (%s)", strerror(errno));
- exit(1);
- }
-
FwmarkServer fwmarkServer(&gCtls->netCtrl, &gCtls->eventReporter);
if (fwmarkServer.startListener()) {
ALOGE("Unable to start FwmarkServer (%s)", strerror(errno));
@@ -197,6 +193,12 @@ int main() {
}
gLog.info("Registering NetdNativeService: %" PRId64 "us", subTime.getTimeAndResetUs());
+ if ((ret = MDnsService::start()) != android::OK) {
+ ALOGE("Unable to start MDnsService: %d", ret);
+ exit(1);
+ }
+ gLog.info("Registering MDnsService: %" PRId64 "us", subTime.getTimeAndResetUs());
+
android::net::process::ScopedPidFile pidFile(PID_FILE_PATH);
// Now that netd is ready to process commands, advertise service availability for HAL clients.
diff --git a/tests/Android.bp b/tests/Android.bp
index 1b6bc9dc..21830d6d 100644
--- a/tests/Android.bp
+++ b/tests/Android.bp
@@ -107,6 +107,8 @@ cc_test {
"libnetd_test_utils",
"libnetdutils",
"libnettestutils",
+ "libtcutils",
+ "mdns_aidl_interface-V1-cpp",
"netd_aidl_interface-V8-cpp",
"netd_event_listener_interface-V1-cpp",
"oemnetd_aidl_interface-cpp",
diff --git a/tests/binder_test.cpp b/tests/binder_test.cpp
index 6d291387..519effea 100644
--- a/tests/binder_test.cpp
+++ b/tests/binder_test.cpp
@@ -71,6 +71,12 @@
#include "TestUnsolService.h"
#include "XfrmController.h"
#include "android/net/INetd.h"
+#include "android/net/mdns/aidl/BnMDnsEventListener.h"
+#include "android/net/mdns/aidl/DiscoveryInfo.h"
+#include "android/net/mdns/aidl/GetAddressInfo.h"
+#include "android/net/mdns/aidl/IMDns.h"
+#include "android/net/mdns/aidl/RegistrationInfo.h"
+#include "android/net/mdns/aidl/ResolutionInfo.h"
#include "binder/IServiceManager.h"
#include "netdutils/InternetAddresses.h"
#include "netdutils/Stopwatch.h"
@@ -102,11 +108,10 @@ using android::base::StartsWith;
using android::base::StringPrintf;
using android::base::Trim;
using android::base::unique_fd;
+using android::binder::Status;
using android::net::INetd;
using android::net::InterfaceConfigurationParcel;
using android::net::InterfaceController;
-using android::net::LOCAL_EXCLUSION_ROUTES_V4;
-using android::net::LOCAL_EXCLUSION_ROUTES_V6;
using android::net::MarkMaskParcel;
using android::net::NativeNetworkConfig;
using android::net::NativeNetworkType;
@@ -131,6 +136,11 @@ using android::net::TetherStatsParcel;
using android::net::TunInterface;
using android::net::UidRangeParcel;
using android::net::UidRanges;
+using android::net::mdns::aidl::DiscoveryInfo;
+using android::net::mdns::aidl::GetAddressInfo;
+using android::net::mdns::aidl::IMDns;
+using android::net::mdns::aidl::RegistrationInfo;
+using android::net::mdns::aidl::ResolutionInfo;
using android::net::netd::aidl::NativeUidRangeConfig;
using android::netdutils::getIfaceNames;
using android::netdutils::IPAddress;
@@ -1444,16 +1454,6 @@ void expectNetworkRouteExistsWithMtu(const char* ipVersion, const std::string& i
<< "] in table " << table;
}
-bool ipRouteExists(const char* ipType, std::string& ipRoute, const std::string& tableName) {
- std::vector<std::string> routes = listIpRoutes(ipType, tableName.c_str());
- for (const auto& route : routes) {
- if (route.find(ipRoute) != std::string::npos) {
- return true;
- }
- }
- return false;
-}
-
void expectVpnLocalExclusionRuleExists(const std::string& ifName, bool expectExists) {
std::string tableName = std::string(ifName + "_local");
// Check if rule exists
@@ -1625,84 +1625,6 @@ void expectProcessDoesNotExist(const std::string& processName) {
} // namespace
-TEST_F(NetdBinderTest, ClatdStartStop) {
- binder::Status status;
-
- const std::string clatdName = StringPrintf("clatd-%s", sTun.name().c_str());
- std::string clatAddress;
- std::string nat64Prefix = "2001:db8:cafe:f00d:1:2::/96";
-
- // Can't start clatd on an interface that's not part of any network...
- status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
- EXPECT_FALSE(status.isOk());
- EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
-
- // ... so create a test physical network and add our tun to it.
- const auto& config = makeNativeNetworkConfig(TEST_NETID1, NativeNetworkType::PHYSICAL,
- INetd::PERMISSION_NONE, false, false);
- EXPECT_TRUE(mNetd->networkCreate(config).isOk());
- EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, sTun.name()).isOk());
-
- // Prefix must be 96 bits long.
- status = mNetd->clatdStart(sTun.name(), "2001:db8:cafe:f00d::/64", &clatAddress);
- EXPECT_FALSE(status.isOk());
- EXPECT_EQ(EINVAL, status.serviceSpecificErrorCode());
-
- // Can't start clatd unless there's a default route...
- status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
- EXPECT_FALSE(status.isOk());
- EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
-
- // so add a default route.
- EXPECT_TRUE(mNetd->networkAddRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
-
- // Can't start clatd unless there's a global address...
- status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
- EXPECT_FALSE(status.isOk());
- EXPECT_EQ(EADDRNOTAVAIL, status.serviceSpecificErrorCode());
-
- // ... so add a global address.
- const std::string v6 = "2001:db8:1:2:f076:ae99:124e:aa99";
- EXPECT_EQ(0, sTun.addAddress(v6.c_str(), 64));
-
- // Now expect clatd to start successfully.
- status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
- EXPECT_TRUE(status.isOk());
- EXPECT_EQ(0, status.serviceSpecificErrorCode());
-
- // Add clat interface and verify the expected rule exists
- const std::string clatIface = "v4-" + sTun.name();
- EXPECT_TRUE(mNetd->networkAddInterface(TEST_NETID1, clatIface).isOk());
- expectVpnLocalExclusionRuleExists(sTun.name(), true);
-
- // Starting it again returns EBUSY.
- status = mNetd->clatdStart(sTun.name(), nat64Prefix, &clatAddress);
- EXPECT_FALSE(status.isOk());
- EXPECT_EQ(EBUSY, status.serviceSpecificErrorCode());
-
- expectProcessExists(clatdName);
-
- // Expect clatd to stop successfully.
- status = mNetd->clatdStop(sTun.name());
- EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
- expectProcessDoesNotExist(clatdName);
-
- // Stopping a clatd that doesn't exist returns ENODEV.
- status = mNetd->clatdStop(sTun.name());
- EXPECT_FALSE(status.isOk());
- EXPECT_EQ(ENODEV, status.serviceSpecificErrorCode());
- expectProcessDoesNotExist(clatdName);
-
- // Clean up.
- EXPECT_TRUE(mNetd->networkRemoveRoute(TEST_NETID1, sTun.name(), "::/0", "").isOk());
- EXPECT_EQ(0, ifc_del_address(sTun.name().c_str(), v6.c_str(), 64));
- EXPECT_TRUE(mNetd->networkDestroy(TEST_NETID1).isOk());
-
- // Corresponding rules should be removed.
- expectVpnLocalExclusionRuleExists(sTun.name(), false);
- expectVpnLocalExclusionRuleExists(clatIface, false);
-}
-
namespace {
bool getIpfwdV4Enable() {
@@ -3540,30 +3462,6 @@ void expectVpnFallthroughRuleExists(const std::string& ifName, int vpnNetId) {
}
}
-void expectVpnLocalExclusionRouteExists(const std::string& ifName) {
- std::string tableName = std::string(ifName + "_local");
- // Check if routes exist
- for (size_t i = 0; i < ARRAY_SIZE(LOCAL_EXCLUSION_ROUTES_V4); ++i) {
- const auto& dst = LOCAL_EXCLUSION_ROUTES_V4[i];
- std::string vpnLocalExclusionRoute =
- StringPrintf("%s dev %s proto static scope link", dst, ifName.c_str());
- EXPECT_TRUE(ipRouteExists(IP_RULE_V4, vpnLocalExclusionRoute, tableName));
- }
- // expect no other rule
- std::vector<std::string> routes = listIpRoutes(IP_RULE_V4, tableName.c_str());
- EXPECT_EQ(routes.size(), ARRAY_SIZE(LOCAL_EXCLUSION_ROUTES_V4));
-
- for (size_t i = 0; i < ARRAY_SIZE(LOCAL_EXCLUSION_ROUTES_V6); ++i) {
- const auto& dst = LOCAL_EXCLUSION_ROUTES_V6[i];
- std::string vpnLocalExclusionRoute =
- StringPrintf("%s dev %s proto static", dst, ifName.c_str());
- EXPECT_TRUE(ipRouteExists(IP_RULE_V6, vpnLocalExclusionRoute, tableName));
- }
- // expect no other rule
- routes = listIpRoutes(IP_RULE_V6, tableName.c_str());
- EXPECT_EQ(routes.size(), ARRAY_SIZE(LOCAL_EXCLUSION_ROUTES_V6));
-}
-
void expectVpnFallthroughWorks(android::net::INetd* netdService, bool bypassable, uid_t uid,
const TunInterface& fallthroughNetwork,
const TunInterface& vpnNetwork, int vpnNetId = TEST_NETID2,
@@ -3603,8 +3501,6 @@ void expectVpnFallthroughWorks(android::net::INetd* netdService, bool bypassable
// Check if local exclusion rule exists
expectVpnLocalExclusionRuleExists(fallthroughNetwork.name(), true);
- // Check if local exclusion route exists
- expectVpnLocalExclusionRouteExists(fallthroughNetwork.name());
// Expect fallthrough to default network
// The fwmark differs depending on whether the VPN is bypassable or not.
@@ -5044,3 +4940,60 @@ TEST_F(PerAppNetworkPermissionsTest, PermissionOnlyAffectsUid) {
EXPECT_EQ(connect(sock, (sockaddr*)&TEST_SOCKADDR_IN6, sizeof(TEST_SOCKADDR_IN6)), -1);
}
}
+
+class MDnsBinderTest : public ::testing::Test {
+ public:
+ MDnsBinderTest() {
+ sp<IServiceManager> sm = android::defaultServiceManager();
+ sp<IBinder> binder = sm->getService(String16("mdns"));
+ if (binder != nullptr) {
+ mMDns = android::interface_cast<IMDns>(binder);
+ }
+ }
+
+ void SetUp() override { ASSERT_NE(nullptr, mMDns.get()); }
+
+ void TearDown() override {}
+
+ protected:
+ sp<IMDns> mMDns;
+};
+
+class TestMDnsListener : public android::net::mdns::aidl::BnMDnsEventListener {
+ public:
+ Status onServiceRegistrationStatus(const RegistrationInfo& /* status */) override {
+ return Status::ok();
+ }
+ Status onServiceDiscoveryStatus(const DiscoveryInfo& /* status */) override {
+ return Status::ok();
+ }
+ Status onServiceResolutionStatus(const ResolutionInfo& /* status */) override {
+ return Status::ok();
+ }
+ Status onGettingServiceAddressStatus(const GetAddressInfo& /* status */) override {
+ return Status::ok();
+ }
+};
+
+TEST_F(MDnsBinderTest, EventListenerTest) {
+ // Register a null listener.
+ binder::Status status = mMDns->registerEventListener(nullptr);
+ EXPECT_FALSE(status.isOk());
+
+ // Unregister a null listener.
+ status = mMDns->unregisterEventListener(nullptr);
+ EXPECT_FALSE(status.isOk());
+
+ // Register the test listener.
+ android::sp<TestMDnsListener> testListener = new TestMDnsListener();
+ status = mMDns->registerEventListener(testListener);
+ EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
+
+ // Register the duplicated listener
+ status = mMDns->registerEventListener(testListener);
+ EXPECT_FALSE(status.isOk());
+
+ // Unregister the test listener
+ status = mMDns->unregisterEventListener(testListener);
+ EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
+}