Files
src
build.gradle
settings.gradle
Code
5 267
src/main/java/com/kodari/publictunnel/PublicServerTunnel.java
package com.kodari.publictunnel;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public final class PublicServerTunnel extends JavaPlugin {
private static final Pattern PUBLIC_ADDRESS = Pattern.compile("\"public_url\"\\s*:\\s*\"tcp://([^\"\\\\]+)\"");
private final Object processLock = new Object();
private volatile boolean running;
private Process process;
private ExecutorService worker;
private int minecraftPort;
@Override
public void onEnable() {
saveDefaultConfig();
minecraftPort = getServer().getPort();
running = true;
worker = Executors.newSingleThreadExecutor(task -> {
Thread thread = new Thread(task, "public-server-tunnel");
thread.setDaemon(true);
return thread;
});
worker.execute(this::runTunnel);
}
@Override
public void onDisable() {
running = false;
stopAgent();
if (worker != null) {
worker.shutdownNow();
}
}
private void runTunnel() {
while (running && !Thread.currentThread().isInterrupted()) {
YamlConfiguration config = YamlConfiguration.loadConfiguration(getDataFolder().toPath().resolve("config.yml").toFile());
int retrySeconds = Math.max(5, config.getInt("retry-seconds", 30));
try {
String token = config.getString("authtoken", "").trim();
if (token.isEmpty()) {
throw new IOException("Set your ngrok authtoken in plugins/PublicServerTunnel/config.yml");
}
String host = config.getString("local-host", "127.0.0.1").trim();
if (host.isEmpty() || host.contains(":") || host.contains("/")) {
throw new IOException("local-host must be an IPv4 address or hostname");
}
Path agent = ensureAgent();
int apiPort = availablePort();
ProcessBuilder builder = new ProcessBuilder(agent.toAbsolutePath().toString(), "tcp",
host + ":" + minecraftPort, "--web-addr", "127.0.0.1:" + apiPort,
"--log", "stdout");
builder.environment().put("NGROK_AUTHTOKEN", token);
builder.redirectErrorStream(true);
builder.redirectOutput(ProcessBuilder.Redirect.DISCARD);
Process started;
synchronized (processLock) {
if (!running) {
return;
}
started = builder.start();
process = started;
}
String address = null;
for (int i = 0; running && i < 30 && started.isAlive(); i++) {
address = readAddress(apiPort);
if (address != null) {
break;
}
Thread.sleep(1000);
}
if (!running) {
return;
}
if (address == null) {
throw new IOException("ngrok could not establish a TCP tunnel; check your authtoken, ngrok account TCP eligibility, and outbound network access");
}
getLogger().info("Public server address: " + address);
while (running && started.isAlive()) {
Thread.sleep(10000);
if (!address.equals(readAddress(apiPort))) {
throw new IOException("The public tunnel is no longer available");
}
}
if (running) {
throw new IOException("The ngrok agent stopped unexpectedly");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
} catch (Exception e) {
if (running) {
getLogger().severe("Public tunnel failed: " + e.getMessage() + ". Retrying in " + retrySeconds + " seconds.");
}
} finally {
stopAgent();
}
try {
if (running) {
Thread.sleep(retrySeconds * 1000L);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
}
private void stopAgent() {
synchronized (processLock) {
if (process != null) {
process.destroyForcibly();
process = null;
}
}
}
private int availablePort() throws IOException {
try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) {
return socket.getLocalPort();
}
}
private String readAddress(int port) {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) URI.create("http://127.0.0.1:" + port + "/api/tunnels").toURL().openConnection();
connection.setConnectTimeout(2000);
connection.setReadTimeout(2000);
if (connection.getResponseCode() != 200) {
return null;
}
try (InputStream input = connection.getInputStream()) {
String response = new String(input.readNBytes(65536), StandardCharsets.UTF_8);
Matcher matcher = PUBLIC_ADDRESS.matcher(response);
return matcher.find() ? matcher.group(1) : null;
}
} catch (IOException e) {
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
private Path ensureAgent() throws IOException {
String osName = System.getProperty("os.name").toLowerCase(Locale.ROOT);
String archName = System.getProperty("os.arch").toLowerCase(Locale.ROOT);
String os;
if (osName.contains("win")) {
os = "windows";
} else if (osName.contains("mac") || osName.contains("darwin")) {
os = "darwin";
} else if (osName.contains("linux")) {
os = "linux";
} else {
throw new IOException("Unsupported operating system: " + osName);
}
String arch;
if (archName.equals("amd64") || archName.equals("x86_64")) {
arch = "amd64";
} else if (archName.equals("aarch64") || archName.equals("arm64")) {
arch = "arm64";
} else {
throw new IOException("Unsupported CPU architecture: " + archName);
}
String executable = os.equals("windows") ? "ngrok.exe" : "ngrok";
Path directory = getDataFolder().toPath();
Files.createDirectories(directory);
Path target = directory.resolve(executable);
if (Files.isRegularFile(target)) {
return target;
}
String url = "https://bin.equinox.io/c/bNyj1mQVY4c/ngrok-v3-stable-" + os + "-" + arch + ".zip";
getLogger().info("Downloading the official ngrok agent for " + os + "/" + arch + ".");
HttpURLConnection connection = (HttpURLConnection) URI.create(url).toURL().openConnection();
connection.setConnectTimeout(15000);
connection.setReadTimeout(30000);
Path temporary = directory.resolve(executable + ".download");
try {