q13x-eaglerproxy/listener.ts

40 lines
1.8 KiB
TypeScript
Raw Normal View History

2022-12-20 11:33:55 -08:00
import { EAGLERCRAFT_SKIN_CHANNEL_NAME } from "./eaglerPacketDef.js";
import { processClientReqPacket, unpackChannelMessage } from "./eaglerSkin.js";
2022-12-18 05:39:38 -08:00
import { Logger } from "./logger.js";
2022-12-20 11:33:55 -08:00
import { State, ProxiedPlayer } from "./types.js";
import { doHandshake, handleMotd } from "./utils.js";
2022-12-18 05:39:38 -08:00
const logger = new Logger("PacketHandler")
export function handlePacket(packet: Buffer, client: ProxiedPlayer) {
if (client.state == State.PRE_HANDSHAKE) {
if (packet.toString() === "Accept: MOTD") {
handleMotd(client)
} else if (!(client as any)._handled) {
;(client as any)._handled = true
doHandshake(client, packet)
2022-12-20 11:33:55 -08:00
.catch(err => {
logger.warn(`Error occurred whilst handling handshake! Error: ${err.stack ?? err}`)
})
} else if (!(client as any)._handled && packet[0] == 0x17) {
const decoded = unpackChannelMessage(packet)
if (decoded.channel == EAGLERCRAFT_SKIN_CHANNEL_NAME) {
client.queuedEaglerSkinPackets.push(decoded)
}
2022-12-18 05:39:38 -08:00
}
} else if (client.state == State.POST_HANDSHAKE) {
if (!client.remoteConnection || client.remoteConnection.socket.closed) {
2022-12-20 11:33:55 -08:00
logger.warn(`Received packet from player ${client.username} that is marked as post handshake, but is disconnected from the game server? Disconnecting due to illegal state.`)
2022-12-18 05:39:38 -08:00
client.ws.close()
} else {
2022-12-20 11:33:55 -08:00
if (packet[0] == 0x17) {
const decoded = unpackChannelMessage(packet)
if (decoded.channel == EAGLERCRAFT_SKIN_CHANNEL_NAME) {
processClientReqPacket(decoded, client)
}
} else {
client.remoteConnection.writeRaw(packet)
}
2022-12-18 05:39:38 -08:00
}
}
}