Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions src/Bencode.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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');
Expand Down
36 changes: 35 additions & 1 deletion tests/DecodeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down Expand Up @@ -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');
}

Expand Down
Loading