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 android.os.Handler;
20 
21 import androidx.annotation.NonNull;
22 import androidx.annotation.Nullable;
23 
24 import com.android.net.module.util.ArrayTrackRecord;
25 import com.android.net.module.util.PacketReader;
26 
27 import java.io.FileDescriptor;
28 import java.io.FileOutputStream;
29 import java.io.IOException;
30 import java.nio.ByteBuffer;
31 import java.util.Arrays;
32 import java.util.function.Predicate;
33 
34 import kotlin.Lazy;
35 import kotlin.LazyKt;
36 
37 /**
38  * A packet reader that runs on a TAP interface.
39  *
40  * It also implements facilities to reply to received packets.
41  */
42 public class TapPacketReader extends PacketReader {
43     private final FileDescriptor mTapFd;
44     private final ArrayTrackRecord<byte[]> mReceivedPackets = new ArrayTrackRecord<>();
45     private final Lazy<ArrayTrackRecord<byte[]>.ReadHead> mReadHead =
46             LazyKt.lazy(mReceivedPackets::newReadHead);
47 
TapPacketReader(Handler h, FileDescriptor tapFd, int maxPacketSize)48     public TapPacketReader(Handler h, FileDescriptor tapFd, int maxPacketSize) {
49         super(h, maxPacketSize);
50         mTapFd = tapFd;
51     }
52 
53 
54     /**
55      * Attempt to start the FdEventsReader on its handler thread.
56      *
57      * As opposed to {@link android.net.util.FdEventsReader#start()}, this method will not report
58      * failure to start, so it is only appropriate in tests that will fail later if that happens.
59      */
startAsyncForTest()60     public void startAsyncForTest() {
61         getHandler().post(this::start);
62     }
63 
64     @Override
createFd()65     protected FileDescriptor createFd() {
66         return mTapFd;
67     }
68 
69     @Override
handlePacket(byte[] recvbuf, int length)70     protected void handlePacket(byte[] recvbuf, int length) {
71         final byte[] newPacket = Arrays.copyOf(recvbuf, length);
72         if (!mReceivedPackets.add(newPacket)) {
73             throw new AssertionError("More than " + Integer.MAX_VALUE + " packets outstanding!");
74         }
75     }
76 
77     /**
78      * @deprecated This method does not actually "pop" (which generally means the last packet).
79      * Use {@link #poll(long)}, which has the same behavior, instead.
80      */
81     @Nullable
82     @Deprecated
popPacket(long timeoutMs)83     public byte[] popPacket(long timeoutMs) {
84         return poll(timeoutMs);
85     }
86 
87     /**
88      * @deprecated This method does not actually "pop" (which generally means the last packet).
89      * Use {@link #poll(long, Predicate)}, which has the same behavior, instead.
90      */
91     @Nullable
92     @Deprecated
popPacket(long timeoutMs, @NonNull Predicate<byte[]> filter)93     public byte[] popPacket(long timeoutMs, @NonNull Predicate<byte[]> filter) {
94         return poll(timeoutMs, filter);
95     }
96 
97     /**
98      * Get the next packet that was received on the interface.
99      */
100     @Nullable
poll(long timeoutMs)101     public byte[] poll(long timeoutMs) {
102         return mReadHead.getValue().poll(timeoutMs, packet -> true);
103     }
104 
105     /**
106      * Get the next packet that was received on the interface and matches the specified filter.
107      */
108     @Nullable
poll(long timeoutMs, @NonNull Predicate<byte[]> filter)109     public byte[] poll(long timeoutMs, @NonNull Predicate<byte[]> filter) {
110         return mReadHead.getValue().poll(timeoutMs, filter::test);
111     }
112 
113     /**
114      * Get the {@link ArrayTrackRecord} that records all packets received by the reader since its
115      * creation.
116      */
getReceivedPackets()117     public ArrayTrackRecord<byte[]> getReceivedPackets() {
118         return mReceivedPackets;
119     }
120 
121     /*
122      * Send a response on the TAP interface.
123      *
124      * The passed ByteBuffer is flipped after use.
125      *
126      * @param packet The packet to send.
127      * @throws IOException if the interface can't be written to.
128      */
sendResponse(final ByteBuffer packet)129     public void sendResponse(final ByteBuffer packet) throws IOException {
130         try (FileOutputStream out = new FileOutputStream(mTapFd)) {
131             byte[] packetBytes = new byte[packet.limit()];
132             packet.get(packetBytes);
133             packet.flip();  // So we can reuse it in the future.
134             out.write(packetBytes);
135         }
136     }
137 }
138