|
8 | 8 | namespace s9e\Bencode; |
9 | 9 |
|
10 | 10 | use ArrayObject; |
| 11 | +use Throwable; |
| 12 | +use TypeError; |
11 | 13 | use const PHP_INT_MAX, PHP_INT_MIN, false; |
12 | 14 | use function is_float, str_contains, strcmp, strlen, strspn, substr, substr_compare; |
13 | 15 | use s9e\Bencode\Exceptions\ComplianceError; |
@@ -38,7 +40,14 @@ class Decoder |
38 | 40 | public static function decode(string $bencoded): ArrayObject|array|int|string |
39 | 41 | { |
40 | 42 | $decoder = new static($bencoded); |
41 | | - $value = $decoder->decodeAnything(); |
| 43 | + try |
| 44 | + { |
| 45 | + $value = $decoder->decodeAnything(); |
| 46 | + } |
| 47 | + catch (TypeError $e) |
| 48 | + { |
| 49 | + throw self::convertTypeError($e, $decoder->offset); |
| 50 | + } |
42 | 51 |
|
43 | 52 | $decoder->checkCursorPosition(); |
44 | 53 |
|
@@ -142,6 +151,19 @@ protected function computeSafeBoundary(): void |
142 | 151 | }; |
143 | 152 | } |
144 | 153 |
|
| 154 | + protected static function convertTypeError(TypeError $e, int $offset): Throwable |
| 155 | + { |
| 156 | + // A type error can occur in decodeString() if the string length exceeds an int |
| 157 | + $frame = $e->getTrace()[0]; |
| 158 | + if ($frame['class'] === __CLASS__ && $frame['function'] === 'decodeString') |
| 159 | + { |
| 160 | + return new DecodingException('String length overflow', $offset - 1); |
| 161 | + } |
| 162 | + |
| 163 | + // Return any other error as-is |
| 164 | + return $e; |
| 165 | + } |
| 166 | + |
145 | 167 | protected function decodeAnything(): ArrayObject|array|int|string |
146 | 168 | { |
147 | 169 | return match ($this->bencoded[$this->offset]) |
@@ -242,11 +264,6 @@ protected function decodeList(): array |
242 | 264 | protected function decodeString(): string |
243 | 265 | { |
244 | 266 | $len = (int) $this->readDigits(':'); |
245 | | - if ($this->offset + $len >= PHP_INT_MAX) |
246 | | - { |
247 | | - throw new DecodingException('String length overflow', $this->offset - 1 - strlen((string) $len)); |
248 | | - } |
249 | | - |
250 | 267 | $string = substr($this->bencoded, $this->offset, $len); |
251 | 268 | $this->offset += $len; |
252 | 269 |
|
|
0 commit comments