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.net.MacAddress
20 import com.android.net.module.util.NetworkStackConstants.ETHER_HEADER_LEN
21 import java.net.Inet4Address
22 import java.net.InetAddress
23 import java.nio.ByteBuffer
24
25 private const val ARP_SENDER_MAC_OFFSET = ETHER_HEADER_LEN + 8
26 private const val ARP_TARGET_IPADDR_OFFSET = ETHER_HEADER_LEN + 24
27
28 private val TYPE_ARP = byteArrayOf(0x08, 0x06)
29 // Arp reply header for IPv4 over ethernet
30 private val ARP_REPLY_IPV4 = byteArrayOf(0x00, 0x01, 0x08, 0x00, 0x06, 0x04, 0x00, 0x02)
31
32 /**
33 * A class that can be used to reply to ARP packets on a [PollPacketReader].
34 */
35 class ArpResponder(
36 reader: PollPacketReader,
37 table: Map<Inet4Address, MacAddress>,
38 name: String = ArpResponder::class.java.simpleName
39 ) : PacketResponder(reader, ArpRequestFilter(), name) {
40 // Copy the map if not already immutable (toMap) to make sure it is not modified
41 private val table = table.toMap()
42
replyToPacketnull43 override fun replyToPacket(packet: ByteArray, reader: PollPacketReader) {
44 val targetIp = InetAddress.getByAddress(
45 packet.copyFromIndexWithLength(ARP_TARGET_IPADDR_OFFSET, 4))
46 as Inet4Address
47
48 val macAddr = table[targetIp]?.toByteArray() ?: return
49 val senderMac = packet.copyFromIndexWithLength(ARP_SENDER_MAC_OFFSET, 6)
50 reader.sendResponse(ByteBuffer.wrap(
51 // Ethernet header
52 senderMac + macAddr + TYPE_ARP +
53 // ARP message
54 ARP_REPLY_IPV4 +
55 macAddr /* sender MAC */ +
56 targetIp.address /* sender IP addr */ +
57 macAddr /* target mac */ +
58 targetIp.address /* target IP addr */
59 ))
60 }
61 }
62
ByteArraynull63 private fun ByteArray.copyFromIndexWithLength(start: Int, len: Int) =
64 copyOfRange(start, start + len)
65