Remi NGUYEN VAN | 7995b43 | 2020-08-14 12:49:56 +0900 | [diff] [blame] | 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 java.net.Inet4Address |
| 21 | import java.net.InetAddress |
| 22 | import java.nio.ByteBuffer |
| 23 | |
| 24 | private val TYPE_ARP = byteArrayOf(0x08, 0x06) |
| 25 | // Arp reply header for IPv4 over ethernet |
| 26 | private 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 | */ |
| 31 | class 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 | |
| 59 | private fun ByteArray.copyFromIndexWithLength(start: Int, len: Int) = |
| 60 | copyOfRange(start, start + len) |