More code cleanup

This commit is contained in:
2024-02-22 00:15:22 +01:00
parent 70e353bd0c
commit 417c11670a
4 changed files with 50 additions and 40 deletions

View File

@ -17,19 +17,12 @@ use React\Stream\WritableStreamInterface;
class WebSocketCodec
{
const OP_CONTINUATION = 0x0;
const OP_FRAME_TEXT = 0x1;
const OP_FRAME_BINARY = 0x2;
const OP_CLOSE = 0x8;
const OP_PING = 0x9;
const OP_PONG = 0xA;
public function encode(array $frame): string
{
// Encoded frame
$encoded = null;
// Unpack frame with defaults
// Re-unpack frame with defaults
$frame = [
...[
'final' => true,
@ -56,10 +49,13 @@ class WebSocketCodec
$size1 = ($len >> 8) & 0xFF;
$size2 = $len & 0xFF;
$size3 = null;
$size4 = null;
} else {
$size0 = $len;
$size1 = null;
$size2 = null;
$size3 = null;
$size4 = null;
}
$encoded .= chr(($frame['final']?0x80:0x00)
@ -152,38 +148,24 @@ class WebSocketCodec
return $decoded;
}
/**
* Masking is reversible, and simply xors a repeated 4-byte key with the data.
*
* @param string $payload The unmasked (or masked) input
* @param string $mask The mask to use (4 bytes)
* @return string The masked (or unmasked) output
*/
private function mask(string $payload, string $mask): string
{
$payloadData = array_map("ord", str_split($payload,1));
$maskData = array_map("ord", str_split($mask,1));
//printf("Mask: %02x %02x %02x %02x\n", ...$maskData);
$unmasked = [];
for ($n = 0; $n < count($payloadData); $n++) {
$unmasked[] = $payloadData[$n] ^ $maskData[$n % 4];
}
return join("", array_map("chr", $unmasked));
}
private function hexdump($data): void
{
printf("%4d .\n", strlen($data));
$rows = str_split($data, 16);
$offs = 0;
foreach ($rows as $row) {
$h = []; $a = [];
for ($n = 0; $n < 16; $n++) {
if ($n < strlen($row)) {
$h[] = sprintf("%02x%s", ord($row[$n]), ($n==7)?" ":" ");
$a[] = sprintf("%s%s", (ctype_print($row[$n])?$row[$n]:"."), ($n==7)?" ":"");
} else {
$h[] = (($n==7)?" ":" ");
$a[] = (($n==7)?" ":" ");
}
}
printf("%04x | %s | %s\n", 16 * $offs++, join("", $h), join("", $a));
}
}
}