mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-20 23:53:13 +09:00
Create lobbies on demand and only list servers on the player's version
When a player connects with a Factorio version and set of built in mods no lobby runs, the lobby plugin now creates one on a connected host that has the version installed or can download it, with a mod pack matching the player's built in mods. This lets a cluster accept players on several Factorio versions on the same port without any setup. It can be turned off with lobby.auto_create. To pick the mod pack the proxy now waits for the whole connection confirm before routing and passes the mods listed in it to the playerProxyRoute hook. Hosts answer the new HostFactorioVersionsRequest with the versions they have installed. The server list in lobbies only shows instances on the Factorio version of the lobby, with a checkbox to also show the others greyed out.
This commit is contained in:
14 files changed
+582
-39
No files matched your search
@@ -28,6 +28,8 @@ export interface PlayerProxyRouteRequest {
|
||||
listenPort: number;
|
||||
/** Instance the proxy port is dedicated to, if any */
|
||||
portInstanceId?: number;
|
||||
/** Mods enabled in the client, including built in mods like base, or undefined if they couldn't be read */
|
||||
mods?: protocol.ModId[];
|
||||
}
|
||||
|
||||
export interface PlayerProxyRoute {
|
||||
@@ -56,6 +58,7 @@ type ClientSession = {
|
||||
/** Fragments of the client's ConnectionRequestReplyConfirm by fragment number */
|
||||
confirmFragments: Map<number, Buffer>;
|
||||
confirmMessageId?: number;
|
||||
confirmLastFragment?: number;
|
||||
confirmServerRequestIdOffset?: number;
|
||||
state: "handshake" | "routing" | "connecting" | "connected" | "failed";
|
||||
route?: PlayerProxyRoute;
|
||||
@@ -367,6 +370,7 @@ export default class PlayerProxyServer {
|
||||
if (session.confirmMessageId !== undefined && session.confirmMessageId !== header.messageId) {
|
||||
// The client is sending a different confirm message, start over with it
|
||||
session.confirmFragments.clear();
|
||||
session.confirmLastFragment = undefined;
|
||||
}
|
||||
session.confirmMessageId = header.messageId;
|
||||
session.confirmServerRequestIdOffset = confirm.serverRequestIdOffset;
|
||||
@@ -384,8 +388,17 @@ export default class PlayerProxyServer {
|
||||
if (session.confirmFragments.size < MAX_PENDING_PACKETS) {
|
||||
session.confirmFragments.set(fragmentNumber, message);
|
||||
}
|
||||
if (!header.fragmented || header.lastFragment) {
|
||||
session.confirmLastFragment = fragmentNumber;
|
||||
}
|
||||
|
||||
if (session.state === "handshake" && session.username !== undefined && session.request) {
|
||||
// Routing waits for the whole message as plugins may use the mods of the client listed in it
|
||||
if (
|
||||
session.state === "handshake"
|
||||
&& session.username !== undefined
|
||||
&& session.request
|
||||
&& this._confirmComplete(session)
|
||||
) {
|
||||
session.state = "routing";
|
||||
this._routeSession(session).catch(err => {
|
||||
this._logger.error(`Unexpected error routing player ${session.username}:\n${err.stack}`);
|
||||
@@ -394,6 +407,28 @@ export default class PlayerProxyServer {
|
||||
}
|
||||
}
|
||||
|
||||
private _confirmComplete(session: ClientSession) {
|
||||
if (session.confirmLastFragment === undefined) {
|
||||
return false;
|
||||
}
|
||||
for (let i = 0; i <= session.confirmLastFragment; i++) {
|
||||
if (!session.confirmFragments.has(i)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private _confirmMods(session: ClientSession) {
|
||||
const fragments = [...session.confirmFragments].sort(([a], [b]) => a - b).map(([, fragment]) => fragment);
|
||||
try {
|
||||
return protocol.parseConfirmMods(protocol.joinPayload(fragments));
|
||||
} catch (err: any) {
|
||||
this._logger.verbose(`Unable to read mods of ${session.username}: ${err.message}`);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private _patchConfirm(session: ClientSession, message: Buffer, fragmentNumber: number) {
|
||||
if (fragmentNumber !== 0 || session.confirmServerRequestIdOffset === undefined) {
|
||||
return message;
|
||||
@@ -411,6 +446,7 @@ export default class PlayerProxyServer {
|
||||
clientPort: session.clientPort,
|
||||
listenPort: session.listener.port,
|
||||
portInstanceId: session.listener.instanceId,
|
||||
mods: this._confirmMods(session),
|
||||
};
|
||||
|
||||
const instanceId = await this._controller.resolvePlayerRoute(request);
|
||||
|
||||
@@ -267,6 +267,54 @@ export function parseConnectionRequestReplyConfirm(buffer: Buffer): ConnectionRe
|
||||
return { clientRequestId, serverRequestId, serverRequestIdOffset, username };
|
||||
}
|
||||
|
||||
/** Mod enabled in a Factorio client */
|
||||
export interface ModId {
|
||||
name: string;
|
||||
version: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Join the payloads of the fragments of a message
|
||||
*
|
||||
* @param fragments -
|
||||
* Fragments of the message in order of fragment number, or the message
|
||||
* if it's not fragmented.
|
||||
* @returns the payload of the message.
|
||||
*/
|
||||
export function joinPayload(fragments: Buffer[]) {
|
||||
return Buffer.concat(fragments.map(fragment => fragment.subarray(parseHeader(fragment).payloadOffset)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the mods enabled in the client from a ConnectionRequestReplyConfirm
|
||||
*
|
||||
* @param payload - Complete payload of the message, see {@link joinPayload}.
|
||||
* @returns name and version of each mod.
|
||||
*/
|
||||
export function parseConfirmMods(payload: Buffer): ModId[] {
|
||||
const reader = new BufferReader(payload);
|
||||
reader.readUInt32LE(); // connectionRequestIDGeneratedOnClient
|
||||
reader.readUInt32LE(); // connectionRequestIDGeneratedOnServer
|
||||
reader.readUInt32LE(); // instanceID
|
||||
reader.readString(); // username
|
||||
reader.readString(); // password
|
||||
reader.readString(); // serverKey
|
||||
reader.readString(); // serverKeyTimestamp
|
||||
reader.readUInt32LE(); // coreChecksum
|
||||
reader.readUInt32LE(); // prototypeListChecksum
|
||||
const count = reader.readSpaceOptimizedUInt32();
|
||||
const mods: ModId[] = [];
|
||||
for (let i = 0; i < count; i++) {
|
||||
const name = reader.readString();
|
||||
const version = [
|
||||
reader.readSpaceOptimizedUInt16(), reader.readSpaceOptimizedUInt16(), reader.readSpaceOptimizedUInt16(),
|
||||
].join(".");
|
||||
reader.readUInt32LE(); // crc
|
||||
mods.push({ name, version });
|
||||
}
|
||||
return mods;
|
||||
}
|
||||
|
||||
export function encodeConnectionRequest(version: ApplicationVersion, clientRequestId: number, messageId = 0) {
|
||||
const writer = new BufferWriter();
|
||||
writer.writeUInt8(MessageType.ConnectionRequest);
|
||||
|
||||
@@ -15,6 +15,7 @@ import { logger } from "@clusterio/lib";
|
||||
import type { HostConnector } from "../host.js";
|
||||
import Instance from "./Instance.js";
|
||||
import InstanceConnection from "./InstanceConnection.js";
|
||||
import { listFactorioVersions } from "./server.js";
|
||||
import { BaseHostPlugin, HostHooks } from "./BaseHostPlugin.js";
|
||||
|
||||
|
||||
@@ -462,6 +463,7 @@ export default class Host extends lib.Link {
|
||||
this.handle(lib.HostConfigSetFieldRequest, this.handleHostConfigSetFieldRequest.bind(this));
|
||||
this.handle(lib.HostConfigSetPropRequest, this.handleHostConfigSetPropRequest.bind(this));
|
||||
this.handle(lib.HostMetricsRequest, this.handleHostMetricsRequest.bind(this));
|
||||
this.handle(lib.HostFactorioVersionsRequest, this.handleHostFactorioVersionsRequest.bind(this));
|
||||
this.handle(lib.SyncUserListsEvent, this.handleSyncUserListsEvent.bind(this));
|
||||
this.handle(lib.SystemInfoRequest, this.handleSystemInfoRequest.bind(this));
|
||||
this.handle(lib.PluginListRequest, this.handlePluginListRequest.bind(this));
|
||||
@@ -1020,6 +1022,23 @@ export default class Host extends lib.Link {
|
||||
return null;
|
||||
}
|
||||
|
||||
async handleHostFactorioVersionsRequest() {
|
||||
let installed: Awaited<ReturnType<typeof listFactorioVersions>>;
|
||||
try {
|
||||
installed = await listFactorioVersions(this.config.get("host.factorio_directory"));
|
||||
} catch (err: any) {
|
||||
if (err.code !== "ENOENT") {
|
||||
throw err;
|
||||
}
|
||||
installed = { direct: false, versions: new Set() };
|
||||
}
|
||||
return {
|
||||
versions: [...installed.versions],
|
||||
// Matches the conditions for downloads in FactorioServer.checkForUpdates
|
||||
canDownload: !installed.direct && process.platform === "linux",
|
||||
};
|
||||
}
|
||||
|
||||
async handleHostMetricsRequest() {
|
||||
let requests: Promise<InstanceType<typeof lib.InstanceMetricsRequest["Response"]>>[] = [];
|
||||
for (let instanceConnection of this.instanceConnections.values()) {
|
||||
|
||||
@@ -79,7 +79,7 @@ function versionOrder(a: string, b: string) {
|
||||
* @param factorioDir - Path to Factorio installation dirs.
|
||||
* @returns Set of installed factorio versions
|
||||
*/
|
||||
async function listFactorioVersions(factorioDir: string) {
|
||||
export async function listFactorioVersions(factorioDir: string) {
|
||||
const versions = new Set<lib.FullVersion>();
|
||||
|
||||
const directVersion = await getFactorioVersion(factorioDir);
|
||||
|
||||
@@ -36,6 +36,19 @@ export class HostUpdateRequest {
|
||||
static permission = "core.host.update" as const;
|
||||
}
|
||||
|
||||
/** Factorio versions installed on a host, used by the controller to place instances */
|
||||
export class HostFactorioVersionsRequest {
|
||||
declare ["constructor"]: typeof HostFactorioVersionsRequest;
|
||||
static type = "request" as const;
|
||||
static src = "controller" as const;
|
||||
static dst = "host" as const;
|
||||
static Response = plainJson(Type.Object({
|
||||
"versions": Type.Array(Type.String()),
|
||||
/** True if the host downloads versions that are not installed when an instance needs them */
|
||||
"canDownload": Type.Boolean(),
|
||||
}));
|
||||
}
|
||||
|
||||
export class HostConfigGetRequest {
|
||||
declare ["constructor"]: typeof HostConfigGetRequest;
|
||||
static type = "request" as const;
|
||||
|
||||
@@ -56,6 +56,7 @@ export const dataClasses: (RequestClass<unknown, unknown> | EventClass<unknown>)
|
||||
host.HostInfoUpdateEvent,
|
||||
host.HostUpdatesEvent,
|
||||
host.HostMetricsRequest,
|
||||
host.HostFactorioVersionsRequest,
|
||||
host.ControllerConnectionEvent,
|
||||
host.PrepareControllerDisconnectRequest,
|
||||
host.SyncUserListsEvent,
|
||||
|
||||
Reference in new issue
Block a user