Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { TargetTypes } from "@/mitm/types";
- import { SmartBuffer } from "smart-buffer";
- export interface IMessageInfos {
- messageId: number;
- dataLength: number;
- buffer?: Buffer;
- }
- export default class MessageParser {
- public static tryParse(
- reader: SmartBuffer,
- messageInfos: IMessageInfos,
- target?: TargetTypes
- ) {
- messageInfos.messageId = 0;
- messageInfos.dataLength = 0;
- messageInfos.buffer = undefined;
- if (reader.remaining() < 2) {
- return false;
- }
- const header = reader.readInt16BE();
- messageInfos.messageId = header >> 2;
- if (target === TargetTypes.CLIENT) {
- const instanceId = reader.readUInt32BE();
- }
- const dataLengthBytesCount = header & 0x3;
- if (reader.remaining() >= dataLengthBytesCount) {
- if (dataLengthBytesCount < 0 || dataLengthBytesCount > 3) {
- throw new RangeError(
- "[MessageParser] Out of range: " + dataLengthBytesCount
- );
- }
- for (let i = dataLengthBytesCount - 1; i >= 0; i--) {
- messageInfos.dataLength |= reader.readInt8() << (i * 8);
- }
- }
- if (messageInfos.dataLength <= 0) {
- return false;
- }
- if (messageInfos.dataLength > reader.remaining()) {
- return false;
- }
- if (messageInfos.buffer === undefined && messageInfos.dataLength >= 0) {
- if (messageInfos.dataLength === 0) {
- messageInfos.buffer = Buffer.from([]);
- }
- // enough bytes in the buffer to build a complete message
- if (reader.remaining() >= messageInfos.dataLength) {
- messageInfos.buffer = reader.readBuffer(messageInfos.dataLength);
- } else if (messageInfos.dataLength > reader.remaining()) {
- // not enough bytes, so we read what we can
- messageInfos.buffer = reader.readBuffer(reader.remaining());
- }
- }
- // second case : the message was split and it missed some bytes
- if (
- !messageInfos.buffer ||
- messageInfos.dataLength === 0 ||
- messageInfos.buffer.length >= messageInfos.dataLength
- ) {
- return true;
- }
- let bytesToRead = 0;
- // still miss some bytes ...
- if (
- messageInfos.buffer.length + reader.remaining() <
- messageInfos.dataLength
- ) {
- bytesToRead = reader.remaining();
- } else if (
- messageInfos.buffer.length + reader.remaining() >=
- messageInfos.dataLength
- ) {
- // there is enough bytes in the buffer to complete the message :)
- bytesToRead = messageInfos.dataLength - messageInfos.buffer.length;
- }
- if (bytesToRead === 0) {
- return true;
- }
- messageInfos.buffer = Buffer.concat([
- messageInfos.buffer,
- reader.readBuffer(bytesToRead)
- ]);
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement