diff --git a/src/Bencode.php b/src/Bencode.php index 9f56728..1423f0c 100644 --- a/src/Bencode.php +++ b/src/Bencode.php @@ -68,6 +68,9 @@ public static function decode($data, &$pos = 0) $return = []; while ($data[$pos] !== 'e') { $key = self::decode($data, $pos); + if ($pos < strlen($data) && $data[$pos] === 'e') { + throw new ParseException('Dictionary key without value: ' . $key); + } $value = self::decode($data, $pos); if ($key === null || $value === null) { break; @@ -91,12 +94,20 @@ public static function decode($data, &$pos = 0) $pos++; } elseif ($data[$pos] === 'i') { $pos++; - $digits = strpos($data, 'e', $pos) - $pos; + $end = strpos($data, 'e', $pos); + if ($end === false) { + throw new ParseException('Unterminated bencode integer'); + } + $digits = $end - $pos; $value = substr($data, $pos, $digits); $return = self::checkInteger($value); $pos += $digits + 1; } else { - $digits = strpos($data, ':', $pos) - $pos; + $colon = strpos($data, ':', $pos); + if ($colon === false) { + throw new ParseException('Missing colon after string length'); + } + $digits = $colon - $pos; $len = self::checkInteger(substr($data, $pos, $digits)); if ($len < 0) { throw new ParseException('Cannot have non-digit values for String length'); diff --git a/tests/DecodeTest.php b/tests/DecodeTest.php index 0951e79..cda121f 100644 --- a/tests/DecodeTest.php +++ b/tests/DecodeTest.php @@ -181,6 +181,40 @@ public function testDecodeStringIncorrectLengthNegative() Bencode::decode('-6:String'); } + /** + * @group string + */ + public function testDecodeStringMissingColonInList() + { + $this->expectException(ParseException::class); + $this->expectExceptionMessage('Missing colon after string length'); + + // used to loop forever (until memory ran out) appending empty strings + Bencode::decode('l0a'); + } + + /** + * @group string + */ + public function testDecodeStringMissingColon() + { + $this->expectException(ParseException::class); + $this->expectExceptionMessage('Missing colon after string length'); + + Bencode::decode('d3:key0'); + } + + /** + * @group integer + */ + public function testDecodeIntegerUnterminated() + { + $this->expectException(ParseException::class); + $this->expectExceptionMessage('Unterminated bencode integer'); + + Bencode::decode('li12'); + } + /** * @group string */ @@ -256,7 +290,7 @@ public function testDecodeDictionaryKeyNotString() public function testDecodeDictionaryWithKeyButWithoutValue() { $this->expectException(ParseException::class); - $this->expectExceptionMessage('Invalid integer format or integer overflow'); // FIXME + $this->expectExceptionMessage('Dictionary key without value: b'); Bencode::decode('d1:ai1e1:be'); }