node-insim
Version:
An InSim library for NodeJS with TypeScript support
88 lines (87 loc) • 2.97 kB
JavaScript
import { __decorate } from "tslib";
import { byte } from '../decorators';
import { InSimError } from '../errors';
import { copyBuffer, pack } from '../lfspack';
import { ipToUnsignedInteger, isValidIPv4 } from '../utils/ip';
import { SendablePacket } from './base';
import { PacketType } from './enums';
/**
* IP Bans
*
* You can set up to 120 IP addresses that are not allowed to join a host
*/
export class IS_IPB extends SendablePacket {
constructor(data) {
super();
/** 8 + NumB * 4 */
this.Size = 8;
this.Type = PacketType.ISP_IPB;
/** 0 unless this is a reply to a {@link TINY_IPB} request */
this.ReqI = 0;
/** Number of bans in this packet */
this.NumB = 0;
this.Sp0 = 0;
this.Sp1 = 0;
this.Sp2 = 0;
this.Sp3 = 0;
/** IP addresses, 0 to {@link MAX_BANS} ({@link NumB}) */
this.BanIPs = [];
this.banIPsOffset = 8;
this.banIPSize = 4;
this.initialize(data);
}
unpack(buffer) {
super.unpack(buffer);
this.BanIPs = [];
for (let i = 0; i < this.NumB; i++) {
const start = this.banIPsOffset + this.banIPSize * i;
const ipAddressBuffer = copyBuffer(buffer.slice(start, start + this.banIPSize));
const ipAddress = ipAddressBuffer.join('.');
this.BanIPs.push(ipAddress);
}
return this;
}
pack() {
if (this.BanIPs.length > IS_IPB.MAX_BANS) {
throw new RangeError(`IS_IPB - Too many BanIPs set (max is ${IS_IPB.MAX_BANS}`);
}
const invalidIPs = this.BanIPs.filter((ipAddress) => !isValidIPv4(ipAddress));
if (invalidIPs.length > 0) {
throw new RangeError(`IS_IPB - The following IP addresses are not valid IPv4: ${invalidIPs.join()}`);
}
this.NumB = this.BanIPs.length;
this.Size = this.banIPsOffset + this.BanIPs.length * this.banIPSize;
const dataBuffer = super.pack();
const maybeIPBuffer = this.BanIPs.map((ipAddress) => pack('L', [ipToUnsignedInteger(ipAddress)]));
if (maybeIPBuffer.some((buffer) => buffer === null)) {
throw new InSimError('IS_IPB - Failed to pack all BanIPs');
}
const banIPsBuffer = maybeIPBuffer.reduce((acc, banIPs) => new Uint8Array([...acc, ...banIPs]), new Uint8Array());
return new Uint8Array([...dataBuffer, ...banIPsBuffer]);
}
}
IS_IPB.MAX_BANS = 120;
__decorate([
byte()
], IS_IPB.prototype, "Size", void 0);
__decorate([
byte()
], IS_IPB.prototype, "Type", void 0);
__decorate([
byte()
], IS_IPB.prototype, "ReqI", void 0);
__decorate([
byte()
], IS_IPB.prototype, "NumB", void 0);
__decorate([
byte()
], IS_IPB.prototype, "Sp0", void 0);
__decorate([
byte()
], IS_IPB.prototype, "Sp1", void 0);
__decorate([
byte()
], IS_IPB.prototype, "Sp2", void 0);
__decorate([
byte()
], IS_IPB.prototype, "Sp3", void 0);