mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-17 15:33:12 +09:00
Merge pull request #996 from bbassie/feature/instance-udp
Add UDP communication support for instances
This commit is contained in:
19 files changed
+708
-25
No files matched your search
@@ -259,6 +259,22 @@ export class BaseInstancePlugin {
|
||||
return await this.instance.sendRcon(message, expectEmpty, this.info.name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send UDP message to instance
|
||||
*
|
||||
* Send a UDP packet to the Factorio server, which is delivered in-game
|
||||
* as an on_udp_packet_received event. Delivery is not guaranteed and
|
||||
* the payload should be kept well below 64 kB. Requires the LuaUdp
|
||||
* plugin feature.
|
||||
*
|
||||
* This should not be called before onStart or after onStop.
|
||||
*
|
||||
* @param message - payload of the packet to send.
|
||||
*/
|
||||
async sendUdp(message: string | Buffer): Promise<void> {
|
||||
await this.instance.sendUdp(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send serially ordered RCON message to instance
|
||||
*
|
||||
|
||||
@@ -233,6 +233,8 @@ export default class Instance extends lib.Link {
|
||||
gamePort: this.config.get("factorio.game_port") ?? host.assignGamePort(this.id),
|
||||
rconPort: this.config.get("factorio.rcon_port") ?? undefined,
|
||||
rconPassword: this.config.get("factorio.rcon_password") ?? undefined,
|
||||
enableLuaUdp: this.config.get("factorio.enable_lua_udp"),
|
||||
luaUdpPort: this.config.get("factorio.lua_udp_port") ?? undefined,
|
||||
enableWhitelist: this.config.get("factorio.enable_whitelist"),
|
||||
enableAuthserverBans: this.config.get("factorio.enable_authserver_bans"),
|
||||
verboseLogging: this.config.get("factorio.verbose_logging"),
|
||||
@@ -506,6 +508,23 @@ end`.replace(/\r?\n/g, " ");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send UDP message to the Factorio server
|
||||
*
|
||||
* Delivered in-game as an on_udp_packet_received event. Requires
|
||||
* factorio.enable_lua_udp to be enabled on the instance.
|
||||
*
|
||||
* @param message - payload of the packet to send.
|
||||
*/
|
||||
async sendUdp(message: string | Buffer) {
|
||||
if (!this.config.get("factorio.enable_lua_udp")) {
|
||||
throw new Error(
|
||||
"Attempted to send UDP message while Lua UDP is disabled. See config factorio.enable_lua_udp."
|
||||
);
|
||||
}
|
||||
await this.server.sendUdp(message);
|
||||
}
|
||||
|
||||
static async listSaves(instanceId: number, savesDir: string, loadedSave: string | null) {
|
||||
let defaultSave = null;
|
||||
if (loadedSave === null) {
|
||||
@@ -1090,7 +1109,8 @@ end`.replace(/\r?\n/g, " ");
|
||||
*/
|
||||
async updateInstanceData() {
|
||||
let name = lib.escapeString(this.name);
|
||||
await this.sendRcon(`/sc clusterio_private.update_instance(${this.id}, "${name}")`, true);
|
||||
let hostUdpPort = this.server.hostUdpPort ?? "nil";
|
||||
await this.sendRcon(`/sc clusterio_private.update_instance(${this.id}, "${name}", ${hostUdpPort})`, true);
|
||||
}
|
||||
|
||||
async updateFactorioSettings(current: Record<string, unknown>, previous: Record<string, unknown>) {
|
||||
|
||||
+139
-8
@@ -2,6 +2,7 @@
|
||||
import fs from "node:fs/promises";
|
||||
import { type FSWatcher, createWriteStream, watch as fsWatch, writeFileSync } from "node:fs";
|
||||
import child_process from "child_process";
|
||||
import dgram from "dgram";
|
||||
import path from "path";
|
||||
import stream from "node:stream";
|
||||
import { pipeline } from "node:stream/promises";
|
||||
@@ -303,6 +304,15 @@ async function generatePassword(length: number) {
|
||||
}
|
||||
}
|
||||
|
||||
function unescapeChannel(channel: Buffer) {
|
||||
return channel
|
||||
.toString("utf-8")
|
||||
.replace(/\\x([0-9a-f]{2})/g, (match, p1) => (
|
||||
String.fromCharCode(parseInt(p1, 16))
|
||||
))
|
||||
;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interpret lines of output from Factorio
|
||||
*
|
||||
@@ -425,6 +435,9 @@ const outputHeuristics: Heuristic[] = [
|
||||
filter: { type: "log", message: /^Starting RCON interface/ },
|
||||
action: function() {
|
||||
this._startRcon().catch((err) => { this.emit("error", err); });
|
||||
if (this.enableLuaUdp) {
|
||||
this._startUdp().catch((err) => { this.emit("error", err); });
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
@@ -556,6 +569,10 @@ export interface FactorioServerOptions {
|
||||
rconPort?: number,
|
||||
/** Password use for RCON. */
|
||||
rconPassword?: string,
|
||||
/** Enable UDP messaging with the Factorio server. */
|
||||
enableLuaUdp?: boolean,
|
||||
/** UDP port the Factorio server receives Lua UDP messages on. */
|
||||
luaUdpPort?: number,
|
||||
/** Turn on whitelisting. */
|
||||
enableWhitelist?: boolean,
|
||||
/** Enable Factorio.com based multiplayer bans. */
|
||||
@@ -600,8 +617,9 @@ type FactorioServerEvents = {
|
||||
"_saving": [],
|
||||
"_saved": [],
|
||||
|
||||
// IPS events
|
||||
// IPC events
|
||||
[ipcEvent: `ipc-${string}`]: [ event: any ],
|
||||
[udpEvent: `udp-${string}`]: [ data: Buffer ],
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -621,6 +639,8 @@ type FactorioServerEvents = {
|
||||
* - autosave-fnished - invoked when the autosave finished
|
||||
* - save-finished - invoked when the server has finished a manual save
|
||||
* - exit - invoked when the sterver has exited
|
||||
* - ipc-<channel> - invoked with data sent with send_json in-game
|
||||
* - udp-<channel> - invoked with data sent with send_udp in-game
|
||||
* @extends events.EventEmitter
|
||||
*/
|
||||
export class FactorioServer extends events.EventEmitter<FactorioServerEvents> {
|
||||
@@ -632,6 +652,10 @@ export class FactorioServer extends events.EventEmitter<FactorioServerEvents> {
|
||||
rconPort: number;
|
||||
/** Password used for RCON on the Factorio game server */
|
||||
rconPassword: string;
|
||||
/** Enable UDP messaging with the Factorio game server */
|
||||
enableLuaUdp: boolean;
|
||||
/** UDP port the Factorio game server receives Lua UDP messages on */
|
||||
luaUdpPort: number;
|
||||
/** Enable player whitelist */
|
||||
enableWhitelist: boolean;
|
||||
/** Enable Factorio.com based multiplayer bans **/
|
||||
@@ -661,6 +685,7 @@ export class FactorioServer extends events.EventEmitter<FactorioServerEvents> {
|
||||
_server: child_process.ChildProcessWithoutNullStreams | null = null;
|
||||
_rconClient: Rcon | null= null;
|
||||
_rconReady = false;
|
||||
_udpSocket: dgram.Socket | null = null;
|
||||
_gameReady = false;
|
||||
_stripRegExp?: RegExp;
|
||||
_maxConcurrentCommands = 5;
|
||||
@@ -693,6 +718,10 @@ export class FactorioServer extends events.EventEmitter<FactorioServerEvents> {
|
||||
this.rconPort = options.rconPort || randomDynamicPort();
|
||||
/** Password used for RCON on the Factorio game server */
|
||||
this.rconPassword = options.rconPassword as string; // init will generate one if not there
|
||||
/** Enable UDP messaging with the Factorio game server */
|
||||
this.enableLuaUdp = options.enableLuaUdp || false;
|
||||
/** UDP port the Factorio game server receives Lua UDP messages on */
|
||||
this.luaUdpPort = options.luaUdpPort || randomDynamicPort();
|
||||
/** Enable player whitelist */
|
||||
this.enableWhitelist = options.enableWhitelist || false;
|
||||
/** Enable Factorio.com based multiplayer bans **/
|
||||
@@ -755,19 +784,24 @@ export class FactorioServer extends events.EventEmitter<FactorioServerEvents> {
|
||||
}));
|
||||
}
|
||||
|
||||
handleUdp(channel: string, handler: (data: Buffer) => Promise<void>) {
|
||||
// Runs from the socket callback, so synchronous throws must be caught here too
|
||||
this.on(`udp-${channel}`, async (data) => {
|
||||
try {
|
||||
await handler(data);
|
||||
} catch (err: any) {
|
||||
this._logger.error(`Error handling udp event:\n${err.stack ?? err.message}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async _handleIpc(line: Buffer) {
|
||||
let channelEnd = line.indexOf("?");
|
||||
if (channelEnd === -1) {
|
||||
throw new Error(`Malformed IPC line "${line.toString()}"`);
|
||||
}
|
||||
|
||||
let channel = line
|
||||
.subarray(6, channelEnd)
|
||||
.toString("utf-8")
|
||||
.replace(/\\x([0-9a-f]{2})/g, (match, p1) => (
|
||||
String.fromCharCode(parseInt(p1, 16))
|
||||
))
|
||||
;
|
||||
let channel = unescapeChannel(line.subarray(6, channelEnd));
|
||||
|
||||
let type = line.subarray(channelEnd + 1, channelEnd + 2).toString("utf-8");
|
||||
let content;
|
||||
@@ -805,6 +839,74 @@ export class FactorioServer extends events.EventEmitter<FactorioServerEvents> {
|
||||
}
|
||||
}
|
||||
|
||||
_handleUdpMessage(message: Buffer, rinfo: dgram.RemoteInfo) {
|
||||
// Factorio sends from the socket bound to the Lua UDP port, anything
|
||||
// else is some other local process.
|
||||
if (rinfo.port !== this.luaUdpPort) {
|
||||
this._logger.warn(`Ignoring UDP packet from unexpected source ${rinfo.address}:${rinfo.port}`);
|
||||
return;
|
||||
}
|
||||
|
||||
let channelEnd = message.indexOf("?");
|
||||
if (channelEnd === -1) {
|
||||
this._logger.warn(`Ignoring malformed UDP packet "${message.subarray(0, 100).toString("utf-8")}"`);
|
||||
return;
|
||||
}
|
||||
|
||||
let channel = unescapeChannel(message.subarray(0, channelEnd));
|
||||
let data = message.subarray(channelEnd + 1);
|
||||
if (!this.emit(`udp-${channel}`, data)) {
|
||||
this._logger.warn(`Warning: Unhandled udp-${channel}`);
|
||||
}
|
||||
}
|
||||
|
||||
async _startUdp() {
|
||||
if (this._udpSocket !== null) {
|
||||
throw Error("UDP socket is already open");
|
||||
}
|
||||
|
||||
const socket = dgram.createSocket("udp4");
|
||||
socket.on("message", (message, rinfo) => this._handleUdpMessage(message, rinfo));
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
socket.once("error", reject);
|
||||
socket.bind(0, "127.0.0.1", () => {
|
||||
socket.off("error", reject);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
} catch (err: any) {
|
||||
this._logger.error(`Failed to open UDP socket:\n${err?.stack ?? err?.message ?? err}`);
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
socket.on("error", err => this.emit("error", err));
|
||||
this._udpSocket = socket;
|
||||
}
|
||||
|
||||
// Factorio before 2.1.10 crashes when a packet is received on a headless server
|
||||
_checkLuaUdpVersion() {
|
||||
if (this.enableLuaUdp && lib.integerFullVersion(this._version!) < lib.integerFullVersion("2.1.10")) {
|
||||
throw new Error("Lua UDP requires Factorio 2.1.10 or later");
|
||||
}
|
||||
}
|
||||
|
||||
_stopUdp() {
|
||||
if (this._udpSocket) {
|
||||
this._udpSocket.close();
|
||||
this._udpSocket = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* UDP port on localhost the host receives Lua UDP messages on
|
||||
*
|
||||
* Only available while the server is running with Lua UDP enabled.
|
||||
*/
|
||||
get hostUdpPort(): number | undefined {
|
||||
return this._udpSocket?.address().port;
|
||||
}
|
||||
|
||||
_handleOutput(rawLine: Buffer, source: "stdout" | "stderr") {
|
||||
if (rawLine.subarray(0, 6).equals(Buffer.from("\f$ipc:"))) {
|
||||
this._handleIpc(rawLine).catch(err => this.emit("error", err));
|
||||
@@ -1087,6 +1189,7 @@ export class FactorioServer extends events.EventEmitter<FactorioServerEvents> {
|
||||
this._server = null;
|
||||
this._rconClient = null;
|
||||
this._rconReady = false;
|
||||
this._udpSocket = null;
|
||||
this._gameReady = false;
|
||||
this._unexpected = [];
|
||||
this._killed = false;
|
||||
@@ -1132,6 +1235,7 @@ export class FactorioServer extends events.EventEmitter<FactorioServerEvents> {
|
||||
if (this._rconClient) {
|
||||
this._rconClient.end().catch(() => {});
|
||||
}
|
||||
this._stopUdp();
|
||||
|
||||
if (this._whitelistWatcher) {
|
||||
this._whitelistWatcher.close();
|
||||
@@ -1150,6 +1254,7 @@ export class FactorioServer extends events.EventEmitter<FactorioServerEvents> {
|
||||
if (this._rconClient) {
|
||||
this._rconClient.end().catch(() => {});
|
||||
}
|
||||
this._stopUdp();
|
||||
|
||||
if (this._whitelistWatcher) {
|
||||
this._whitelistWatcher.close();
|
||||
@@ -1248,6 +1353,7 @@ export class FactorioServer extends events.EventEmitter<FactorioServerEvents> {
|
||||
*/
|
||||
async start(save: string) {
|
||||
this._check(["init"]);
|
||||
this._checkLuaUdpVersion();
|
||||
this._state = "running";
|
||||
|
||||
try {
|
||||
@@ -1263,6 +1369,7 @@ export class FactorioServer extends events.EventEmitter<FactorioServerEvents> {
|
||||
"--port", String(this.gamePort),
|
||||
"--rcon-port", String(this.rconPort),
|
||||
"--rcon-password", this.rconPassword,
|
||||
...(this.enableLuaUdp ? ["--enable-lua-udp", String(this.luaUdpPort)] : []),
|
||||
...(this.enableWhitelist ? ["--use-server-whitelist"] : []),
|
||||
...(this.enableAuthserverBans ? ["--use-authserver-bans"] : []),
|
||||
...(this.verboseLogging ? ["--verbose"] : []),
|
||||
@@ -1300,6 +1407,7 @@ export class FactorioServer extends events.EventEmitter<FactorioServerEvents> {
|
||||
*/
|
||||
async startScenario(scenario: string, seed?: number, mapGenSettings?: object, mapSettings?: object) {
|
||||
this._check(["init"]);
|
||||
this._checkLuaUdpVersion();
|
||||
this._state = "running";
|
||||
|
||||
try {
|
||||
@@ -1321,6 +1429,7 @@ export class FactorioServer extends events.EventEmitter<FactorioServerEvents> {
|
||||
"--port", String(this.gamePort),
|
||||
"--rcon-port", String(this.rconPort),
|
||||
"--rcon-password", this.rconPassword,
|
||||
...(this.enableLuaUdp ? ["--enable-lua-udp", String(this.luaUdpPort)] : []),
|
||||
...(this.enableWhitelist ? ["--use-server-whitelist"] : []),
|
||||
...(this.enableAuthserverBans ? ["--use-authserver-bans"] : []),
|
||||
...(this.verboseLogging ? ["--verbose"] : []),
|
||||
@@ -1401,6 +1510,27 @@ export class FactorioServer extends events.EventEmitter<FactorioServerEvents> {
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send UDP message to the server
|
||||
*
|
||||
* Sends a UDP packet to the Lua UDP port of the Factorio server, which
|
||||
* is delivered in-game as an on_udp_packet_received event. Delivery is
|
||||
* not guaranteed. Requires Lua UDP to be enabled.
|
||||
*
|
||||
* @param message - payload of the packet to send.
|
||||
*/
|
||||
async sendUdp(message: string | Buffer) {
|
||||
this._check(["running", "stopping"]);
|
||||
if (!this._udpSocket) {
|
||||
throw new Error("UDP socket is not open");
|
||||
}
|
||||
|
||||
const socket = this._udpSocket;
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
socket.send(message, this.luaUdpPort, "127.0.0.1", err => (err ? reject(err) : resolve()));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Timeout in ms to wait after a shutdown is requested before killing the
|
||||
* process. Defaults to 0 meaning no timeout
|
||||
@@ -1436,6 +1566,7 @@ export class FactorioServer extends events.EventEmitter<FactorioServerEvents> {
|
||||
if (this._rconClient) {
|
||||
this._rconClient.end().catch(() => {});
|
||||
}
|
||||
this._stopUdp();
|
||||
if (this._whitelistWatcher) {
|
||||
this._whitelistWatcher.close();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user