Volver al índice

src/main/java/ar/com/companeros/clientupdate/UpdateInstaller.java

package ar.com.companeros.clientupdate;

import java.io.IOException;
import java.nio.file.*;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.HexFormat;
import java.util.zip.ZipFile;

/** Instalador mínimo del cliente: sólo Java estándar y sólo después de cerrar Minecraft. */
public final class UpdateInstaller {
    private UpdateInstaller() { }

    // PROCESO: el PID también debe conservar su fecha de creación para evitar su reutilización.
    public static void main(String[] args) {
        Path state = null;
        try {
            if (args.length != 7) throw new IOException("Argumentos de instalación inválidos");
            long pid = Long.parseLong(args[0]), started = Long.parseLong(args[1]);
            Path target = Path.of(args[2]).toAbsolutePath().normalize();
            Path staged = Path.of(args[3]).toAbsolutePath().normalize();
            state = target.getParent().getParent().resolve("config/raps/client-updates");
            if (!target.getFileName().toString().equals("Raps.jar") || !target.getParent().getFileName().toString().equals("mods")
                    || !staged.getParent().equals(state) || !staged.getFileName().toString().endsWith(".pending"))
                throw new IOException("Destino de instalación no autorizado");
            long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.HOURS.toNanos(24);
            while (sameProcess(pid, started)) {
                if (System.nanoTime() >= deadline) return;
                Thread.sleep(1000);
            }
            // Windows puede demorar en liberar el archivo después de finalizar el proceso.
            for (int attempt = 0; attempt < 30; attempt++) {
                try { install(staged, target, args[4], args[5], Long.parseLong(args[6])); return; }
                catch (AccessDeniedException locked) { Thread.sleep(2000); }
            }
            throw new IOException("Minecraft aún mantiene bloqueado el JAR");
        } catch (Exception failure) {
            if (state != null && Files.isDirectory(state)) try {
                Files.writeString(state.resolve("installer-error.log"), Instant.now() + " " + failure.getClass().getSimpleName());
            } catch (IOException ignored) { }
        }
    }
    private static boolean sameProcess(long pid, long started) {
        return ProcessHandle.of(pid).filter(ProcessHandle::isAlive)
            .filter(process -> process.info().startInstant().map(time -> Math.abs(time.toEpochMilli() - started) < 2000).orElse(true)).isPresent();
    }

    // ARCHIVOS: hash comprobado otra vez, identidad del mod, respaldo y sustitución atómica.
    public static void install(Path staged, Path target, String previousHash, String nextHash, long sequence) throws Exception {
        assertPlainPath(staged); assertPlainPath(target);
        if (!hash(staged).equals(nextHash) || !hash(target).equals(previousHash))
            throw new IOException("La descarga o la instalación cambiaron durante la espera");
        assertRapsJar(staged); assertRapsJar(target);
        Path game = target.getParent().getParent();
        Path backups = game.resolve("config/raps/client-backups");
        assertPlainPath(backups); Files.createDirectories(backups);
        Path backup = backups.resolve("Raps-" + sequence + "-" + System.currentTimeMillis() + ".jar");
        Files.copy(target, backup);
        Files.move(staged, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
        if (!hash(target).equals(nextHash)) {
            Files.move(backup, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
            throw new IOException("Verificación posterior fallida; se restauró el respaldo");
        }
        Path state = game.resolve("config/raps/client-updates");
        assertPlainPath(state); Files.createDirectories(state);
        Path temporary = Files.createTempFile(state, "installed-", ".tmp");
        Files.writeString(temporary, Long.toString(sequence));
        Files.move(temporary, state.resolve("installed-sequence.txt"), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
    }
    public static void assertPlainPath(Path path) throws IOException {
        for (Path current = path.toAbsolutePath().normalize(); current != null; current = current.getParent())
            if (Files.isSymbolicLink(current) || Files.exists(current, LinkOption.NOFOLLOW_LINKS)
                    && Files.readAttributes(current, java.nio.file.attribute.BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS).isOther())
                throw new IOException("Ruta redirigida no admitida");
    }
    public static String hash(Path file) throws Exception {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        try (var input = Files.newInputStream(file)) {
            byte[] buffer = new byte[65536]; int count;
            while ((count = input.read(buffer)) >= 0) digest.update(buffer, 0, count);
        }
        return HexFormat.of().formatHex(digest.digest());
    }
    public static void assertRapsJar(Path path) throws IOException {
        try (ZipFile zip = new ZipFile(path.toFile())) {
            var entry = zip.getEntry("META-INF/mods.toml");
            if (entry == null || entry.getSize() > 65536) throw new IOException("JAR sin identidad válida");
            try (var input = zip.getInputStream(entry)) {
                byte[] bytes = input.readNBytes(65537);
                if (bytes.length > 65536 || !new String(bytes, java.nio.charset.StandardCharsets.UTF_8)
                        .matches("(?s).*modId\\s*=\\s*\"companeros\".*")) throw new IOException("El archivo no pertenece a Raps");
            }
        }
    }
}