Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 2a0b4913 authored by Remi NGUYEN VAN's avatar Remi NGUYEN VAN Committed by Automerger Merge Worker
Browse files

Add tests for IpReachabilityMonitor am: 5f3bb6d0

Change-Id: I4e420dcf03caf4557920947e0ca32c789cfba8c1
parents 692fe8d8 5f3bb6d0
Loading
Loading
Loading
Loading
+9 −2
Original line number Diff line number Diff line
@@ -27,6 +27,7 @@ import android.system.OsConstants;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;

import java.io.FileDescriptor;
import java.io.IOException;
@@ -92,6 +93,12 @@ public abstract class FdEventsReader<BufferType> {
        mBuffer = buffer;
    }

    @VisibleForTesting
    @NonNull
    protected MessageQueue getMessageQueue() {
        return mQueue;
    }

    /** Start this FdEventsReader. */
    public boolean start() {
        if (!onCorrectThread()) {
@@ -185,7 +192,7 @@ public abstract class FdEventsReader<BufferType> {

        if (mFd == null) return false;

        mQueue.addOnFileDescriptorEventListener(
        getMessageQueue().addOnFileDescriptorEventListener(
                mFd,
                FD_EVENTS,
                (fd, events) -> {
@@ -247,7 +254,7 @@ public abstract class FdEventsReader<BufferType> {
    private void unregisterAndDestroyFd() {
        if (mFd == null) return;

        mQueue.removeOnFileDescriptorEventListener(mFd);
        getMessageQueue().removeOnFileDescriptorEventListener(mFd);
        closeFd(mFd);
        mFd = null;
        onStop();
+9 −2
Original line number Diff line number Diff line
@@ -27,6 +27,7 @@ import android.net.INetd;
import android.net.LinkProperties;
import android.net.RouteInfo;
import android.net.ip.IpNeighborMonitor.NeighborEvent;
import android.net.ip.IpNeighborMonitor.NeighborEventConsumer;
import android.net.metrics.IpConnectivityLog;
import android.net.metrics.IpReachabilityEvent;
import android.net.netlink.StructNdMsg;
@@ -154,11 +155,12 @@ public class IpReachabilityMonitor {
    }

    /**
     * Encapsulates IpReachabilityMonitor depencencies on systems that hinder unit testing.
     * Encapsulates IpReachabilityMonitor dependencies on systems that hinder unit testing.
     * TODO: consider also wrapping MultinetworkPolicyTracker in this interface.
     */
    interface Dependencies {
        void acquireWakeLock(long durationMs);
        IpNeighborMonitor makeIpNeighborMonitor(Handler h, SharedLog log, NeighborEventConsumer cb);

        static Dependencies makeDefault(Context context, String iface) {
            final String lockName = TAG + "." + iface;
@@ -169,6 +171,11 @@ public class IpReachabilityMonitor {
                public void acquireWakeLock(long durationMs) {
                    lock.acquire(durationMs);
                }

                public IpNeighborMonitor makeIpNeighborMonitor(Handler h, SharedLog log,
                        NeighborEventConsumer cb) {
                    return new IpNeighborMonitor(h, log, cb);
                }
            };
        }
    }
@@ -223,7 +230,7 @@ public class IpReachabilityMonitor {
        }
        setNeighbourParametersForSteadyState();

        mIpNeighborMonitor = new IpNeighborMonitor(h, mLog,
        mIpNeighborMonitor = mDependencies.makeIpNeighborMonitor(h, mLog,
                (NeighborEvent event) -> {
                    if (mInterfaceParams.index != event.ifindex) return;
                    if (!mNeighborWatchList.containsKey(event.ip)) return;
+0 −70
Original line number Diff line number Diff line
/*
 * Copyright (C) 2017 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 android.net.ip;

import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.when;

import android.content.Context;
import android.net.INetd;
import android.net.util.InterfaceParams;
import android.net.util.SharedLog;
import android.os.Handler;
import android.os.Looper;

import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

/**
 * Tests for IpReachabilityMonitor.
 */
@RunWith(AndroidJUnit4.class)
@SmallTest
public class IpReachabilityMonitorTest {
    @Mock IpReachabilityMonitor.Callback mCallback;
    @Mock IpReachabilityMonitor.Dependencies mDependencies;
    @Mock SharedLog mLog;
    @Mock Context mContext;
    @Mock INetd mNetd;
    Handler mHandler;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        when(mLog.forSubComponent(anyString())).thenReturn(mLog);
        mHandler = new Handler(Looper.getMainLooper());
    }

    IpReachabilityMonitor makeMonitor() {
        final InterfaceParams ifParams = new InterfaceParams("fake0", 1, null);
        return new IpReachabilityMonitor(
                mContext, ifParams, mHandler, mLog, mCallback, false, mDependencies, mNetd);
    }

    @Test
    public void testNothing() {
        // make sure the unit test runs in the same thread with main looper.
        // Otherwise, throwing IllegalStateException would cause test fails.
        mHandler.post(() -> makeMonitor());
    }
}
+247 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2017 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 android.net.ip

import android.content.Context
import android.net.INetd
import android.net.InetAddresses.parseNumericAddress
import android.net.IpPrefix
import android.net.LinkAddress
import android.net.LinkProperties
import android.net.RouteInfo
import android.net.netlink.StructNdMsg.NUD_FAILED
import android.net.netlink.StructNdMsg.NUD_STALE
import android.net.netlink.makeNewNeighMessage
import android.net.util.InterfaceParams
import android.net.util.SharedLog
import android.os.Handler
import android.os.HandlerThread
import android.os.MessageQueue
import android.os.MessageQueue.OnFileDescriptorEventListener
import android.system.ErrnoException
import android.system.OsConstants.EAGAIN
import androidx.test.filters.SmallTest
import androidx.test.runner.AndroidJUnit4
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentCaptor
import org.mockito.ArgumentMatchers.any
import org.mockito.ArgumentMatchers.anyInt
import org.mockito.ArgumentMatchers.anyString
import org.mockito.ArgumentMatchers.eq
import org.mockito.Mockito.doAnswer
import org.mockito.Mockito.doReturn
import org.mockito.Mockito.mock
import org.mockito.Mockito.never
import org.mockito.Mockito.timeout
import org.mockito.Mockito.verify
import java.io.FileDescriptor
import java.net.Inet4Address
import java.net.Inet6Address
import java.net.InetAddress
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.TimeUnit
import kotlin.test.assertTrue
import kotlin.test.fail

private const val TEST_TIMEOUT_MS = 10_000L

private val TEST_IPV4_GATEWAY = parseNumericAddress("192.168.222.3") as Inet4Address
private val TEST_IPV6_GATEWAY = parseNumericAddress("2001:db8::1") as Inet6Address

private val TEST_IPV4_LINKADDR = LinkAddress("192.168.222.123/24")
private val TEST_IPV6_LINKADDR = LinkAddress("2001:db8::123/64")

// DNSes inside IP prefix
private val TEST_IPV4_DNS = parseNumericAddress("192.168.222.1") as Inet4Address
private val TEST_IPV6_DNS = parseNumericAddress("2001:db8::321") as Inet6Address

private val TEST_IFACE = InterfaceParams("fake0", 21, null)
private val TEST_LINK_PROPERTIES = LinkProperties().apply {
    interfaceName = TEST_IFACE.name
    addLinkAddress(TEST_IPV4_LINKADDR)
    addLinkAddress(TEST_IPV6_LINKADDR)

    // Add on link routes
    addRoute(RouteInfo(TEST_IPV4_LINKADDR, null /* gateway */, TEST_IFACE.name))
    addRoute(RouteInfo(TEST_IPV6_LINKADDR, null /* gateway */, TEST_IFACE.name))

    // Add default routes
    addRoute(RouteInfo(IpPrefix(parseNumericAddress("0.0.0.0"), 0), TEST_IPV4_GATEWAY))
    addRoute(RouteInfo(IpPrefix(parseNumericAddress("::"), 0), TEST_IPV6_GATEWAY))

    addDnsServer(TEST_IPV4_DNS)
    addDnsServer(TEST_IPV6_DNS)
}

/**
 * Tests for IpReachabilityMonitor.
 */
@RunWith(AndroidJUnit4::class)
@SmallTest
class IpReachabilityMonitorTest {
    private val callback = mock(IpReachabilityMonitor.Callback::class.java)
    private val dependencies = mock(IpReachabilityMonitor.Dependencies::class.java)
    private val log = mock(SharedLog::class.java)
    private val context = mock(Context::class.java)
    private val netd = mock(INetd::class.java)
    private val fd = mock(FileDescriptor::class.java)

    private val handlerThread = HandlerThread(IpReachabilityMonitorTest::class.simpleName)
    private val handler by lazy { Handler(handlerThread.looper) }

    private lateinit var reachabilityMonitor: IpReachabilityMonitor
    private lateinit var neighborMonitor: TestIpNeighborMonitor

    /**
     * A version of [IpNeighborMonitor] that overrides packet reading from a socket, and instead
     * allows the test to enqueue test packets via [enqueuePacket].
     */
    private class TestIpNeighborMonitor(
        handler: Handler,
        log: SharedLog,
        cb: NeighborEventConsumer,
        private val fd: FileDescriptor
    ) : IpNeighborMonitor(handler, log, cb) {

        private val pendingPackets = ConcurrentLinkedQueue<ByteArray>()
        val msgQueue = mock(MessageQueue::class.java)

        private var eventListener: OnFileDescriptorEventListener? = null

        override fun createFd() = fd
        override fun getMessageQueue() = msgQueue

        fun enqueuePacket(packet: ByteArray) {
            val listener = eventListener ?: fail("IpNeighborMonitor was not yet started")
            pendingPackets.add(packet)
            handler.post {
                listener.onFileDescriptorEvents(fd, OnFileDescriptorEventListener.EVENT_INPUT)
            }
        }

        override fun readPacket(fd: FileDescriptor, packetBuffer: ByteArray): Int {
            val packet = pendingPackets.poll() ?: throw ErrnoException("No pending packet", EAGAIN)
            if (packet.size > packetBuffer.size) {
                fail("Buffer (${packetBuffer.size}) is too small for packet (${packet.size})")
            }
            System.arraycopy(packet, 0, packetBuffer, 0, packet.size)
            return packet.size
        }

        override fun onStart() {
            super.onStart()

            // Find the file descriptor listener that was registered on the instrumented queue
            val captor = ArgumentCaptor.forClass(OnFileDescriptorEventListener::class.java)
            verify(msgQueue).addOnFileDescriptorEventListener(
                    eq(fd), anyInt(), captor.capture())
            eventListener = captor.value
        }
    }

    @Before
    fun setUp() {
        doReturn(log).`when`(log).forSubComponent(anyString())
        doReturn(true).`when`(fd).valid()
        handlerThread.start()

        doAnswer { inv ->
            val handler = inv.getArgument<Handler>(0)
            val log = inv.getArgument<SharedLog>(1)
            val cb = inv.getArgument<IpNeighborMonitor.NeighborEventConsumer>(2)
            neighborMonitor = TestIpNeighborMonitor(handler, log, cb, fd)
            neighborMonitor
        }.`when`(dependencies).makeIpNeighborMonitor(any(), any(), any())

        val monitorFuture = CompletableFuture<IpReachabilityMonitor>()
        // IpReachabilityMonitor needs to be started from the handler thread
        handler.post {
            monitorFuture.complete(IpReachabilityMonitor(
                    context,
                    TEST_IFACE,
                    handler,
                    log,
                    callback,
                    false /* useMultinetworkPolicyTracker */,
                    dependencies,
                    netd))
        }
        reachabilityMonitor = monitorFuture.get(TEST_TIMEOUT_MS, TimeUnit.MILLISECONDS)
        assertTrue(::neighborMonitor.isInitialized,
                "IpReachabilityMonitor did not call makeIpNeighborMonitor")
    }

    @After
    fun tearDown() {
        doReturn(false).`when`(fd).valid()
        handlerThread.quitSafely()
    }

    // TODO: fix this bug
    @Test
    fun testLoseProvisioning_CrashIfFirstProbeIsFailed() {
        reachabilityMonitor.updateLinkProperties(TEST_LINK_PROPERTIES)

        doAnswer {
            // Set the fd as invalid when the event listener is removed, to avoid a crash when the
            // reader tries to close the mock fd.
            // This does not exactly reflect behavior on close, but this test is only demonstrating
            // a bug that causes the close, and it will be removed when the bug fixed.
            doReturn(false).`when`(fd).valid()
        }.`when`(neighborMonitor.msgQueue).removeOnFileDescriptorEventListener(any())

        neighborMonitor.enqueuePacket(makeNewNeighMessage(TEST_IPV4_DNS, NUD_FAILED))
        verify(neighborMonitor.msgQueue, timeout(TEST_TIMEOUT_MS))
                .removeOnFileDescriptorEventListener(any())
        verify(callback, never()).notifyLost(eq(TEST_IPV4_DNS), anyString())
    }

    private fun runLoseProvisioningTest(lostNeighbor: InetAddress) {
        reachabilityMonitor.updateLinkProperties(TEST_LINK_PROPERTIES)

        neighborMonitor.enqueuePacket(makeNewNeighMessage(TEST_IPV4_GATEWAY, NUD_STALE))
        neighborMonitor.enqueuePacket(makeNewNeighMessage(TEST_IPV6_GATEWAY, NUD_STALE))
        neighborMonitor.enqueuePacket(makeNewNeighMessage(TEST_IPV4_DNS, NUD_STALE))
        neighborMonitor.enqueuePacket(makeNewNeighMessage(TEST_IPV6_DNS, NUD_STALE))

        neighborMonitor.enqueuePacket(makeNewNeighMessage(lostNeighbor, NUD_FAILED))
        verify(callback, timeout(TEST_TIMEOUT_MS)).notifyLost(eq(lostNeighbor), anyString())
    }

    @Test
    fun testLoseProvisioning_Ipv4DnsLost() {
        runLoseProvisioningTest(TEST_IPV4_DNS)
    }

    @Test
    fun testLoseProvisioning_Ipv6DnsLost() {
        runLoseProvisioningTest(TEST_IPV6_DNS)
    }

    @Test
    fun testLoseProvisioning_Ipv4GatewayLost() {
        runLoseProvisioningTest(TEST_IPV4_GATEWAY)
    }

    @Test
    fun testLoseProvisioning_Ipv6GatewayLost() {
        runLoseProvisioningTest(TEST_IPV6_GATEWAY)
    }
}
 No newline at end of file
+100 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2020 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 android.net.netlink

import android.net.netlink.NetlinkConstants.RTM_DELNEIGH
import android.net.netlink.NetlinkConstants.RTM_NEWNEIGH
import libcore.util.HexEncoding
import libcore.util.HexEncoding.encodeToString
import java.net.Inet6Address
import java.net.InetAddress

/**
 * Make a RTM_NEWNEIGH netlink message.
 */
fun makeNewNeighMessage(
    neighAddr: InetAddress,
    nudState: Short
) = makeNeighborMessage(
        neighAddr = neighAddr,
        type = RTM_NEWNEIGH,
        nudState = nudState
)

/**
 * Make a RTM_DELNEIGH netlink message.
 */
fun makeDelNeighMessage(
    neighAddr: InetAddress,
    nudState: Short
) = makeNeighborMessage(
        neighAddr = neighAddr,
        type = RTM_DELNEIGH,
        nudState = nudState
)

private fun makeNeighborMessage(
    neighAddr: InetAddress,
    type: Short,
    nudState: Short
) = HexEncoding.decode(
    /* ktlint-disable indent */
    // -- struct nlmsghdr --
                         // length = 88 or 76:
    (if (neighAddr is Inet6Address) "58000000" else "4c000000") +
    type.toLEHex() +     // type
    "0000" +             // flags
    "00000000" +         // seqno
    "00000000" +         // pid (0 == kernel)
    // struct ndmsg
                         // family (AF_INET6 or AF_INET)
    (if (neighAddr is Inet6Address) "0a" else "02") +
    "00" +               // pad1
    "0000" +             // pad2
    "15000000" +         // interface index (21 == wlan0, on test device)
    nudState.toLEHex() + // NUD state
    "00" +               // flags
    "01" +               // type
    // -- struct nlattr: NDA_DST --
                         // length = 20 or 8:
    (if (neighAddr is Inet6Address) "1400" else "0800") +
    "0100" +             // type (1 == NDA_DST, for neighbor messages)
                         // IP address:
    encodeToString(neighAddr.address, false /* upperCase */) +
    // -- struct nlattr: NDA_LLADDR --
    "0a00" +             // length = 10
    "0200" +             // type (2 == NDA_LLADDR, for neighbor messages)
    "00005e000164" +     // MAC Address (== 00:00:5e:00:01:64)
    "0000" +             // padding, for 4 byte alignment
    // -- struct nlattr: NDA_PROBES --
    "0800" +             // length = 8
    "0400" +             // type (4 == NDA_PROBES, for neighbor messages)
    "01000000" +         // number of probes
    // -- struct nlattr: NDA_CACHEINFO --
    "1400" +             // length = 20
    "0300" +             // type (3 == NDA_CACHEINFO, for neighbor messages)
    "05190000" +         // ndm_used, as "clock ticks ago"
    "05190000" +         // ndm_confirmed, as "clock ticks ago"
    "190d0000" +         // ndm_updated, as "clock ticks ago"
    "00000000",          // ndm_refcnt
    false /* allowSingleChar */)
    /* ktlint-enable indent */

/**
 * Convert a [Short] to a little-endian hex string.
 */
private fun Short.toLEHex() = String.format("%04x", java.lang.Short.reverseBytes(this))
Loading