Shell and folders
Some checks failed
build / build (push) Failing after 1m37s

This commit is contained in:
2026-10-07 19:13:25 +02:00
parent 7a115445ab
commit 5897870725
53 changed files with 6626 additions and 450 deletions

View File

@@ -0,0 +1,115 @@
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.
*
* <p><b>This hands out a real shell on the machine the server runs on, to
* anyone who can open the editor.</b> 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.</p>
*
* <p>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.</p>
*/
public final class ShellManager {
private static final Map<UUID, ShellSession> 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.
}
}
}

View File

@@ -0,0 +1,535 @@
package com.aranroig.shell;
import com.aranroig.Codecraft;
import com.aranroig.payloads.ClientboundShellClosedPayload;
import com.aranroig.payloads.ClientboundShellOutputPayload;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.server.level.ServerPlayer;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.lang.ProcessBuilder.Redirect;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* One interactive bash session on the server, wired to one player's terminal
* pane: what it prints is forwarded to the pane as
* {@link ClientboundShellOutputPayload}s, and every byte the player types is
* written to its input.
*
* <h2>A real terminal, not a pipe</h2>
*
* <p>Bash is fully interactive ({@code -i}, readline and all) and runs on a
* pseudo-terminal allocated through {@code script} (util-linux), so everything
* a real terminal does happens here: the tty echoes what arrives, readline
* redraws the line while it is edited, programs see a tty — {@code tty} says
* {@code /dev/pts/…}, {@code ls --color=auto} colours, {@code sudo} prompts,
* {@code vim} takes over the screen — and {@code TERM} is
* {@code xterm-256color} to match. Drawing all of that, cursor and all, is the
* pane's job: it is the emulator, this is only the machine behind it. Where
* {@code script} is not available, it falls back to plain non-interactive
* bash over pipes, which still runs commands and keeps state, but without any
* of the tty behaviours.</p>
*
* <p>The pane tells the shell how big the "window" is the way a real terminal
* emulator sizes one: the pty's window is moved from out here — {@code stty}
* run against the session's {@code /dev/pts} device, which makes the kernel
* resize the terminal and signal the programs in the foreground that it did,
* so a full-screen program reflows mid-resize — and nothing is ever typed
* into the shell to say so.</p>
*
* <h2>Threading</h2>
*
* <p>The process' output is read on its own thread — a command that prints
* for a minute must not stop the server from ticking — and handed straight to
* the player's connection, which netty accepts from any thread. Input goes
* the other way from the server thread, written through as it arrives.</p>
*/
public final class ShellSession {
/**
* The shell the pseudo-terminal runs: the server user's plain interactive
* bash, so — exactly like a terminal opened on the machine itself — it
* sources their startup files, {@code /etc/bash.bashrc} and
* {@code ~/.bashrc}, before the first prompt.
*/
private static final String SHELL_COMMAND = "bash -i";
/** Allocates the pty that lets bash be interactive. Tried in order. */
private static final String[] PTY_LAUNCHERS = { "/usr/bin/script", "/bin/script", "script" };
/** Tried in order when no pty launcher could be started; first one that starts wins. */
private static final String[] PLAIN_SHELLS = { "/bin/bash", "/usr/bin/bash", "bash" };
/**
* Sizes the pty's window through its {@code /dev/pts} device; tried in
* order like everything else. {@code stty} does nothing but the one ioctl
* on its standard input, which the kernel turns into a new window size
* and — when it changed — a SIGWINCH for the terminal's foreground group.
*/
private static final String[] STTY_COMMANDS = { "/bin/stty", "/usr/bin/stty", "stty" };
/** How long the shell may take to appear under {@code script} before the pty device search gives up. */
private static final long PTS_SEARCH_BUDGET_MS = 5_000;
private static final long PTS_SEARCH_RETRY_MS = 200;
/** How long one {@code stty} may take to size a window before it is not believed. */
private static final long STTY_TIMEOUT_MS = 2_000;
/** How much of the shell's output is read — and sent — at once. */
private static final int CHUNK_SIZE = 4096;
private final ServerPlayer player;
private Process process;
private OutputStream stdin;
private volatile boolean alive;
/** Whether the shell sits on a real pty (programs see a terminal) or on pipes. */
private boolean interactive;
/** Set when we killed it ourselves, so its exit is not announced as news. */
private volatile boolean closing;
/**
* Guards the wanted and applied window sizes, and the wait between the
* pane wanting one and the resize worker getting it: the pane's sizes
* arrive on the server thread with its payloads, and the {@code stty}
* runs that turn them into kernel calls must not keep the server ticking.
*/
private final Object resizeLock = new Object();
/** The size the pane last wanted, and the last one actually applied; guarded by {@link #resizeLock}. */
private int wantRows, wantCols, appliedRows, appliedCols;
/** Whether the worker that applies sizes has been started; guarded by {@link #resizeLock}. */
private boolean resizeLoopStarted;
/**
* This session's {@code /dev/pts} device, found once by following the
* process tree down from {@code script}: whoever runs under it has the
* pty on its standard input, and the link there is the device. Written
* only by the resize worker.
*/
private String ptsDevice;
/** Whether the device above was given up on; guarded by {@link #resizeLock}, read by the worker. */
private boolean ptsSearchFailed;
ShellSession(ServerPlayer player) {
this.player = player;
}
/**
* Spawns the shell and starts forwarding its output to the player. A
* pseudo-terminal through {@code script} if one can be had, plain bash
* over pipes otherwise. {@code rows}/{@code cols} (when positive) are the
* size of the pane that asked: on the pty the window is set to them as
* soon as its device can be found (see {@link #resize}), the same call a
* real window resize makes; only the pipe fallback, which has no terminal
* at all to size, is given them as {@code LINES}/{@code COLUMNS} instead.
*
* @throws IOException no shell could be started on this machine
*/
public void start(int rows, int cols) throws IOException {
IOException lastFailure = null;
for (String launcher : PTY_LAUNCHERS) {
try {
process = ptyBuilderFor(launcher).start();
// `script` starting is not running it: an older one that does
// not know these options exits at once, and that is found out
// by giving it the moment it needs, no more.
if (startedAndStayedUp()) {
interactive = true;
break;
}
process = null;
} catch (IOException e) {
lastFailure = e;
process = null;
}
}
if (process == null) {
for (String shell : PLAIN_SHELLS) {
try {
process = plainBuilderFor(shell, rows, cols).start();
break;
} catch (IOException e) {
lastFailure = e;
}
}
}
if (process == null) {
throw lastFailure != null ? lastFailure
: new IOException("no bash found on this server");
}
stdin = process.getOutputStream();
alive = true;
Codecraft.LOGGER.info("Spawned a {} shell for {} in {}",
interactive ? "pty-backed" : "plain",
player.getName().getString(), System.getProperty("user.dir"));
// A terminal opens at the size of the window that asked: `script`
// cannot be told, so its pty starts at the kernel's default and the
// worker corrects it to the pane's grid a moment later, as soon as
// the device behind it is findable — well before bash prints much.
synchronized (resizeLock) {
wantRows = rows;
wantCols = cols;
if (interactive) startResizeLoop();
}
Thread.ofVirtual()
.name("codecraft-shell-" + player.getName().getString())
.start(this::pumpOutput);
}
/**
* Whether the process made it past the moment an unusable launcher takes
* to argue with its own command line and give up.
*/
private boolean startedAndStayedUp() {
try {
return !process.waitFor(250, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return true;
}
}
private static ProcessBuilder ptyBuilderFor(String script) {
ProcessBuilder builder = new ProcessBuilder(
// -q quiet, -f flush every write (output must not wait for the
// shell to exit), -e exit with the child's code. The tty's
// echo stays on: the pane shows what was typed exactly the
// way it arrives back, as any terminal does, so readline can
// redraw the line and nothing is ever shown twice.
script, "-q", "-f", "-e",
"-c", SHELL_COMMAND,
// No typescript file: the scrollback in the pane is the record.
"/dev/null");
// A real terminal on a real tty, not the dumb one a pipe implies. The
// prompt stays bash's own — it is part of what the pane draws. And no
// LINES/COLUMNS in the environment: those make programs trust the
// numbers over the terminal they are on, and the numbers here must be
// the pty's own window, kept true by the resize machinery below.
builder.environment().put("TERM", "xterm-256color");
return builder;
}
private static ProcessBuilder plainBuilderFor(String shell, int rows, int cols) {
ProcessBuilder builder = new ProcessBuilder(shell, "--noediting");
// A non-interactive bash reads no rc files at all, so BASH_ENV is the
// way to have this path source the same ~/.bashrc (expanded by bash
// itself, against the server process' HOME) that the pty path gets.
builder.environment().put("BASH_ENV", "~/.bashrc");
// Without the pty, stdout and stderr are merged here instead.
builder.redirectErrorStream(true);
return configurePipeEnv(builder, rows, cols);
}
/** The environment of the pipe fallback: a terminal it does not really have, sized only by env. */
private static ProcessBuilder configurePipeEnv(ProcessBuilder builder, int rows, int cols) {
Map<String, String> env = builder.environment();
env.put("TERM", "xterm-256color");
// There is no terminal to size on this path, so LINES/COLUMNS are the
// only way a program here can be told anything at all.
if (rows > 0 && cols > 0) {
env.put("LINES", String.valueOf(rows));
env.put("COLUMNS", String.valueOf(cols));
}
return builder;
}
/**
* Writes what the pane typed straight to the pseudo-terminal: keystrokes,
* tabs, Ctrl-C's {@code \u0003}, an arrow key's escape sequence, an
* emulator's answer to a status query. Nothing is interpreted on the way —
* on the pty those bytes are edits and signals, not text, and the shell
* and its programs read them exactly as they would from a real terminal.
*/
public void submitInput(String bytes) {
if (!alive || stdin == null) return;
try {
stdin.write(bytes.getBytes(StandardCharsets.UTF_8));
stdin.flush();
} catch (IOException e) {
Codecraft.LOGGER.warn("Could not write to the shell of {}", player.getName().getString(), e);
}
}
/**
* Resizes the pty's window to a new size of the pane, from the outside:
* nothing is written to the shell's input, so a full-screen program in
* the foreground is signalled mid-run — SIGWINCH, and it redraws —
* instead of waiting for a typed {@code stty} it would only read as
* keystrokes. The newest size wins while an older one is still being
* applied, so dragging a sash across the screen converges on where it
* was let go rather than queueing a resize per frame.
*/
public void resize(int rows, int cols) {
if (rows <= 0 || cols <= 0) return;
synchronized (resizeLock) {
if (!alive) return;
wantRows = rows;
wantCols = cols;
resizeLock.notifyAll();
if (interactive) startResizeLoop();
}
}
/** Hands the pending sizes to a worker; the caller holds {@link #resizeLock}. */
private void startResizeLoop() {
if (resizeLoopStarted) return;
resizeLoopStarted = true;
Thread.ofVirtual()
.name("codecraft-shell-resize-" + player.getName().getString())
.start(this::applySizes);
}
/**
* Waits for the pane to want a window of a different size and applies it,
* one wanted size at a time: whatever arrived meanwhile is simply the
* next thing asked for.
*/
private void applySizes() {
while (true) {
int rows, cols;
synchronized (resizeLock) {
while (alive && !sizeWantedLocked()) {
try {
resizeLock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
if (!alive) return;
rows = wantRows;
cols = wantCols;
}
applyWindowSize(rows, cols);
synchronized (resizeLock) {
appliedRows = rows;
appliedCols = cols;
}
}
}
/** Whether a real size is wanted and not applied yet; the caller holds {@link #resizeLock}. */
private boolean sizeWantedLocked() {
return wantRows > 0 && wantCols > 0 && (wantRows != appliedRows || wantCols != appliedCols);
}
/**
* Moves the pty's window to {@code rows} x {@code cols} by sizing its
* device — the same ioctl a real terminal emulator makes, and the kernel
* signals the terminal's foreground the way it signals any resize.
*/
private void applyWindowSize(int rows, int cols) {
String device = findPtsDevice();
if (device != null && runSttyAt(device, rows, cols)) return;
// No device to size from — no /proc to find it, no stty to size it,
// or it went away mid-session. Typed at the prompt is the only way
// left to tell a size at all: echoed, blind to whatever holds the
// screen, and the old behaviour, but better here than a window stuck
// at whatever it was.
Codecraft.LOGGER.warn("Could not size the pty of {}'s shell from its device; "
+ "resizing falls back to typing at the prompt", player.getName().getString());
ptsDevice = null;
submitInput("export LINES=" + rows + " COLUMNS=" + cols
+ "; stty rows " + rows + " cols " + cols + "\r");
}
/** Sizes the terminal at {@code device} by handing it, as standard input, to {@code stty}. */
private boolean runSttyAt(String device, int rows, int cols) {
for (String stty : STTY_COMMANDS) {
Process resized = null;
try {
resized = new ProcessBuilder(stty, "rows", String.valueOf(rows), "cols", String.valueOf(cols))
.redirectInput(new File(device))
.redirectOutput(Redirect.DISCARD)
.redirectError(Redirect.DISCARD)
.start();
if (resized.waitFor(STTY_TIMEOUT_MS, TimeUnit.MILLISECONDS) && resized.exitValue() == 0) return true;
} catch (IOException e) {
// This stty is not here; the next one may be.
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
} finally {
if (resized != null && resized.isAlive()) resized.destroyForcibly();
}
}
return false;
}
/**
* This session's pty device, searched for on first need and kept after.
* The shell appears under {@code script} a moment after the spawn, so the
* search retries quietly for a little while before giving up — from then
* on this session is known to have no findable device.
*/
private String findPtsDevice() {
synchronized (resizeLock) {
if (ptsDevice != null) return ptsDevice;
if (ptsSearchFailed) return null;
}
long deadline = System.currentTimeMillis() + PTS_SEARCH_BUDGET_MS;
do {
try {
String device = searchPtsDevice();
ptsDevice = device;
return device;
} catch (IOException e) {
try {
Thread.sleep(PTS_SEARCH_RETRY_MS);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
return null;
}
}
} while (alive && System.currentTimeMillis() < deadline);
synchronized (resizeLock) {
ptsSearchFailed = true;
}
Codecraft.LOGGER.warn("No /dev/pts under {}'s shell process tree; the pty window cannot be sized from here",
player.getName().getString());
return null;
}
/**
* Follows the process tree down from {@code script}: whoever runs under
* it has the pty on its standard input, and the {@code /proc} link there
* names the device. Throws when the tree holds nobody yet, which is how
* the search knows to look again in a moment.
*/
private String searchPtsDevice() throws IOException {
ArrayDeque<Long> queue = new ArrayDeque<>();
queue.add(process.pid());
for (int visited = 0; !queue.isEmpty() && visited < 64; visited++) {
for (long child : childrenOf(queue.poll())) {
String standardInput = fdTarget(child, 0);
if (standardInput != null && standardInput.startsWith("/dev/pts/")) return standardInput;
queue.add(child);
}
}
throw new IOException("no /dev/pts within pid " + process.pid() + "'s tree");
}
/** The pids {@code pid} spawned, as {@code /proc} reports them. */
private static List<Long> childrenOf(long pid) {
List<Long> children = new ArrayList<>();
try {
String line = Files.readString(
Path.of("/proc", Long.toString(pid), "task", Long.toString(pid), "children"));
for (String token : line.split(" ")) {
if (!token.isBlank()) children.add(Long.parseLong(token));
}
} catch (IOException | NumberFormatException e) {
// No /proc to ask, or the process is gone already: nobody is under there.
}
return children;
}
/** What fd {@code fd} of {@code pid} points at, or null when {@code /proc} will not say. */
private static String fdTarget(long pid, int fd) {
try {
return Files.readSymbolicLink(
Path.of("/proc", Long.toString(pid), "fd", Integer.toString(fd))).toString();
} catch (IOException | SecurityException e) {
return null;
}
}
public boolean isAlive() {
return alive;
}
/** Kills the shell; its output thread then ends by itself, quietly. */
public void close() {
closing = true;
alive = false;
synchronized (resizeLock) {
resizeLock.notifyAll();
}
if (process == null) return;
process.destroy();
try {
if (!process.waitFor(500, TimeUnit.MILLISECONDS)) process.destroyForcibly();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
process.destroyForcibly();
}
}
/**
* Reads the shell's merged output until it closes, forwarding every chunk.
*
* <p>Reading characters through a decoder rather than raw bytes is what
* keeps a multibyte character that arrives split over two reads intact.
* Nothing else is done to the stream: the pane interprets it character by
* character — escape sequences and chunk boundaries rarely agree with each
* other, and the emulator is built knowing that.</p>
*/
private void pumpOutput() {
char[] buffer = new char[CHUNK_SIZE];
try (Reader output = new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8)) {
int read;
while ((read = output.read(buffer)) > 0) {
send(new ClientboundShellOutputPayload(new String(buffer, 0, read)));
}
} catch (IOException e) {
if (!closing) {
Codecraft.LOGGER.warn("Shell output for {} broke: {}", player.getName().getString(), e.toString());
}
} finally {
alive = false;
synchronized (resizeLock) {
resizeLock.notifyAll();
}
ShellManager.sessionEnded(this);
if (!closing) {
int code = exitCode();
send(new ClientboundShellClosedPayload(
code >= 0 ? "shell exited (code " + code + ")" : "shell stopped"));
}
}
}
private int exitCode() {
try {
return process.exitValue();
} catch (IllegalStateException e) {
return -1;
}
}
/** Sends one message to the player, surviving the moment they are leaving. */
private void send(CustomPacketPayload payload) {
try {
ServerPlayNetworking.send(player, payload);
} catch (RuntimeException e) {
// The connection is gone; there is nobody left to print this to.
}
}
}