initial commit

This commit is contained in:
2022-01-10 23:21:47 +03:00
commit e9cd348935
15 changed files with 676 additions and 0 deletions

168
lib/bedrock.js Normal file
View File

@ -0,0 +1,168 @@
/**
* Implementation of the RakNet ping/pong protocol.
* @see https://wiki.vg/Raknet_Protocol#Unconnected_Ping
*
* Data types:
* @see https://wiki.vg/Raknet_Protocol#Data_types
*/
'use strict';
import dgram from 'dgram';
import ByteBuffer from 'bytebuffer';
const START_TIME = new Date().getTime();
/**
* Decode Unconnected Ping
* @param {number} pingId
* @returns {import('bytebuffer')}
* @see https://wiki.vg/Raknet_Protocol#Unconnected_Ping
*/
const UNCONNECTED_PING = (pingId) => {
// 0x01
const bb = new ByteBuffer();
bb.buffer[0] = 0x01;
bb.offset = 1;
return bb.writeLong(pingId).append('00ffff00fefefefefdfdfdfd12345678', 'hex').writeLong(0).flip().compact();
};
/**
* Decode Unconnected Pong
* @param {import('bytebuffer')} buffer
* @see https://wiki.vg/Raknet_Protocol#Unconnected_Pong
*/
const UNCONNECTED_PONG = (buffer) => {
// 0x1c
buffer.offset = 1;
const pingId = buffer.readLong();
const serverId = buffer.readLong();
const offset = buffer.offset += 16;
const nameLength = buffer.readShort();
let advertiseStr;
try {
advertiseStr = buffer.readUTF8String(nameLength);
} catch (err) {
advertiseStr = buffer.readUTF8String(parseInt(err.message.substr(err.message.indexOf(',') + 2, 3)));
}
advertiseStr = advertiseStr.split(/;/g);
const gameId = advertiseStr[0];
const description = advertiseStr[1];
const protocolVersion = advertiseStr[2];
const gameVersion = advertiseStr[3];
const currentPlayers = advertiseStr[4];
const maxPlayers = advertiseStr[5];
const name = advertiseStr[7];
const mode = advertiseStr[8];
return {
pingId,
advertiseStr,
serverId,
offset,
gameId,
description,
protocolVersion,
gameVersion,
currentPlayers,
maxPlayers,
name,
mode
};
};
function ping(host, port = 19132, cb, timeout = 5000) {
const socket = dgram.createSocket('udp4');
// Set manual timeout interval.
// This ensures the connection will NEVER hang regardless of internal state
const timeoutTask = setTimeout(() => {
socket.emit('error', new Error('Socket timeout'));
}, timeout);
const closeSocket = () => {
socket.close();
clearTimeout(timeoutTask);
};
// Generic error handler
// This protects multiple error callbacks given the complex socket state
// This is mostly dangerous since it can swallow errors
let didFireError = false;
const handleError = (err) => {
closeSocket();
if (!didFireError) {
didFireError = true;
cb(null, err);
}
};
try {
const ping = UNCONNECTED_PING(new Date().getTime() - START_TIME);
socket.send(ping.buffer, 0, ping.buffer.length, port, host);
} catch (err) {
handleError(err);
}
socket.on('message', (msg) => {
const buffer = new ByteBuffer().append(msg, 'hex').flip();
const id = buffer.buffer[0];
switch (id) {
// https://wiki.vg/Raknet_Protocol#Unconnected_Ping
case 0x1c: {
const pong = UNCONNECTED_PONG(buffer);
const clientData = {
version: {
name: pong.name,
protocol: pong.protocolVersion
},
players: {
max: pong.maxPlayers,
online: pong.currentPlayers
},
description: pong.description.replace(/\xA7[0-9A-FK-OR]/ig, ''),
gamemode: pong.mode
};
// Close the socket and clear the timeout task
// This is a general cleanup for success conditions
closeSocket();
cb(null, clientData);
break;
}
default: {
handleError(new Error('Received unexpected packet'));
break;
}
}
});
socket.on('error', (err) => handleError(err));
}
/**
* Asynchronously ping Minecraft Bedrock server.
*
* The optional `options` argument can be an object with a `ping` (default is `19132`) or/and `timeout` (default is `5000`) property.
*
* @param {string} host The Bedrock server address.
* @param {import('../types/index.js').PingOptions} options The configuration for pinging Minecraft Bedrock server.
* @returns {Promise<import('../types/lib/bedrock.js').BedrockPingResponse>}
*/
export function pingBedrock(host, options = {}) {
if (!host) throw new Error('Host argument is not provided');
const { port = 19132, timeout = 5000 } = options;
return new Promise((resilve, reject) => {
ping(host, port, (err, res) => {
err ? reject(err) : resilve(res);
}, timeout);
});
}

127
lib/java.js Normal file
View File

@ -0,0 +1,127 @@
/**
* Implementation of the Java Minecraft ping protocol.
* @see https://wiki.vg/Server_List_Ping
*/
'use strict';
import net from 'net';
import varint from './varint.js';
const PROTOCOL_VERSION = 0;
function ping(host, port = 25565, cb, timeout = 5000) {
const socket = net.createConnection(({ host, port }));
// Set manual timeout interval.
// This ensures the connection will NEVER hang regardless of internal state
const timeoutTask = setTimeout(() => {
socket.emit('error', new Error('Socket timeout'));
}, timeout);
const closeSocket = () => {
socket.destroy();
clearTimeout(timeoutTask);
};
// Generic error handler
// This protects multiple error callbacks given the complex socket state
// This is mostly dangerous since it can swallow errors
let didFireError = false;
const handleError = (err) => {
closeSocket();
if (!didFireError) {
didFireError = true;
cb(null, err);
}
};
// #setNoDelay instantly flushes data during read/writes
// This prevents the runtime from delaying the write at all
socket.setNoDelay(true);
socket.on('connect', () => {
const handshake = varint.concat([
varint.encodeInt(0),
varint.encodeInt(PROTOCOL_VERSION),
varint.encodeInt(host.length),
varint.encodeString(host),
varint.encodeUShort(port),
varint.encodeInt(1)
]);
socket.write(handshake);
const request = varint.concat([
varint.encodeInt(0)
]);
socket.write(request);
});
let incomingBuffer = Buffer.alloc(0);
socket.on('data', (data) => {
incomingBuffer = Buffer.concat([incomingBuffer, data]);
// Wait until incomingBuffer is at least 5 bytes long to ensure it has captured the first VarInt value
// This value is used to determine the full read length of the response
// "VarInts are never longer than 5 bytes"
// https://wiki.vg/Data_types#VarInt_and_VarLong
if (incomingBuffer.length < 5) {
return;
}
let offset = 0;
const packetLength = varint.decodeInt(incomingBuffer, offset);
// Ensure incomingBuffer contains the full response
if (incomingBuffer.length - offset < packetLength) {
return;
}
const packetId = varint.decodeInt(incomingBuffer, varint.decodeLength(packetLength));
if (packetId === 0) {
const data = incomingBuffer.slice(varint.decodeLength(packetLength) + varint.decodeLength(packetId));
const responseLength = varint.decodeInt(data, 0);
const response = data.slice(varint.decodeLength(responseLength), varint.decodeLength(responseLength) + responseLength);
try {
const message = JSON.parse(response);
cb(null, message);
// Close the socket and clear the timeout task
closeSocket();
} catch (err) {
handleError(err);
}
} else {
handleError(new Error('Received unexpected packet'));
}
});
socket.on('error', handleError);
}
/**
* Asynchronously ping Minecraft Java server.
*
* The optional `options` argument can be an object with a `ping` (default is `25565`) or/and `timeout` (default is `5000`) property.
*
* @param {string} host The Java server address.
* @param {import('../types/index.js').PingOptions} options The configuration for pinging Minecraft Java server.
* @returns {Promise<import('../types/lib/java.js').JavaPingResponse>}
*/
export function pingJava(host, options = {}) {
if (!host) throw new Error('Host argument is not provided');
const { port = 25565, timeout = 5000 } = options;
return new Promise((resolve, reject) => {
ping(host, port, (err, res) => {
err ? reject(err) : resolve(res);
}, timeout);
});
}

90
lib/varint.js Normal file
View File

@ -0,0 +1,90 @@
// https://wiki.vg/Data_types
const varint = {
encodeInt: (val) => {
// "constInts are never longer than 5 bytes"
// https://wiki.vg/Data_types#constInt_and_constLong
const buf = Buffer.alloc(5);
let written = 0;
while (true) {
if ((val & 0xFFFFFF80) === 0) {
buf.writeUInt8(val, written++);
break;
} else {
buf.writeUInt8(val & 0x7F | 0x80, written++);
val >>>= 7;
}
}
return buf.slice(0, written);
},
encodeString: (val) => {
return Buffer.from(val, 'utf-8');
},
encodeUShort: (val) => {
return Buffer.from([val >> 8, val & 0xFF]);
},
concat: (chunks) => {
let length = 0;
for (const chunk of chunks) {
length += chunk.length;
}
const buffer = [
varint.encodeInt(length),
...chunks
];
return Buffer.concat(buffer);
},
decodeInt: (buffer, offset) => {
let val = 0;
let count = 0;
while (true) {
const b = buffer.readUInt8(offset++);
val |= (b & 0x7F) << count++ * 7;
if ((b & 0x80) != 128) {
break;
}
}
return val;
},
// The number of bytes that the last .decodeInt() call had to use to decode.
decodeLength: (val) => {
const N1 = Math.pow(2, 7);
const N2 = Math.pow(2, 14);
const N3 = Math.pow(2, 21);
const N4 = Math.pow(2, 28);
const N5 = Math.pow(2, 35);
const N6 = Math.pow(2, 42);
const N7 = Math.pow(2, 49);
const N8 = Math.pow(2, 56);
const N9 = Math.pow(2, 63);
return (
val < N1 ? 1
: val < N2 ? 2
: val < N3 ? 3
: val < N4 ? 4
: val < N5 ? 5
: val < N6 ? 6
: val < N7 ? 7
: val < N8 ? 8
: val < N9 ? 9
: 10
);
}
};
export default varint;