Merge "remove SKIP_IF_BPF_NOT_SUPPORTED"
diff --git a/staticlibs/Android.bp b/staticlibs/Android.bp
index 63c8b4e..d8a397d 100644
--- a/staticlibs/Android.bp
+++ b/staticlibs/Android.bp
@@ -40,6 +40,7 @@
"device/com/android/net/module/util/NetworkMonitorUtils.java",
"device/com/android/net/module/util/PacketReader.java",
"device/com/android/net/module/util/SharedLog.java",
+ "device/com/android/net/module/util/SocketUtils.java",
// This library is used by system modules, for which the system health impact of Kotlin
// has not yet been evaluated. Annotations may need jarjar'ing.
// "src_devicecommon/**/*.kt",
diff --git a/staticlibs/device/com/android/net/module/util/SocketUtils.java b/staticlibs/device/com/android/net/module/util/SocketUtils.java
new file mode 100644
index 0000000..9878ea5
--- /dev/null
+++ b/staticlibs/device/com/android/net/module/util/SocketUtils.java
@@ -0,0 +1,58 @@
+/*
+ * 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.
+ */
+
+package com.android.net.module.util;
+
+import static android.net.util.SocketUtils.closeSocket;
+
+import android.annotation.NonNull;
+import android.system.NetlinkSocketAddress;
+
+import java.io.FileDescriptor;
+import java.io.IOException;
+import java.net.SocketAddress;
+
+/**
+ * Collection of utilities to interact with raw sockets.
+ *
+ * This class also provides utilities to interact with {@link android.net.util.SocketUtils}
+ * because it is in the API surface could not be simply move the frameworks/libs/net/
+ * to share with module.
+ *
+ * TODO: deprecate android.net.util.SocketUtils and replace with this class.
+ */
+public class SocketUtils {
+
+ /**
+ * Make a socket address to communicate with netlink.
+ */
+ @NonNull
+ public static SocketAddress makeNetlinkSocketAddress(int portId, int groupsMask) {
+ return new NetlinkSocketAddress(portId, groupsMask);
+ }
+
+ /**
+ * Close a socket, ignoring any exception while closing.
+ */
+ public static void closeSocketQuietly(FileDescriptor fd) {
+ try {
+ closeSocket(fd);
+ } catch (IOException ignored) {
+ }
+ }
+
+ private SocketUtils() {}
+}
diff --git a/staticlibs/device/com/android/net/module/util/ip/IpNeighborMonitor.java b/staticlibs/device/com/android/net/module/util/ip/IpNeighborMonitor.java
index 4a61794..e88e7f0 100644
--- a/staticlibs/device/com/android/net/module/util/ip/IpNeighborMonitor.java
+++ b/staticlibs/device/com/android/net/module/util/ip/IpNeighborMonitor.java
@@ -31,7 +31,7 @@
import com.android.net.module.util.SharedLog;
import com.android.net.module.util.netlink.NetlinkMessage;
-import com.android.net.module.util.netlink.NetlinkSocket;
+import com.android.net.module.util.netlink.NetlinkUtils;
import com.android.net.module.util.netlink.RtNetlinkNeighborMessage;
import com.android.net.module.util.netlink.StructNdMsg;
@@ -68,7 +68,7 @@
1, ip, StructNdMsg.NUD_PROBE, ifIndex, null);
try {
- NetlinkSocket.sendOneShotKernelMessage(NETLINK_ROUTE, msg);
+ NetlinkUtils.sendOneShotKernelMessage(NETLINK_ROUTE, msg);
} catch (ErrnoException e) {
Log.e(TAG, "Error " + msgSnippet + ": " + e);
return -e.errno;
diff --git a/staticlibs/device/com/android/net/module/util/ip/NetlinkMonitor.java b/staticlibs/device/com/android/net/module/util/ip/NetlinkMonitor.java
index 942aaf1..f882483 100644
--- a/staticlibs/device/com/android/net/module/util/ip/NetlinkMonitor.java
+++ b/staticlibs/device/com/android/net/module/util/ip/NetlinkMonitor.java
@@ -16,7 +16,6 @@
package com.android.net.module.util.ip;
-import static android.net.util.SocketUtils.makeNetlinkSocketAddress;
import static android.system.OsConstants.AF_NETLINK;
import static android.system.OsConstants.ENOBUFS;
import static android.system.OsConstants.SOCK_DGRAM;
@@ -24,10 +23,11 @@
import static android.system.OsConstants.SOL_SOCKET;
import static android.system.OsConstants.SO_RCVBUF;
+import static com.android.net.module.util.SocketUtils.closeSocketQuietly;
+import static com.android.net.module.util.SocketUtils.makeNetlinkSocketAddress;
import static com.android.net.module.util.netlink.NetlinkConstants.hexify;
import android.annotation.NonNull;
-import android.net.util.SocketUtils;
import android.os.Handler;
import android.os.SystemClock;
import android.system.ErrnoException;
@@ -38,10 +38,9 @@
import com.android.net.module.util.SharedLog;
import com.android.net.module.util.netlink.NetlinkErrorMessage;
import com.android.net.module.util.netlink.NetlinkMessage;
-import com.android.net.module.util.netlink.NetlinkSocket;
+import com.android.net.module.util.netlink.NetlinkUtils;
import java.io.FileDescriptor;
-import java.io.IOException;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
@@ -83,7 +82,7 @@
*/
public NetlinkMonitor(@NonNull Handler h, @NonNull SharedLog log, @NonNull String tag,
int family, int bindGroups, int sockRcvbufSize) {
- super(h, NetlinkSocket.DEFAULT_RECV_BUFSIZE);
+ super(h, NetlinkUtils.DEFAULT_RECV_BUFSIZE);
mLog = log.forSubComponent(tag);
mTag = tag;
mFamily = family;
@@ -110,7 +109,7 @@
}
}
Os.bind(fd, makeNetlinkSocketAddress(0, mBindGroups));
- NetlinkSocket.connectToKernel(fd);
+ NetlinkUtils.connectSocketToNetlink(fd);
if (DBG) {
final SocketAddress nlAddr = Os.getsockname(fd);
@@ -179,14 +178,6 @@
return true;
}
- // TODO: move NetworkStackUtils to frameworks/libs/net for NetworkStackUtils#closeSocketQuietly.
- private void closeSocketQuietly(FileDescriptor fd) {
- try {
- SocketUtils.closeSocket(fd);
- } catch (IOException ignored) {
- }
- }
-
/**
* Processes one netlink message. Must be overridden by subclasses.
* @param nlMsg the message to process.
diff --git a/staticlibs/device/com/android/net/module/util/netlink/InetDiagMessage.java b/staticlibs/device/com/android/net/module/util/netlink/InetDiagMessage.java
index eff1f25..5a180e7 100644
--- a/staticlibs/device/com/android/net/module/util/netlink/InetDiagMessage.java
+++ b/staticlibs/device/com/android/net/module/util/netlink/InetDiagMessage.java
@@ -19,11 +19,12 @@
import static android.os.Process.INVALID_UID;
import static android.system.OsConstants.AF_INET;
import static android.system.OsConstants.AF_INET6;
+import static android.system.OsConstants.IPPROTO_TCP;
import static android.system.OsConstants.IPPROTO_UDP;
import static android.system.OsConstants.NETLINK_INET_DIAG;
import static com.android.net.module.util.netlink.NetlinkConstants.SOCK_DIAG_BY_FAMILY;
-import static com.android.net.module.util.netlink.NetlinkSocket.DEFAULT_RECV_BUFSIZE;
+import static com.android.net.module.util.netlink.NetlinkUtils.DEFAULT_RECV_BUFSIZE;
import static com.android.net.module.util.netlink.StructNlMsgHdr.NLM_F_DUMP;
import static com.android.net.module.util.netlink.StructNlMsgHdr.NLM_F_REQUEST;
@@ -132,8 +133,8 @@
FileDescriptor fd)
throws ErrnoException, InterruptedIOException {
byte[] msg = inetDiagReqV2(protocol, local, remote, family, flags);
- NetlinkSocket.sendMessage(fd, msg, 0, msg.length, TIMEOUT_MS);
- ByteBuffer response = NetlinkSocket.recvMessage(fd, DEFAULT_RECV_BUFSIZE, TIMEOUT_MS);
+ NetlinkUtils.sendMessage(fd, msg, 0, msg.length, TIMEOUT_MS);
+ ByteBuffer response = NetlinkUtils.recvMessage(fd, DEFAULT_RECV_BUFSIZE, TIMEOUT_MS);
final NetlinkMessage nlMsg = NetlinkMessage.parse(response, NETLINK_INET_DIAG);
if (nlMsg == null) {
@@ -210,8 +211,8 @@
int uid = INVALID_UID;
FileDescriptor fd = null;
try {
- fd = NetlinkSocket.forProto(NETLINK_INET_DIAG);
- NetlinkSocket.connectToKernel(fd);
+ fd = NetlinkUtils.netlinkSocketForProto(NETLINK_INET_DIAG);
+ NetlinkUtils.connectSocketToNetlink(fd);
uid = lookupUid(protocol, local, remote, fd);
} catch (ErrnoException | SocketException | IllegalArgumentException
| InterruptedIOException e) {
@@ -228,6 +229,20 @@
return uid;
}
+ /**
+ * Construct an inet_diag_req_v2 message for querying alive TCP sockets from kernel.
+ */
+ public static byte[] buildInetDiagReqForAliveTcpSockets(int family) {
+ return inetDiagReqV2(IPPROTO_TCP,
+ null /* local addr */,
+ null /* remote addr */,
+ family,
+ (short) (StructNlMsgHdr.NLM_F_REQUEST | StructNlMsgHdr.NLM_F_DUMP) /* flag */,
+ 0 /* pad */,
+ 1 << NetlinkConstants.INET_DIAG_MEMINFO /* idiagExt */,
+ NetlinkUtils.TCP_MONITOR_STATE_FILTER);
+ }
+
@Override
public String toString() {
return "InetDiagMessage{ "
diff --git a/staticlibs/device/com/android/net/module/util/netlink/NetlinkSocket.java b/staticlibs/device/com/android/net/module/util/netlink/NetlinkSocket.java
deleted file mode 100644
index ec326dd..0000000
--- a/staticlibs/device/com/android/net/module/util/netlink/NetlinkSocket.java
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * Copyright (C) 2015 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.
- */
-
-package com.android.net.module.util.netlink;
-
-import static android.net.util.SocketUtils.makeNetlinkSocketAddress;
-import static android.system.OsConstants.AF_NETLINK;
-import static android.system.OsConstants.EIO;
-import static android.system.OsConstants.EPROTO;
-import static android.system.OsConstants.ETIMEDOUT;
-import static android.system.OsConstants.SOCK_DGRAM;
-import static android.system.OsConstants.SOL_SOCKET;
-import static android.system.OsConstants.SO_RCVBUF;
-import static android.system.OsConstants.SO_RCVTIMEO;
-import static android.system.OsConstants.SO_SNDTIMEO;
-
-import android.net.util.SocketUtils;
-import android.system.ErrnoException;
-import android.system.Os;
-import android.system.StructTimeval;
-import android.util.Log;
-
-import java.io.FileDescriptor;
-import java.io.IOException;
-import java.io.InterruptedIOException;
-import java.net.SocketException;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-
-/**
- * NetlinkSocket
- *
- * A small static class to assist with AF_NETLINK socket operations.
- *
- * @hide
- */
-public class NetlinkSocket {
- private static final String TAG = "NetlinkSocket";
- private static final long IO_TIMEOUT_MS = 300L;
-
- public static final int DEFAULT_RECV_BUFSIZE = 8 * 1024;
- public static final int SOCKET_RECV_BUFSIZE = 64 * 1024;
-
- /**
- * Send one netlink message to kernel via netlink socket.
- *
- * @param nlProto netlink protocol type.
- * @param msg the raw bytes of netlink message to be sent.
- */
- public static void sendOneShotKernelMessage(int nlProto, byte[] msg) throws ErrnoException {
- final String errPrefix = "Error in NetlinkSocket.sendOneShotKernelMessage";
- final FileDescriptor fd = forProto(nlProto);
-
- try {
- connectToKernel(fd);
- sendMessage(fd, msg, 0, msg.length, IO_TIMEOUT_MS);
- final ByteBuffer bytes = recvMessage(fd, DEFAULT_RECV_BUFSIZE, IO_TIMEOUT_MS);
- // recvMessage() guaranteed to not return null if it did not throw.
- final NetlinkMessage response = NetlinkMessage.parse(bytes, nlProto);
- if (response != null && response instanceof NetlinkErrorMessage
- && (((NetlinkErrorMessage) response).getNlMsgError() != null)) {
- final int errno = ((NetlinkErrorMessage) response).getNlMsgError().error;
- if (errno != 0) {
- // TODO: consider ignoring EINVAL (-22), which appears to be
- // normal when probing a neighbor for which the kernel does
- // not already have / no longer has a link layer address.
- Log.e(TAG, errPrefix + ", errmsg=" + response.toString());
- // Note: convert kernel errnos (negative) into userspace errnos (positive).
- throw new ErrnoException(response.toString(), Math.abs(errno));
- }
- } else {
- final String errmsg;
- if (response == null) {
- bytes.position(0);
- errmsg = "raw bytes: " + NetlinkConstants.hexify(bytes);
- } else {
- errmsg = response.toString();
- }
- Log.e(TAG, errPrefix + ", errmsg=" + errmsg);
- throw new ErrnoException(errmsg, EPROTO);
- }
- } catch (InterruptedIOException e) {
- Log.e(TAG, errPrefix, e);
- throw new ErrnoException(errPrefix, ETIMEDOUT, e);
- } catch (SocketException e) {
- Log.e(TAG, errPrefix, e);
- throw new ErrnoException(errPrefix, EIO, e);
- } finally {
- try {
- SocketUtils.closeSocket(fd);
- } catch (IOException e) {
- // Nothing we can do here
- }
- }
- }
-
- /**
- * Create netlink socket with the given netlink protocol type.
- *
- * @return fd the fileDescriptor of the socket.
- * Throw ErrnoException if the exception is thrown.
- */
- public static FileDescriptor forProto(int nlProto) throws ErrnoException {
- final FileDescriptor fd = Os.socket(AF_NETLINK, SOCK_DGRAM, nlProto);
- Os.setsockoptInt(fd, SOL_SOCKET, SO_RCVBUF, SOCKET_RECV_BUFSIZE);
- return fd;
- }
-
- /**
- * Connect to kernel via netlink socket.
- *
- * Throw ErrnoException, SocketException if the exception is thrown.
- */
- public static void connectToKernel(FileDescriptor fd) throws ErrnoException, SocketException {
- Os.connect(fd, makeNetlinkSocketAddress(0, 0));
- }
-
- private static void checkTimeout(long timeoutMs) {
- if (timeoutMs < 0) {
- throw new IllegalArgumentException("Negative timeouts not permitted");
- }
- }
-
- /**
- * Wait up to |timeoutMs| (or until underlying socket error) for a
- * netlink message of at most |bufsize| size.
- *
- * Multi-threaded calls with different timeouts will cause unexpected results.
- */
- public static ByteBuffer recvMessage(FileDescriptor fd, int bufsize, long timeoutMs)
- throws ErrnoException, IllegalArgumentException, InterruptedIOException {
- checkTimeout(timeoutMs);
-
- Os.setsockoptTimeval(fd, SOL_SOCKET, SO_RCVTIMEO, StructTimeval.fromMillis(timeoutMs));
-
- ByteBuffer byteBuffer = ByteBuffer.allocate(bufsize);
- int length = Os.read(fd, byteBuffer);
- if (length == bufsize) {
- Log.w(TAG, "maximum read");
- }
- byteBuffer.position(0);
- byteBuffer.limit(length);
- byteBuffer.order(ByteOrder.nativeOrder());
- return byteBuffer;
- }
-
- /**
- * Send a message to a peer to which this socket has previously connected,
- * waiting at most |timeoutMs| milliseconds for the send to complete.
- *
- * Multi-threaded calls with different timeouts will cause unexpected results.
- */
- public static int sendMessage(
- FileDescriptor fd, byte[] bytes, int offset, int count, long timeoutMs)
- throws ErrnoException, IllegalArgumentException, InterruptedIOException {
- checkTimeout(timeoutMs);
- Os.setsockoptTimeval(fd, SOL_SOCKET, SO_SNDTIMEO, StructTimeval.fromMillis(timeoutMs));
- return Os.write(fd, bytes, offset, count);
- }
-}
diff --git a/staticlibs/device/com/android/net/module/util/netlink/NetlinkUtils.java b/staticlibs/device/com/android/net/module/util/netlink/NetlinkUtils.java
index 34c468a..ae16cf8 100644
--- a/staticlibs/device/com/android/net/module/util/netlink/NetlinkUtils.java
+++ b/staticlibs/device/com/android/net/module/util/netlink/NetlinkUtils.java
@@ -16,13 +16,40 @@
package com.android.net.module.util.netlink;
-import static android.system.OsConstants.IPPROTO_TCP;
+import static android.net.util.SocketUtils.makeNetlinkSocketAddress;
+import static android.system.OsConstants.AF_NETLINK;
+import static android.system.OsConstants.EIO;
+import static android.system.OsConstants.EPROTO;
+import static android.system.OsConstants.ETIMEDOUT;
+import static android.system.OsConstants.NETLINK_INET_DIAG;
+import static android.system.OsConstants.SOCK_CLOEXEC;
+import static android.system.OsConstants.SOCK_DGRAM;
+import static android.system.OsConstants.SOL_SOCKET;
+import static android.system.OsConstants.SO_RCVBUF;
+import static android.system.OsConstants.SO_RCVTIMEO;
+import static android.system.OsConstants.SO_SNDTIMEO;
+
+import android.net.util.SocketUtils;
+import android.system.ErrnoException;
+import android.system.Os;
+import android.system.StructTimeval;
+import android.util.Log;
+
+import androidx.annotation.NonNull;
+
+import java.io.FileDescriptor;
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.SocketException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
/**
- * Utilities for netlink related class.
+ * Utilities for netlink related class that may not be able to fit into a specific class.
* @hide
*/
public class NetlinkUtils {
+ private static final String TAG = "NetlinkUtils";
/** Corresponds to enum from bionic/libc/include/netinet/tcp.h. */
private static final int TCP_ESTABLISHED = 1;
private static final int TCP_SYN_SENT = 2;
@@ -31,17 +58,155 @@
public static final int TCP_MONITOR_STATE_FILTER =
(1 << TCP_ESTABLISHED) | (1 << TCP_SYN_SENT) | (1 << TCP_SYN_RECV);
+ public static final int UNKNOWN_MARK = 0xffffffff;
+ public static final int NULL_MASK = 0;
+
+ // Initial mark value corresponds to the initValue in system/netd/include/Fwmark.h.
+ public static final int INIT_MARK_VALUE = 0;
+ // Corresponds to enum definition in bionic/libc/kernel/uapi/linux/inet_diag.h
+ public static final int INET_DIAG_INFO = 2;
+ public static final int INET_DIAG_MARK = 15;
+
+ public static final long IO_TIMEOUT_MS = 300L;
+
+ public static final int DEFAULT_RECV_BUFSIZE = 8 * 1024;
+ public static final int SOCKET_RECV_BUFSIZE = 64 * 1024;
+
/**
- * Construct an inet_diag_req_v2 message for querying alive TCP sockets from kernel.
+ * Return whether the input ByteBuffer contains enough remaining bytes for
+ * {@code StructNlMsgHdr}.
*/
- public static byte[] buildInetDiagReqForAliveTcpSockets(int family) {
- return InetDiagMessage.inetDiagReqV2(IPPROTO_TCP,
- null /* local addr */,
- null /* remote addr */,
- family,
- (short) (StructNlMsgHdr.NLM_F_REQUEST | StructNlMsgHdr.NLM_F_DUMP) /* flag */,
- 0 /* pad */,
- 1 << NetlinkConstants.INET_DIAG_MEMINFO /* idiagExt */,
- TCP_MONITOR_STATE_FILTER);
+ public static boolean enoughBytesRemainForValidNlMsg(@NonNull final ByteBuffer bytes) {
+ return bytes.remaining() >= StructNlMsgHdr.STRUCT_SIZE;
}
+
+ /**
+ * Send one netlink message to kernel via netlink socket.
+ *
+ * @param nlProto netlink protocol type.
+ * @param msg the raw bytes of netlink message to be sent.
+ */
+ public static void sendOneShotKernelMessage(int nlProto, byte[] msg) throws ErrnoException {
+ final String errPrefix = "Error in NetlinkSocket.sendOneShotKernelMessage";
+ final FileDescriptor fd = netlinkSocketForProto(nlProto);
+
+ try {
+ connectSocketToNetlink(fd);
+ sendMessage(fd, msg, 0, msg.length, IO_TIMEOUT_MS);
+ final ByteBuffer bytes = recvMessage(fd, DEFAULT_RECV_BUFSIZE, IO_TIMEOUT_MS);
+ // recvMessage() guaranteed to not return null if it did not throw.
+ final NetlinkMessage response = NetlinkMessage.parse(bytes, nlProto);
+ if (response != null && response instanceof NetlinkErrorMessage
+ && (((NetlinkErrorMessage) response).getNlMsgError() != null)) {
+ final int errno = ((NetlinkErrorMessage) response).getNlMsgError().error;
+ if (errno != 0) {
+ // TODO: consider ignoring EINVAL (-22), which appears to be
+ // normal when probing a neighbor for which the kernel does
+ // not already have / no longer has a link layer address.
+ Log.e(TAG, errPrefix + ", errmsg=" + response.toString());
+ // Note: convert kernel errnos (negative) into userspace errnos (positive).
+ throw new ErrnoException(response.toString(), Math.abs(errno));
+ }
+ } else {
+ final String errmsg;
+ if (response == null) {
+ bytes.position(0);
+ errmsg = "raw bytes: " + NetlinkConstants.hexify(bytes);
+ } else {
+ errmsg = response.toString();
+ }
+ Log.e(TAG, errPrefix + ", errmsg=" + errmsg);
+ throw new ErrnoException(errmsg, EPROTO);
+ }
+ } catch (InterruptedIOException e) {
+ Log.e(TAG, errPrefix, e);
+ throw new ErrnoException(errPrefix, ETIMEDOUT, e);
+ } catch (SocketException e) {
+ Log.e(TAG, errPrefix, e);
+ throw new ErrnoException(errPrefix, EIO, e);
+ } finally {
+ try {
+ SocketUtils.closeSocket(fd);
+ } catch (IOException e) {
+ // Nothing we can do here
+ }
+ }
+ }
+
+ /**
+ * Create netlink socket with the given netlink protocol type.
+ *
+ * @return fd the fileDescriptor of the socket.
+ * @throws ErrnoException if the FileDescriptor not connect to be created successfully
+ */
+ public static FileDescriptor netlinkSocketForProto(int nlProto) throws ErrnoException {
+ final FileDescriptor fd = Os.socket(AF_NETLINK, SOCK_DGRAM, nlProto);
+ Os.setsockoptInt(fd, SOL_SOCKET, SO_RCVBUF, SOCKET_RECV_BUFSIZE);
+ return fd;
+ }
+
+ /**
+ * Construct a netlink inet_diag socket.
+ */
+ public static FileDescriptor createNetLinkInetDiagSocket() throws ErrnoException {
+ return Os.socket(AF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_INET_DIAG);
+ }
+
+ /**
+ * Connect the given file descriptor to the Netlink interface to the kernel.
+ *
+ * The fd must be a SOCK_DGRAM socket : create it with {@link #netlinkSocketForProto}
+ *
+ * @throws ErrnoException if the {@code fd} could not connect to kernel successfully
+ * @throws SocketException if there is an error accessing a socket.
+ */
+ public static void connectSocketToNetlink(FileDescriptor fd)
+ throws ErrnoException, SocketException {
+ Os.connect(fd, makeNetlinkSocketAddress(0, 0));
+ }
+
+ private static void checkTimeout(long timeoutMs) {
+ if (timeoutMs < 0) {
+ throw new IllegalArgumentException("Negative timeouts not permitted");
+ }
+ }
+
+ /**
+ * Wait up to |timeoutMs| (or until underlying socket error) for a
+ * netlink message of at most |bufsize| size.
+ *
+ * Multi-threaded calls with different timeouts will cause unexpected results.
+ */
+ public static ByteBuffer recvMessage(FileDescriptor fd, int bufsize, long timeoutMs)
+ throws ErrnoException, IllegalArgumentException, InterruptedIOException {
+ checkTimeout(timeoutMs);
+
+ Os.setsockoptTimeval(fd, SOL_SOCKET, SO_RCVTIMEO, StructTimeval.fromMillis(timeoutMs));
+
+ final ByteBuffer byteBuffer = ByteBuffer.allocate(bufsize);
+ final int length = Os.read(fd, byteBuffer);
+ if (length == bufsize) {
+ Log.w(TAG, "maximum read");
+ }
+ byteBuffer.position(0);
+ byteBuffer.limit(length);
+ byteBuffer.order(ByteOrder.nativeOrder());
+ return byteBuffer;
+ }
+
+ /**
+ * Send a message to a peer to which this socket has previously connected.
+ *
+ * This waits at most |timeoutMs| milliseconds for the send to complete, will get the exception
+ * if it times out.
+ */
+ public static int sendMessage(
+ FileDescriptor fd, byte[] bytes, int offset, int count, long timeoutMs)
+ throws ErrnoException, IllegalArgumentException, InterruptedIOException {
+ checkTimeout(timeoutMs);
+ Os.setsockoptTimeval(fd, SOL_SOCKET, SO_SNDTIMEO, StructTimeval.fromMillis(timeoutMs));
+ return Os.write(fd, bytes, offset, count);
+ }
+
+ private NetlinkUtils() {}
}
diff --git a/staticlibs/tests/unit/src/com/android/net/module/util/ip/ConntrackMonitorTest.java b/staticlibs/tests/unit/src/com/android/net/module/util/ip/ConntrackMonitorTest.java
index 99d8f07..7ee376c 100644
--- a/staticlibs/tests/unit/src/com/android/net/module/util/ip/ConntrackMonitorTest.java
+++ b/staticlibs/tests/unit/src/com/android/net/module/util/ip/ConntrackMonitorTest.java
@@ -47,7 +47,7 @@
import com.android.net.module.util.SharedLog;
import com.android.net.module.util.ip.ConntrackMonitor.ConntrackEvent;
import com.android.net.module.util.netlink.NetlinkConstants;
-import com.android.net.module.util.netlink.NetlinkSocket;
+import com.android.net.module.util.netlink.NetlinkUtils;
import libcore.util.HexEncoding;
@@ -104,7 +104,7 @@
private void sendMessage(byte[] msg) {
mHandler.post(() -> {
try {
- NetlinkSocket.sendMessage(mWriteFd, msg, 0 /* offset */, msg.length,
+ NetlinkUtils.sendMessage(mWriteFd, msg, 0 /* offset */, msg.length,
TIMEOUT_MS);
} catch (ErrnoException | InterruptedIOException e) {
fail("Unable to send netfilter message: " + e);
diff --git a/staticlibs/tests/unit/src/com/android/net/module/util/netlink/NetlinkSocketTest.java b/staticlibs/tests/unit/src/com/android/net/module/util/netlink/NetlinkUtilsTest.java
similarity index 89%
rename from staticlibs/tests/unit/src/com/android/net/module/util/netlink/NetlinkSocketTest.java
rename to staticlibs/tests/unit/src/com/android/net/module/util/netlink/NetlinkUtilsTest.java
index f4073b6..7a1639a 100644
--- a/staticlibs/tests/unit/src/com/android/net/module/util/netlink/NetlinkSocketTest.java
+++ b/staticlibs/tests/unit/src/com/android/net/module/util/netlink/NetlinkUtilsTest.java
@@ -22,7 +22,7 @@
import static android.system.OsConstants.EACCES;
import static android.system.OsConstants.NETLINK_ROUTE;
-import static com.android.net.module.util.netlink.NetlinkSocket.DEFAULT_RECV_BUFSIZE;
+import static com.android.net.module.util.netlink.NetlinkUtils.DEFAULT_RECV_BUFSIZE;
import static com.android.net.module.util.netlink.StructNlMsgHdr.NLM_F_DUMP;
import static com.android.net.module.util.netlink.StructNlMsgHdr.NLM_F_REQUEST;
@@ -42,8 +42,6 @@
import com.android.modules.utils.build.SdkLevel;
import com.android.net.module.util.Struct;
-import com.android.net.module.util.Struct.Field;
-import com.android.net.module.util.Struct.Type;
import libcore.io.IoUtils;
@@ -56,17 +54,17 @@
@RunWith(AndroidJUnit4.class)
@SmallTest
-public class NetlinkSocketTest {
- private static final String TAG = "NetlinkSocketTest";
+public class NetlinkUtilsTest {
+ private static final String TAG = "NetlinkUitlsTest";
private static final int TEST_SEQNO = 5;
private static final int TEST_TIMEOUT_MS = 500;
@Test
public void testGetNeighborsQuery() throws Exception {
- final FileDescriptor fd = NetlinkSocket.forProto(NETLINK_ROUTE);
+ final FileDescriptor fd = NetlinkUtils.netlinkSocketForProto(NETLINK_ROUTE);
assertNotNull(fd);
- NetlinkSocket.connectToKernel(fd);
+ NetlinkUtils.connectSocketToNetlink(fd);
final NetlinkSocketAddress localAddr = (NetlinkSocketAddress) Os.getsockname(fd);
assertNotNull(localAddr);
@@ -85,7 +83,7 @@
// Apps targeting an SDK version > S are not allowed to send RTM_GETNEIGH{TBL} messages
if (SdkLevel.isAtLeastT() && targetSdk > 31) {
try {
- NetlinkSocket.sendMessage(fd, req, 0, req.length, TEST_TIMEOUT_MS);
+ NetlinkUtils.sendMessage(fd, req, 0, req.length, TEST_TIMEOUT_MS);
fail("RTM_GETNEIGH is not allowed for apps targeting SDK > 31 on T+ platforms,"
+ " target SDK version: " + targetSdk);
} catch (ErrnoException e) {
@@ -97,14 +95,14 @@
// Check that apps targeting lower API levels / running on older platforms succeed
assertEquals(req.length,
- NetlinkSocket.sendMessage(fd, req, 0, req.length, TEST_TIMEOUT_MS));
+ NetlinkUtils.sendMessage(fd, req, 0, req.length, TEST_TIMEOUT_MS));
int neighMessageCount = 0;
int doneMessageCount = 0;
while (doneMessageCount == 0) {
ByteBuffer response =
- NetlinkSocket.recvMessage(fd, DEFAULT_RECV_BUFSIZE, TEST_TIMEOUT_MS);
+ NetlinkUtils.recvMessage(fd, DEFAULT_RECV_BUFSIZE, TEST_TIMEOUT_MS);
assertNotNull(response);
assertTrue(StructNlMsgHdr.STRUCT_SIZE <= response.limit());
assertEquals(0, response.position());
@@ -141,10 +139,10 @@
@Test
public void testBasicWorkingGetAddrQuery() throws Exception {
- final FileDescriptor fd = NetlinkSocket.forProto(NETLINK_ROUTE);
+ final FileDescriptor fd = NetlinkUtils.netlinkSocketForProto(NETLINK_ROUTE);
assertNotNull(fd);
- NetlinkSocket.connectToKernel(fd);
+ NetlinkUtils.connectSocketToNetlink(fd);
final NetlinkSocketAddress localAddr = (NetlinkSocketAddress) Os.getsockname(fd);
assertNotNull(localAddr);
@@ -156,12 +154,12 @@
assertNotNull(req);
final long timeout = 500;
- assertEquals(req.length, NetlinkSocket.sendMessage(fd, req, 0, req.length, timeout));
+ assertEquals(req.length, NetlinkUtils.sendMessage(fd, req, 0, req.length, timeout));
int addrMessageCount = 0;
while (true) {
- ByteBuffer response = NetlinkSocket.recvMessage(fd, DEFAULT_RECV_BUFSIZE, timeout);
+ ByteBuffer response = NetlinkUtils.recvMessage(fd, DEFAULT_RECV_BUFSIZE, timeout);
assertNotNull(response);
assertTrue(StructNlMsgHdr.STRUCT_SIZE <= response.limit());
assertEquals(0, response.position());
diff --git a/staticlibs/tests/unit/src/com/android/testutils/TestDnsServerTest.kt b/staticlibs/tests/unit/src/com/android/testutils/TestDnsServerTest.kt
new file mode 100644
index 0000000..6f4587b
--- /dev/null
+++ b/staticlibs/tests/unit/src/com/android/testutils/TestDnsServerTest.kt
@@ -0,0 +1,122 @@
+/*
+ * 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.
+ */
+
+package com.android.testutils
+
+import android.net.DnsResolver.CLASS_IN
+import android.net.DnsResolver.TYPE_AAAA
+import android.net.Network
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.net.module.util.DnsPacket
+import com.android.net.module.util.DnsPacket.DnsRecord
+import libcore.net.InetAddressUtils
+import org.junit.After
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.Mockito
+import java.net.DatagramPacket
+import java.net.DatagramSocket
+import java.net.InetAddress
+import java.net.InetSocketAddress
+import kotlin.test.assertEquals
+import kotlin.test.assertFailsWith
+import kotlin.test.assertFalse
+import kotlin.test.assertTrue
+
+val TEST_V6_ADDR = InetAddressUtils.parseNumericAddress("2001:db8::3")
+const val TEST_DOMAIN = "hello.example.com"
+
+@RunWith(AndroidJUnit4::class)
+@SmallTest
+class TestDnsServerTest {
+ private val network = Mockito.mock(Network::class.java)
+ private val localAddr = InetSocketAddress(InetAddress.getLocalHost(), 0 /* port */)
+ private val testServer: TestDnsServer = TestDnsServer(network, localAddr)
+
+ @After
+ fun tearDown() {
+ if (testServer.isAlive) testServer.stop()
+ }
+
+ @Test
+ fun testStartStop() {
+ repeat(100) {
+ val server = TestDnsServer(network, localAddr)
+ server.start()
+ assertTrue(server.isAlive)
+ server.stop()
+ assertFalse(server.isAlive)
+ }
+
+ // Test illegal start/stop.
+ assertFailsWith<IllegalStateException> { testServer.stop() }
+ testServer.start()
+ assertTrue(testServer.isAlive)
+ assertFailsWith<IllegalStateException> { testServer.start() }
+ testServer.stop()
+ assertFalse(testServer.isAlive)
+ assertFailsWith<IllegalStateException> { testServer.stop() }
+ // TestDnsServer rejects start after stop.
+ assertFailsWith<IllegalStateException> { testServer.start() }
+ }
+
+ @Test
+ fun testHandleDnsQuery() {
+ testServer.setAnswer(TEST_DOMAIN, listOf(TEST_V6_ADDR))
+ testServer.start()
+
+ // Mock query and send it to the test server.
+ val queryHeader = DnsPacket.DnsHeader(0xbeef /* id */,
+ 0x0 /* flag */, 1 /* qcount */, 0 /* ancount */)
+ val qlist = listOf(DnsRecord.makeQuestion(TEST_DOMAIN, TYPE_AAAA, CLASS_IN))
+ val queryPacket = TestDnsServer.DnsQueryPacket(queryHeader, qlist, emptyList())
+ val response = resolve(queryPacket, testServer.port)
+
+ // Verify expected answer packet. Set QR bit of flag to 1 for response packet
+ // according to RFC 1035 section 4.1.1.
+ val answerHeader = DnsPacket.DnsHeader(0xbeef,
+ 1 shl 15 /* flag */, 1 /* qcount */, 1 /* ancount */)
+ val alist = listOf(DnsRecord.makeAOrAAAARecord(DnsPacket.ANSECTION, TEST_DOMAIN,
+ CLASS_IN, DEFAULT_TTL_S, TEST_V6_ADDR))
+ val expectedAnswerPacket = TestDnsServer.DnsAnswerPacket(answerHeader, qlist, alist)
+ assertEquals(expectedAnswerPacket, response)
+
+ // Clean up the server in tearDown.
+ }
+
+ private fun resolve(queryDnsPacket: DnsPacket, serverPort: Int): TestDnsServer.DnsAnswerPacket {
+ val bytes = queryDnsPacket.bytes
+ // Create a new client socket, the socket will be bound to a
+ // random port other than the server port.
+ val socket = DatagramSocket(localAddr).also { it.soTimeout = 100 }
+ val queryPacket = DatagramPacket(bytes, bytes.size, localAddr.address, serverPort)
+
+ // Send query and wait for the reply.
+ socket.send(queryPacket)
+ val buffer = ByteArray(MAX_BUF_SIZE)
+ val reply = DatagramPacket(buffer, buffer.size)
+ socket.receive(reply)
+ return TestDnsServer.DnsAnswerPacket(reply.data)
+ }
+
+ // TODO: Add more tests, which includes:
+ // * Empty question RR packet (or more unexpected states)
+ // * No answer found (setAnswer empty list at L.78)
+ // * Test one or multi A record(s)
+ // * Test multi AAAA records
+ // * Test CNAME records
+}
diff --git a/staticlibs/testutils/devicetests/com/android/testutils/DnsAnswerProvider.kt b/staticlibs/testutils/devicetests/com/android/testutils/DnsAnswerProvider.kt
new file mode 100644
index 0000000..6a804bf
--- /dev/null
+++ b/staticlibs/testutils/devicetests/com/android/testutils/DnsAnswerProvider.kt
@@ -0,0 +1,65 @@
+/*
+ * 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.
+ */
+
+package com.android.testutils
+
+import android.net.DnsResolver.CLASS_IN
+import com.android.net.module.util.DnsPacket
+import com.android.net.module.util.DnsPacket.ANSECTION
+import java.net.InetAddress
+import java.util.concurrent.ConcurrentHashMap
+
+const val DEFAULT_TTL_S = 5L
+
+/**
+ * Helper class to store the mapping of DNS queries.
+ *
+ * DnsAnswerProvider is built atop a ConcurrentHashMap and as such it provides the same
+ * guarantees as ConcurrentHashMap between writing and reading elements. Specifically :
+ * - Setting an answer happens-before reading the same answer.
+ * - Callers can read and write concurrently from DnsAnswerProvider and expect no
+ * ConcurrentModificationException.
+ * Freshness of the answers depends on ordering of the threads ; if callers need a
+ * freshness guarantee, they need to provide the happens-before relationship from a
+ * write that they want to observe to the read that they need to be observed.
+ */
+class DnsAnswerProvider {
+ private val mDnsKeyToRecords = ConcurrentHashMap<String, List<DnsPacket.DnsRecord>>()
+
+ /**
+ * Get answer for the specified hostname.
+ *
+ * @param query the target hostname.
+ * @param type type of record, could be A or AAAA.
+ *
+ * @return list of [DnsPacket.DnsRecord] associated to the query. Empty if no record matches.
+ */
+ fun getAnswer(query: String, type: Int) = mDnsKeyToRecords[query]
+ .orEmpty().filter { it.nsType == type }
+
+ /** Set answer for the specified {@code query}.
+ *
+ * @param query the target hostname
+ * @param addresses [List<InetAddress>] which could be used to generate multiple A or AAAA
+ * RRs with the corresponding addresses.
+ */
+ fun setAnswer(query: String, hosts: List<InetAddress>) = mDnsKeyToRecords.put(query, hosts.map {
+ DnsPacket.DnsRecord.makeAOrAAAARecord(ANSECTION, query, CLASS_IN, DEFAULT_TTL_S, it)
+ })
+
+ fun clearAnswer(query: String) = mDnsKeyToRecords.remove(query)
+ fun clearAll() = mDnsKeyToRecords.clear()
+}
\ No newline at end of file
diff --git a/staticlibs/testutils/devicetests/com/android/testutils/TestDnsServer.kt b/staticlibs/testutils/devicetests/com/android/testutils/TestDnsServer.kt
new file mode 100644
index 0000000..e1b771b
--- /dev/null
+++ b/staticlibs/testutils/devicetests/com/android/testutils/TestDnsServer.kt
@@ -0,0 +1,173 @@
+/*
+ * 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.
+ */
+
+package com.android.testutils
+
+import android.net.Network
+import android.util.Log
+import com.android.internal.annotations.GuardedBy
+import com.android.internal.annotations.VisibleForTesting
+import com.android.internal.annotations.VisibleForTesting.Visibility.PRIVATE
+import com.android.net.module.util.DnsPacket
+import java.net.DatagramPacket
+import java.net.DatagramSocket
+import java.net.InetAddress
+import java.net.InetSocketAddress
+import java.net.SocketAddress
+import java.net.SocketException
+import java.util.ArrayList
+
+private const val TAG = "TestDnsServer"
+private const val VDBG = true
+@VisibleForTesting(visibility = PRIVATE)
+const val MAX_BUF_SIZE = 8192
+
+/**
+ * A simple implementation of Dns Server that can be bound on specific address and Network.
+ *
+ * The caller should use start() to make the server start a new thread to receive DNS queries
+ * on the bound address, [isAlive] to check status, and stop() for stopping.
+ * The server allows user to manipulate the records to be answered through
+ * [setAnswer] at runtime.
+ *
+ * This server runs on its own thread. Please make sure writing the query to the socket
+ * happens-after using [setAnswer] to guarantee the correct answer is returned. If possible,
+ * use [setAnswer] before calling [start] for simplicity.
+ */
+class TestDnsServer(network: Network, addr: InetSocketAddress) {
+ enum class Status {
+ NOT_STARTED, STARTED, STOPPED
+ }
+ @GuardedBy("thread")
+ private var status: Status = Status.NOT_STARTED
+ private val thread = ReceivingThread()
+ private val socket = DatagramSocket(addr).also { network.bindSocket(it) }
+ private val ansProvider = DnsAnswerProvider()
+
+ // The buffer to store the received packet. They are being reused for
+ // efficiency and it's fine because they are only ever accessed
+ // on the server thread in a sequential manner.
+ private val buffer = ByteArray(MAX_BUF_SIZE)
+ private val packet = DatagramPacket(buffer, buffer.size)
+
+ fun setAnswer(hostname: String, answer: List<InetAddress>) =
+ ansProvider.setAnswer(hostname, answer)
+
+ private fun processPacket() {
+ // Blocking read and try construct a DnsQueryPacket object.
+ socket.receive(packet)
+ val q = DnsQueryPacket(packet.data)
+ handleDnsQuery(q, packet.socketAddress)
+ }
+
+ // TODO: Add support to reply some error with a DNS reply packet with failure RCODE.
+ private fun handleDnsQuery(q: DnsQueryPacket, src: SocketAddress) {
+ val queryRecords = q.queryRecords
+ if (queryRecords.size != 1) {
+ throw IllegalArgumentException(
+ "Expected one dns query record but got ${queryRecords.size}"
+ )
+ }
+ val answerRecords = queryRecords[0].let { ansProvider.getAnswer(it.dName, it.nsType) }
+
+ if (VDBG) {
+ Log.v(TAG, "handleDnsPacket: " +
+ queryRecords.map { "${it.dName},${it.nsType}" }.joinToString() +
+ " ansCount=${answerRecords.size} socketAddress=$src")
+ }
+
+ val bytes = q.getAnswerPacket(answerRecords).bytes
+ val reply = DatagramPacket(bytes, bytes.size, src)
+ socket.send(reply)
+ }
+
+ fun start() {
+ synchronized(thread) {
+ if (status != Status.NOT_STARTED) {
+ throw IllegalStateException("unexpected status: $status")
+ }
+ thread.start()
+ status = Status.STARTED
+ }
+ }
+ fun stop() {
+ synchronized(thread) {
+ if (status != Status.STARTED) {
+ throw IllegalStateException("unexpected status: $status")
+ }
+ // The thread needs to be interrupted before closing the socket to prevent a data
+ // race where the thread tries to read from the socket while it's being closed.
+ // DatagramSocket is not thread-safe and running both concurrently can end up in
+ // getPort() returning -1 after it's been checked not to, resulting in a crash by
+ // IllegalArgumentException inside the DatagramSocket implementation.
+ thread.interrupt()
+ socket.close()
+ thread.join()
+ status = Status.STOPPED
+ }
+ }
+ val isAlive get() = thread.isAlive
+ val port get() = socket.localPort
+
+ inner class ReceivingThread : Thread() {
+ override fun run() {
+ while (!interrupted() && !socket.isClosed) {
+ try {
+ processPacket()
+ } catch (e: InterruptedException) {
+ // The caller terminated the server, exit.
+ break
+ } catch (e: SocketException) {
+ // The caller terminated the server, exit.
+ break
+ }
+ }
+ Log.i(TAG, "exiting socket={$socket}")
+ }
+ }
+
+ @VisibleForTesting(visibility = PRIVATE)
+ class DnsQueryPacket : DnsPacket {
+ constructor(data: ByteArray) : super(data)
+ constructor(header: DnsHeader, qd: List<DnsRecord>, an: List<DnsRecord>) :
+ super(header, qd, an)
+
+ init {
+ if (mHeader.isResponse) {
+ throw ParseException("Not a query packet")
+ }
+ }
+
+ val queryRecords: List<DnsRecord>
+ get() = mRecords[QDSECTION]
+
+ fun getAnswerPacket(ar: List<DnsRecord>): DnsAnswerPacket {
+ // Set QR bit of flag to 1 for response packet according to RFC 1035 section 4.1.1.
+ val flags = 1 shl 15
+ val qr = ArrayList(mRecords[QDSECTION])
+ // Copy the query packet header id to the answer packet as RFC 1035 section 4.1.1.
+ val header = DnsHeader(mHeader.id, flags, qr.size, ar.size)
+ return DnsAnswerPacket(header, qr, ar)
+ }
+ }
+
+ class DnsAnswerPacket : DnsPacket {
+ constructor(header: DnsHeader, qr: List<DnsRecord>, ar: List<DnsRecord>) :
+ super(header, qr, ar)
+ @VisibleForTesting(visibility = PRIVATE)
+ constructor(bytes: ByteArray) : super(bytes)
+ }
+}