Commit e4382d9d authored by Max Lv's avatar Max Lv

Fix the byte to positive int issue.

After masking the subnet, we convert it from int to byte and store it back to
bytearray.  Then in the matches() function, we convert the masked addr from int
to byte again, which may be converted to a negative value due to overflow.

Also adding a unit test to cover this case.
parent 40688911
...@@ -28,10 +28,18 @@ class SubnetTest { ...@@ -28,10 +28,18 @@ class SubnetTest {
} }
@Test @Test
fun matching() { fun matching1() {
val matcher = Subnet.fromString("1.10.11.12/25")!!.toImmutable() val matcher = Subnet.fromString("1.10.11.12/25")!!.toImmutable()
Assert.assertFalse(matcher.matches(parseNumericAddress("1.10.10.12").address)) Assert.assertFalse(matcher.matches(parseNumericAddress("1.10.10.12").address))
Assert.assertTrue(matcher.matches(parseNumericAddress("1.10.11.13").address)) Assert.assertTrue(matcher.matches(parseNumericAddress("1.10.11.13").address))
Assert.assertFalse(matcher.matches(parseNumericAddress("1.10.11.212").address)) Assert.assertFalse(matcher.matches(parseNumericAddress("1.10.11.212").address))
} }
@Test
fun matching2() {
val matcher = Subnet.fromString("14.208.0.0/12")!!.toImmutable()
Assert.assertTrue(matcher.matches(parseNumericAddress("14.215.178.36").address))
Assert.assertTrue(matcher.matches(parseNumericAddress("14.215.178.37").address))
Assert.assertFalse(matcher.matches(parseNumericAddress("1.10.11.212").address))
}
} }
...@@ -57,6 +57,8 @@ class Subnet(val address: InetAddress, val prefixSize: Int) : Comparable<Subnet> ...@@ -57,6 +57,8 @@ class Subnet(val address: InetAddress, val prefixSize: Int) : Comparable<Subnet>
} }
} }
fun Byte.toPositiveInt() = toInt() and 0xFF
fun matches(b: Immutable) = matches(b.a) fun matches(b: Immutable) = matches(b.a)
fun matches(b: ByteArray): Boolean { fun matches(b: ByteArray): Boolean {
if (a.size != b.size) return false if (a.size != b.size) return false
...@@ -66,7 +68,7 @@ class Subnet(val address: InetAddress, val prefixSize: Int) : Comparable<Subnet> ...@@ -66,7 +68,7 @@ class Subnet(val address: InetAddress, val prefixSize: Int) : Comparable<Subnet>
++i ++i
} }
val mask = 256 - (1 shl i * 8 + 8 - prefixSize) val mask = 256 - (1 shl i * 8 + 8 - prefixSize)
return i * 8 == prefixSize || a[i].toInt() and mask == b[i].toInt() and mask return i * 8 == prefixSize || a[i].toPositiveInt() == b[i].toPositiveInt() and mask
} }
} }
fun toImmutable() = Immutable(address.address.also { fun toImmutable() = Immutable(address.address.also {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment