No chat to show

This project's files are all here to explore.

Files
src
build.gradle.kts
README.md
settings.gradle.kts
Code
15 2,166
src/main/java/dev/worldlink/WorldLinkPlugin.java
package dev.worldlink;

import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.command.PluginCommand;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.*;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

public final class WorldLinkPlugin extends JavaPlugin {
    static final String NPC_TAG = "worldlink_npc";
    static final int PROTOCOL = 1;

    record NpcRef(Link link, UUID remoteId) { }

    final Map<String, Link> links = new ConcurrentHashMap<>();
    final Map<UUID, NpcRef> npcEntities = new ConcurrentHashMap<>();
    private ServerSocket listener;

    @Override
    public void onEnable() {
        saveDefaultConfig();
        getDataFolder().mkdirs();
        loadLinks();
        getServer().getPluginManager().registerEvents(new LinkListener(this), this);
        PluginCommand cmd = getCommand("link");
        if (cmd != null) {
            LinkCommand lc = new LinkCommand(this);
            cmd.setExecutor(lc);
            cmd.setTabCompleter(lc);
        }
        getServer().getScheduler().runTaskTimer(this, () -> links.values().forEach(Link::tick), 1L, 1L);
        getServer().getScheduler().runTaskTimerAsynchronously(this, this::saveHashes, 6000L, 6000L);
    }

    @Override
    public void onDisable() {
        for (Link l : links.values()) l.stop();
        saveHashes();
        saveLinks();
        synchronized (this) {
            if (listener != null) try { listener.close(); } catch (IOException ignored) { }
        }
    }

    // ------------------------------------------------------------------ link management
    Link linkForWorld(String name) {
        for (Link l : links.values()) if (l.worldName.equalsIgnoreCase(name)) return l;
        return null;
    }

    Link sourceLinkFor(World w) {
        Link l = linkForWorld(w.getName());
        return l != null && l.role == Link.Role.SOURCE ? l : null;
    }

    private static String randomToken() {
        byte[] b = new byte[16];
        new SecureRandom().nextBytes(b);
        StringBuilder sb = new StringBuilder();
        for (byte x : b) sb.append(String.format("%02x", x));
        return sb.toString();
    }

    Link createHostLink(String world, Link.Role role) {
        String token = randomToken();
        Link l = new Link(this, token.substring(0, 6), true, token, world, role);
        l.remotePort = getConfig().getInt("listen-port", 25599);
        links.put(l.id, l);
        l.start();
        saveLinks();
        return l;
    }

    Link createJoinLink(String code, String world) {
        String raw = code.trim();
        if (raw.startsWith("WL-")) raw = raw.substring(3);
        String[] parts = new String(Base64.getUrlDecoder().decode(raw), StandardCharsets.UTF_8).split("\\|", 3);
        if (parts.length != 3) throw new IllegalArgumentException("Invalid code");
        String token = parts[2];
        Link l = new Link(this, token.substring(0, 6), false, token, world, Link.Role.TARGET);
        l.remoteHost = parts[0];
        l.remotePort = Integer.parseInt(parts[1]);
        links.put(l.id, l);
        l.start();
        saveLinks();
        return l;
    }

    void removeLink(Link l) {
        l.stop();
        links.remove(l.id);
        //noinspection ResultOfMethodCallIgnored
        l.knownFile().delete();
        saveLinks();
    }

    String publicHost() {
        String h = getConfig().getString("public-host", "");
        if (h != null && !h.isBlank()) return h.trim();
        h = Bukkit.getIp();
        if (h != null && !h.isBlank()) return h;
        try { return InetAddress.getLocalHost().getHostAddress(); } catch (Exception e) { return "127.0.0.1"; }
    }

    String encodeCode(Link l) {
        String raw = publicHost() + "|" + getConfig().getInt("listen-port", 25599) + "|" + l.token;
        return "WL-" + Base64.getUrlEncoder().withoutPadding().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
    }

    // ------------------------------------------------------------------ persistence
    private File linksFile() { return new File(getDataFolder(), "links.yml"); }

    void saveLinks() {
        YamlConfiguration y = new YamlConfiguration();
        for (Link l : links.values()) {
            ConfigurationSection s = y.createSection("links." + l.id);
            s.set("host", l.host);
            s.set("token", l.token);
            s.set("world", l.worldName);
            s.set("role", l.role.name());
            s.set("remote-host", l.remoteHost);
            s.set("remote-port", l.remotePort);
            s.set("remote-world", l.remoteWorld);
        }
        try { y.save(linksFile()); } catch (IOException e) { getLogger().warning("Could not save links.yml: " + e.getMessage()); }
    }

    private void loadLinks() {
        if (!linksFile().isFile()) return;
        YamlConfiguration y = YamlConfiguration.loadConfiguration(linksFile());
        ConfigurationSection root = y.getConfigurationSection("links");
        if (root == null) return;
        for (String id : root.getKeys(false)) {
            ConfigurationSection s = root.getConfigurationSection(id);
            if (s == null) continue;
            Link l = new Link(this, id, s.getBoolean("host"), s.getString("token", ""), s.getString("world", "world"),
                    Link.Role.valueOf(s.getString("role", "TARGET")));
            l.remoteHost = s.getString("remote-host", "");
            l.remotePort = s.getInt("remote-port");
            l.remoteWorld = s.getString("remote-world", "?");
            links.put(id, l);
            l.start();
        }
    }

    private void saveHashes() {
        for (Link l : links.values()) if (l.role == Link.Role.SOURCE) l.source.save(l.knownFile());
    }

    // ------------------------------------------------------------------ listener for incoming links
    synchronized void ensureListener() {
        if (listener != null && !listener.isClosed()) return;
        try {
            ServerSocket ss = new ServerSocket();
            ss.setReuseAddress(true);
            ss.bind(new InetSocketAddress(getConfig().getString("bind-address", "0.0.0.0"), getConfig().getInt("listen-port", 25599)));
            listener = ss;
            Thread t = new Thread(() -> {
                while (!ss.isClosed()) {
                    try {
                        Socket s = ss.accept();
                        Thread h = new Thread(() -> handshake(s), "WorldLink-handshake");
                        h.setDaemon(true);
                        h.start();
                    } catch (IOException e) {
                        if (ss.isClosed()) return;
                    }
                }
            }, "WorldLink-accept");
            t.setDaemon(true);
            t.start();
            getLogger().info("Listening for links on port " + ss.getLocalPort());
        } catch (IOException e) {
            getLogger().severe("Could not open listen port: " + e.getMessage());
        }
    }

    private void handshake(Socket s) {
        try {
            s.setSoTimeout(10_000);
            DataInputStream in = new DataInputStream(s.getInputStream());
            DataOutputStream out = new DataOutputStream(s.getOutputStream());
            if (in.readInt() != Connection.MAGIC) throw new IOException("bad magic");
            int proto = in.readInt();
            String token = in.readUTF();
            String world = in.readUTF();