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