forked from NetherGamesMC/libproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MultiCompressor.php
77 lines (61 loc) · 2.31 KB
/
MultiCompressor.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
declare(strict_types=1);
namespace libproxy;
use ErrorException;
use GlobalLogger;
use pocketmine\network\mcpe\compression\Compressor;
use pocketmine\network\mcpe\compression\DecompressionException;
use pocketmine\network\mcpe\compression\ZlibCompressor;
use pocketmine\utils\BinaryDataException;
use pocketmine\utils\BinaryStream;
use pocketmine\utils\SingletonTrait;
use RuntimeException;
use function zstd_uncompress;
class MultiCompressor implements Compressor
{
public const ZSTD_COMPRESSION_LEVEL = -1;
public const METHOD_ZLIB = 0x00;
public const METHOD_ZSTD = 0x01;
use SingletonTrait;
public function willCompress(string $data): bool
{
return true;
}
public function decompress(string $payload): string
{
$stream = new BinaryStream($payload);
try {
$method = $stream->getByte();
try {
$result = match ($method) {
self::METHOD_ZLIB => ZlibCompressor::getInstance()->decompress($stream->getRemaining()),
self::METHOD_ZSTD => zstd_uncompress($stream->getRemaining()),
default => throw new DecompressionException("Decompression method not found"),
};
} catch (ErrorException $exception) {
throw new DecompressionException('Failed to decompress data', 0, $exception);
}
} catch (BinaryDataException $exception) {
throw new DecompressionException("Decompression method is invalid");
}
if ($result === false) {
throw new DecompressionException("Failed to decompress data");
}
return $result;
}
/**
* The proxy needs to know the length of the string before compression for allocating buffers (JAVA)
* @see decompress() doesn't need this as it's not send back by the Proxy, since we don't need it
*
* @param string $payload
* @return string
*/
public function compress(string $payload): string
{
if (($size = strlen($payload)) >= (3.5 * 1024 * 1024)) {
GlobalLogger::get()->alert("Payload exceed maximum safe decompression size, $size.");
GlobalLogger::get()->logException(new RuntimeException());
}
return ZlibCompressor::getInstance()->compress($payload);
}
}