1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.testutils
18 
19 import java.util.function.Predicate
20 
21 private const val POLL_FREQUENCY_MS = 1000L
22 
23 /**
24  * A class that can be used to reply to packets from a [TapPacketReader].
25  *
26  * A reply thread will be created to reply to incoming packets asynchronously.
27  * The receiver creates a new read head on the [TapPacketReader], to read packets, so it does not
28  * affect packets obtained through [TapPacketReader.popPacket].
29  *
30  * @param reader a [TapPacketReader] to obtain incoming packets and reply to them.
31  * @param packetFilter A filter to apply to incoming packets.
32  * @param name Name to use for the internal responder thread.
33  */
34 abstract class PacketResponder(
35     private val reader: TapPacketReader,
36     private val packetFilter: Predicate<ByteArray>,
37     name: String
38 ) {
39     private val replyThread = ReplyThread(name)
40 
replyToPacketnull41     protected abstract fun replyToPacket(packet: ByteArray, reader: TapPacketReader)
42 
43     /**
44      * Start the [PacketResponder].
45      */
46     fun start() {
47         replyThread.start()
48     }
49 
50     /**
51      * Stop the [PacketResponder].
52      *
53      * The responder cannot be used anymore after being stopped.
54      */
stopnull55     fun stop() {
56         replyThread.interrupt()
57         replyThread.join()
58     }
59 
60     private inner class ReplyThread(name: String) : Thread(name) {
runnull61         override fun run() {
62             try {
63                 // Create a new ReadHead so other packets polled on the reader are not affected
64                 val recvPackets = reader.receivedPackets.newReadHead()
65                 while (!isInterrupted) {
66                     recvPackets.poll(POLL_FREQUENCY_MS, packetFilter::test)?.let {
67                         replyToPacket(it, reader)
68                     }
69                 }
70             } catch (e: InterruptedException) {
71                 // Exit gracefully
72             }
73         }
74     }
75 }
76