package com.aranroig.shell;
import com.aranroig.Codecraft;
import com.aranroig.payloads.ClientboundShellClosedPayload;
import com.aranroig.payloads.ClientboundShellOutputPayload;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* The server half of the editor's terminal: at most one {@link ShellSession}
* per player, spawned when they press the terminal button and killed when they
* close the pane, leave, or the server stops.
*
*
This hands out a real shell on the machine the server runs on, to
* anyone who can open the editor. Commands run as the server's user, in
* the server's files, with everything that implies. That is fine on a
* single-player game or a server among friends who all get the keys to the
* box; it is emphatically not something to leave open to strangers.
*
* Payload handlers run on the server thread, so spawning, submitting and
* closing need no locking; only the output threads report back from outside,
* through {@link #sessionEnded}, hence the concurrent map.
*/
public final class ShellManager {
private static final Map SESSIONS = new ConcurrentHashMap<>();
private ShellManager() {
}
/** Kills every shell when its player leaves or the server goes down. */
public static void install() {
ServerPlayConnectionEvents.DISCONNECT.register((handler, server) -> close(handler.player));
ServerLifecycleEvents.SERVER_STOPPING.register(ShellManager::closeAll);
}
/**
* Gives {@code player} a shell, opening it at the size of the terminal
* pane that asked ({@code rows}/{@code cols} of 0: the shell's own
* defaults). Pressing the button with one already running does not
* disturb it: the pane keeps its scrollback, so the same session is
* simply attached again and told so.
*/
public static void spawn(ServerPlayer player, int rows, int cols) {
ShellSession existing = SESSIONS.get(player.getUUID());
if (existing != null && existing.isAlive()) {
send(player, new ClientboundShellOutputPayload("shell already running — this pane is attached to it\r\n"));
return;
}
if (existing != null) existing.close();
ShellSession session = new ShellSession(player);
try {
session.start(rows, cols);
SESSIONS.put(player.getUUID(), session);
} catch (IOException e) {
Codecraft.LOGGER.warn("Could not spawn a shell for {}", player.getName().getString(), e);
send(player, new ClientboundShellOutputPayload("could not start a shell: " + e.getMessage() + "\r\n"));
send(player, new ClientboundShellClosedPayload("could not start a shell"));
}
}
/** Forwards what the pane's keyboard produced, as it is, to that player's shell. */
public static void submit(ServerPlayer player, String bytes) {
ShellSession session = SESSIONS.get(player.getUUID());
if (session == null || !session.isAlive()) {
send(player, new ClientboundShellOutputPayload("no shell running — open one with the Shell button\r\n"));
return;
}
session.submitInput(bytes);
}
/**
* Resizes the pty behind that player's shell to the size their terminal
* pane now has. Nothing is said when there is no live shell to size: the
* next spawn opens at whatever size asks anyway.
*/
public static void resize(ServerPlayer player, int rows, int cols) {
ShellSession session = SESSIONS.get(player.getUUID());
if (session != null && session.isAlive()) session.resize(rows, cols);
}
/** Kills the shell a player was attached to, if they had one. */
public static void close(ServerPlayer player) {
ShellSession session = SESSIONS.remove(player.getUUID());
if (session != null) session.close();
}
/** Called by a session's output thread once the process is done with. */
static void sessionEnded(ShellSession session) {
SESSIONS.values().removeIf(alive -> alive == session);
}
private static void closeAll(MinecraftServer server) {
for (ShellSession session : SESSIONS.values()) session.close();
SESSIONS.clear();
}
private static void send(ServerPlayer player, CustomPacketPayload payload) {
try {
ServerPlayNetworking.send(player, payload);
} catch (RuntimeException e) {
// The player is leaving; nobody is there to read this.
}
}
}