Skip to content

Commit e4382d9

Browse files
committed
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.
1 parent 4068891 commit e4382d9

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

core/src/androidTest/java/com/github/shadowsocks/net/SubnetTest.kt

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,18 @@ class SubnetTest {
2828
}
2929

3030
@Test
31-
fun matching() {
31+
fun matching1() {
3232
val matcher = Subnet.fromString("1.10.11.12/25")!!.toImmutable()
3333
Assert.assertFalse(matcher.matches(parseNumericAddress("1.10.10.12").address))
3434
Assert.assertTrue(matcher.matches(parseNumericAddress("1.10.11.13").address))
3535
Assert.assertFalse(matcher.matches(parseNumericAddress("1.10.11.212").address))
3636
}
37+
38+
@Test
39+
fun matching2() {
40+
val matcher = Subnet.fromString("14.208.0.0/12")!!.toImmutable()
41+
Assert.assertTrue(matcher.matches(parseNumericAddress("14.215.178.36").address))
42+
Assert.assertTrue(matcher.matches(parseNumericAddress("14.215.178.37").address))
43+
Assert.assertFalse(matcher.matches(parseNumericAddress("1.10.11.212").address))
44+
}
3745
}

core/src/main/java/com/github/shadowsocks/net/Subnet.kt

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,8 @@ class Subnet(val address: InetAddress, val prefixSize: Int) : Comparable<Subnet>
5757
}
5858
}
5959

60+
fun Byte.toPositiveInt() = toInt() and 0xFF
61+
6062
fun matches(b: Immutable) = matches(b.a)
6163
fun matches(b: ByteArray): Boolean {
6264
if (a.size != b.size) return false
@@ -66,7 +68,7 @@ class Subnet(val address: InetAddress, val prefixSize: Int) : Comparable<Subnet>
6668
++i
6769
}
6870
val mask = 256 - (1 shl i * 8 + 8 - prefixSize)
69-
return i * 8 == prefixSize || a[i].toInt() and mask == b[i].toInt() and mask
71+
return i * 8 == prefixSize || a[i].toPositiveInt() == b[i].toPositiveInt() and mask
7072
}
7173
}
7274
fun toImmutable() = Immutable(address.address.also {

0 commit comments

Comments
 (0)