Skip to content

Commit

Permalink
Reduce nuisance console logs
Browse files Browse the repository at this point in the history
Debug console logs can be shown by passing `debug: true` option to LSC, Buffer, or Debug.
  • Loading branch information
Gigabyte5671 committed Dec 28, 2022
1 parent 8d6df52 commit dfcdd8b
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 34 deletions.
21 changes: 13 additions & 8 deletions functions/Buffer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,20 @@ import { generalEnumfields } from '../data/index.js';
import type { EnumTree } from '../interfaces/index.js';
import { hexToString } from './Utils.js';

export interface BufferOptions {
debug?: boolean
}

export class Buffer {
_buffer = new Uint8Array;
_options = {} as BufferOptions;
_bytesReadSinceCreation = 0;
_lastByteRead = undefined as Uint8Array | undefined;
_currentByteRead = undefined as Uint8Array | undefined;

constructor (buffer = new Uint8Array) {
constructor (buffer = new Uint8Array, options?: BufferOptions) {
this._buffer = buffer;
this._options = options ?? {} as BufferOptions;
}

/**
Expand Down Expand Up @@ -132,15 +138,15 @@ export class Buffer {
* @returns An Enum Tree.
*/
parse (): EnumTree {
console.log('[Buffer] Parsing...');
if (this._options.debug) console.log('[Buffer] Parsing...');
let output = {} as EnumTree;
const startTime = performance?.now();
const bytesProcessed = this._branch(output);
const endTime = performance?.now();
if (performance) {
console.log('[Buffer] Done parsing', bytesProcessed, 'bytes in', endTime - startTime, 'milliseconds.');
if (this._options.debug) console.log('[Buffer] Done parsing', bytesProcessed, 'bytes in', endTime - startTime, 'milliseconds.');
} else {
console.log('[Buffer] Done parsing', bytesProcessed, 'bytes.');
if (this._options.debug) console.log('[Buffer] Done parsing', bytesProcessed, 'bytes.');
}
return { ...output } as EnumTree;
}
Expand Down Expand Up @@ -176,8 +182,7 @@ export class Buffer {

// Prune the branch if the enumerator doesn't exist, since this likely indicates that we have lost track of our place in the buffer.
if (!(enumerator in generalEnumfields)) {
console.warn('[Buffer] Enumerator', enumerator, 'was not found at byte #', this.bytesReadSinceCreation, '.');
console.log(hexToString(this.peek(64)).toUpperCase());
console.warn('[Buffer] Enumerator', enumerator, 'was not found at byte #', this.bytesReadSinceCreation, '.\n', hexToString(this.peek(64)).toUpperCase());
/* this.invertEndianness(2);
enumerator = hexToString(this.read(2)).toUpperCase();
bytesProcessed += 2; */
Expand All @@ -191,7 +196,7 @@ export class Buffer {
this.invertEndianness(2);
const fieldLength = parseInt(hexToString(this.read(2)), 16);
bytesProcessed += 2;
console.log('[Buffer] ArrayOfEnumBlockArrays encountered was:', enumerator, '. With length:', fieldLength);
if (this._options.debug) console.log('[Buffer] ArrayOfEnumBlockArrays encountered was:', enumerator, '. With length:', fieldLength);
let arraysProcessed = 0;
while (arraysProcessed < fieldLength) { // TODO: This loop does not check for buffer errors.
this.invertEndianness(2);
Expand All @@ -210,7 +215,7 @@ export class Buffer {
this.invertEndianness(2);
const arrayLength = parseInt(hexToString(this.read(2)), 16);
bytesProcessed += 2;
console.log('[Buffer] EnumBlockArray encountered was:', enumerator, '. With length:', arrayLength);
if (this._options.debug) console.log('[Buffer] EnumBlockArray encountered was:', enumerator, '. With length:', arrayLength);
bytesProcessed += this._branch(parent[enumerator], arrayLength);
}

Expand Down
9 changes: 5 additions & 4 deletions functions/Decoder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import type { EnumTree, Map } from '../interfaces/index.js';
import { hexToString } from './Utils.js';

export interface DecoderOptions {
clean?: boolean
clean?: boolean,
debug?: boolean
}

export class Decoder {
Expand All @@ -14,17 +15,17 @@ export class Decoder {

constructor (tree: EnumTree, options?: DecoderOptions) {
this._tree = tree;
this._options = options ?? {};
this._options = options ?? {} as DecoderOptions;
}

/**
* Decodes a machine-readable Enum Tree.
* @returns A human-readable Enum Tree.
*/
decode () {
console.log('[Decoder] Decoding tree...');
if (this._options.debug) console.log('[Decoder] Decoding tree...');
this._enumfieldsParsed = recurse(this._output, this._tree, this._options);
console.log('[Decoder] Parsed', this._enumfieldsParsed, 'enumfields.');
if (this._options.debug) console.log('[Decoder] Parsed', this._enumfieldsParsed, 'enumfields.');
return this._output;
}

Expand Down
44 changes: 23 additions & 21 deletions functions/Main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as net from 'net';
import { loginServers } from '../data/index.js';
import type { LoginServer, HiRezAccount, HashedCredentials } from '../interfaces/index.js';
import { GenericMessage, AuthenticationMessage } from './Messages.js';
import { Buffer } from './Buffer.js';
import { BufferOptions, Buffer } from './Buffer.js';
import { DecoderOptions, Decoder } from './Decoder.js';
import { verifyPacketLength } from './Utils.js';

Expand All @@ -19,6 +19,8 @@ interface LoginServerConnectionMessage {

interface LoginServerConnectionOptions {
authenticate?: boolean,
buffer?: BufferOptions,
debug?: boolean,
decoder?: DecoderOptions
}

Expand All @@ -34,7 +36,7 @@ export class LoginServerConnection {
};
_socket = {} as net.Socket;
_isReceivingStream = false;
_streamBuffer = new Buffer();
_streamBuffer = new Buffer(new Uint8Array, this._options.buffer);
_timeToIdle = 3000;
_idleTimers = [] as NodeJS.Timeout[];
_messageQueue = [] as LoginServerConnectionMessage[];
Expand Down Expand Up @@ -75,7 +77,7 @@ export class LoginServerConnection {
* Establish a live connection to the Login Server.
*/
async connect () {
console.log('[LSC] Connecting to login server on', this._serverInstance.ip, '...');
if (this._options.debug) console.log('[LSC] Connecting to login server on', this._serverInstance.ip, '...');

this._socket = net.connect(
this._serverInstance.port,
Expand All @@ -88,7 +90,7 @@ export class LoginServerConnection {

// Set up event listeners.
this._socket.on('connect', () => {
console.log('[LSC] Connected.');
if (this._options.debug) console.log('[LSC] Connected.');
this._isConnected = true;
this._idleTimers.forEach((timer) => { clearTimeout(timer); });
this._idleTimers.push(setTimeout(() => { this._idle(); }, this._timeToIdle));
Expand All @@ -102,15 +104,15 @@ export class LoginServerConnection {
});

this._socket.on('data', (data) => {
console.log('[LSC] Data:', data);
if (this._options.debug) console.log('[LSC] Data:', data);
const array = Uint8Array.from(data);

this._idleTimers.forEach((timer) => { clearTimeout(timer); });
this._idleTimers.push(setTimeout(() => { this._idle(); }, this._timeToIdle));

// Process an existing packet stream.
if (this._isReceivingStream) {
console.log('[LSC] Received stream packet.')
if (this._options.debug) console.log('[LSC] Received stream packet.')
// Append all received packets to the same Buffer.
this._streamBuffer.append(array);
// TODO: Figure out a definitive way to detect when a stream has ended.
Expand All @@ -119,7 +121,7 @@ export class LoginServerConnection {
// Detect the start of a packet stream.
else if (array[0] === 0 && array[1] === 0) { // data[00 00 ...] Indicates the start of a packet stream.
this._isReceivingStream = true;
console.log('[LSC] Packet stream started.');
if (this._options.debug) console.log('[LSC] Packet stream started.');
this._streamBuffer.clear();
this._streamBuffer.append(array);
this._streamBuffer.advance(2);
Expand All @@ -131,14 +133,14 @@ export class LoginServerConnection {
console.warn('Length of received data is invalid. Packet may be malformed.');
return;
}
const buffer = new Buffer(array);
const buffer = new Buffer(array, this._options.buffer);
buffer.advance(2);
const enumTree = buffer.parse();
console.log('[LSC] Parsed:', enumTree);
if (this._options.debug) console.log('[LSC] Parsed:', enumTree);

const decoder = new Decoder(enumTree, this._options.decoder ?? {});
const decodedData = decoder.decode();
console.log('[LSC] Decoded:', decodedData);
if (this._options.debug) console.log('[LSC] Decoded:', decodedData);

if (!this._options.authenticate || (this._authProgress.initial && this._authProgress.confirmation)) {
this._callbacks.receive.forEach((callback) => { callback(decodedData); });
Expand All @@ -152,18 +154,18 @@ export class LoginServerConnection {
const ackMessage = new GenericMessage(['12003a0001009e04610b04010000000000000000']);
this._socket.write(ackMessage.buffer, 'hex', () => {
this._authProgress.initial = true;
console.log('[AUTH] Acknowledgement message sent.');
if (this._options.debug) console.log('[AUTH] Acknowledgement message sent.');
});
}

if ('Auth Info Confirmation' in decodedData && this._credentials) {
this._credentials.salt = new Uint8Array(decodedData['Auth Info Confirmation']['Salt']);
const authMessage = new AuthenticationMessage({...this._credentials})
console.log('[AUTH] Sending credentials...');
console.log(authMessage);
if (this._options.debug) console.log('[AUTH] Sending credentials...');
if (this._options.debug) console.log(authMessage);
this._socket.write(authMessage.buffer, 'hex', () => {
this._authProgress.confirmation = true;
console.log('[AUTH] Credentials sent.');
if (this._options.debug) console.log('[AUTH] Credentials sent.');
});
}
}
Expand All @@ -173,7 +175,7 @@ export class LoginServerConnection {
// Start connection sequence.
const initialMessage = new GenericMessage(['1000bc0102009e04610b040189040c000000']);
this._socket.write(initialMessage.buffer, 'hex', () => {
console.log('[LSC] Connection request sent.');
if (this._options.debug) console.log('[LSC] Connection request sent.');
});
}

Expand All @@ -194,7 +196,7 @@ export class LoginServerConnection {
*/
async send (message: LoginServerConnectionMessage) {
if (!this._isConnected) {
throw new Error('Please connect to a login server first.');
throw new Error('Please connect to a login server before sending a message.');
}
// Add the requested message to the queue.
this._messageQueue.push(message);
Expand All @@ -216,23 +218,23 @@ export class LoginServerConnection {
if (message) {
this._messageId++;
this._socket.write(message.buffer, 'hex', () => {
console.log(`[LSC] Sent message ${this._messageId}.`);
if (this._options.debug) console.log(`[LSC] Sent message ${this._messageId}.`);
});
}
}

_flushStreamBuffer () {
// Flush the stream buffer.
if (this._streamBuffer.length > 0) {
console.log('[LSC] Flushing stream buffer...');
if (this._options.debug) console.log('[LSC] Flushing stream buffer...');
const enumTree = this._streamBuffer.parse();
console.log('[LSC] Parsed:', enumTree);
if (this._options.debug) console.log('[LSC] Parsed:', enumTree);

const decoder = new Decoder(enumTree, this._options.decoder ?? {});
const decodedData = decoder.decode();
console.log('[LSC] Decoded:', decodedData);
if (this._options.debug) console.log('[LSC] Decoded:', decodedData);

console.log('[LSC] End of stream data.');
if (this._options.debug) console.log('[LSC] End of stream data.');

this._callbacks.receive.forEach((callback) => { callback(decodedData); });
}
Expand Down
1 change: 0 additions & 1 deletion functions/Utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ export function invertEndianness (array: Uint8Array): Uint8Array {
*/
export function verifyPacketLength (packet: Uint8Array): boolean {
const length = parseInt(hexToString(new Uint8Array([packet[1], packet[0]])), 16);
console.log('[verifyPacketLength] length:', length, `(${length + 2})`);
if (packet.length === length + 2) {
return true;
}
Expand Down

0 comments on commit dfcdd8b

Please sign in to comment.