Expose bounded web contexts for embedded tools
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
package online.astradev.packs;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpContext;
|
||||
import com.sun.net.httpserver.HttpHandler;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -11,7 +13,9 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
@@ -20,11 +24,26 @@ import java.util.concurrent.TimeUnit;
|
||||
|
||||
/** Serves only published archives, with expiring links and bounded downloads. */
|
||||
public final class PackHost implements AutoCloseable {
|
||||
private static final String PACK_PREFIX = "/astrapacks";
|
||||
private static final int MAX_CUSTOM_CONTEXTS = 8;
|
||||
|
||||
private record Grant(String hash, long expires) {}
|
||||
|
||||
private static final class WebMount {
|
||||
private final String prefix;
|
||||
private final HttpHandler handler;
|
||||
private HttpContext context;
|
||||
|
||||
private WebMount(String prefix, HttpHandler handler) {
|
||||
this.prefix = prefix;
|
||||
this.handler = handler;
|
||||
}
|
||||
}
|
||||
|
||||
private final PackConfig.Hosting config;
|
||||
private final Map<String, Path> published = new ConcurrentHashMap<>();
|
||||
private final Map<String, Grant> grants = new ConcurrentHashMap<>();
|
||||
private final Map<String, WebMount> webMounts = new LinkedHashMap<>();
|
||||
private final Map<String, Integer> downloadsByIp = new HashMap<>();
|
||||
private final ExecutorService workers = Executors.newVirtualThreadPerTaskExecutor();
|
||||
private HttpServer server;
|
||||
@@ -35,10 +54,141 @@ public final class PackHost implements AutoCloseable {
|
||||
}
|
||||
|
||||
public void start() throws IOException {
|
||||
server = HttpServer.create(new InetSocketAddress(config.bindAddress, config.port), 0);
|
||||
server.createContext("/", this::handle);
|
||||
server.setExecutor(workers);
|
||||
server.start();
|
||||
synchronized (webMounts) {
|
||||
if (server != null) {
|
||||
throw new IllegalStateException("AstraPacks HTTP host is already started");
|
||||
}
|
||||
HttpServer next =
|
||||
HttpServer.create(new InetSocketAddress(config.bindAddress, config.port), 0);
|
||||
next.createContext("/", this::handle);
|
||||
for (WebMount mount : webMounts.values()) {
|
||||
mount.context = next.createContext(mount.prefix, mount.handler);
|
||||
}
|
||||
next.setExecutor(workers);
|
||||
next.start();
|
||||
server = next;
|
||||
}
|
||||
}
|
||||
|
||||
/** Mounts a custom HTTP context, either before or after this host is started. */
|
||||
public AutoCloseable mountWebContext(String prefix, HttpHandler handler) {
|
||||
String normalizedPrefix = normalizePrefix(prefix);
|
||||
Objects.requireNonNull(handler, "handler");
|
||||
WebMount mount = new WebMount(normalizedPrefix, handler);
|
||||
synchronized (webMounts) {
|
||||
ensureAvailablePrefix(normalizedPrefix);
|
||||
if (webMounts.size() >= MAX_CUSTOM_CONTEXTS) {
|
||||
throw new IllegalStateException("AstraPacks supports at most 8 custom HTTP contexts");
|
||||
}
|
||||
webMounts.put(normalizedPrefix, mount);
|
||||
if (server != null) {
|
||||
try {
|
||||
mount.context = server.createContext(normalizedPrefix, handler);
|
||||
} catch (RuntimeException error) {
|
||||
webMounts.remove(normalizedPrefix);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
return () -> unmount(mount);
|
||||
}
|
||||
|
||||
private void unmount(WebMount mount) {
|
||||
synchronized (webMounts) {
|
||||
if (!webMounts.remove(mount.prefix, mount)) return;
|
||||
removeContext(mount);
|
||||
}
|
||||
}
|
||||
|
||||
private void removeContext(WebMount mount) {
|
||||
if (mount.context == null || server == null) return;
|
||||
server.removeContext(mount.context);
|
||||
mount.context = null;
|
||||
}
|
||||
|
||||
public String publicUrl(String path) {
|
||||
return publicUrl(config.publicAddress, path);
|
||||
}
|
||||
|
||||
public String publicUrl(String publicAddress, String path) {
|
||||
String address = requirePublicAddress(publicAddress);
|
||||
return address + validateAbsolutePath(path);
|
||||
}
|
||||
|
||||
private void ensureAvailablePrefix(String prefix) {
|
||||
if (isPackPrefix(prefix)) {
|
||||
throw new IllegalArgumentException("The /astrapacks HTTP namespace is reserved");
|
||||
}
|
||||
for (String existing : webMounts.keySet()) {
|
||||
if (prefixesOverlap(existing, prefix)) {
|
||||
throw new IllegalArgumentException(
|
||||
"HTTP context overlaps an existing custom context: " + existing);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isPackPrefix(String prefix) {
|
||||
return prefix.equals(PACK_PREFIX) || prefix.startsWith(PACK_PREFIX + "/");
|
||||
}
|
||||
|
||||
private static boolean prefixesOverlap(String first, String second) {
|
||||
return first.startsWith(second) || second.startsWith(first);
|
||||
}
|
||||
|
||||
private static String normalizePrefix(String prefix) {
|
||||
Objects.requireNonNull(prefix, "prefix");
|
||||
validatePrefixShape(prefix);
|
||||
return withoutTrailingSlashes(prefix);
|
||||
}
|
||||
|
||||
private static void validatePrefixShape(String prefix) {
|
||||
if (prefix.length() > 128
|
||||
|| !prefix.startsWith("/")
|
||||
|| prefix.equals("/")
|
||||
|| hasForbiddenPathSyntax(prefix)
|
||||
|| prefix.indexOf("//") >= 0) {
|
||||
throw new IllegalArgumentException("Invalid HTTP context prefix: " + prefix);
|
||||
}
|
||||
}
|
||||
|
||||
private static String withoutTrailingSlashes(String prefix) {
|
||||
String normalized = prefix;
|
||||
while (normalized.length() > 1 && normalized.endsWith("/")) {
|
||||
normalized = normalized.substring(0, normalized.length() - 1);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private static String validateAbsolutePath(String path) {
|
||||
Objects.requireNonNull(path, "path");
|
||||
if (!path.startsWith("/")
|
||||
|| path.startsWith("//")
|
||||
|| hasForbiddenPathSyntax(path)
|
||||
|| containsControlCharacter(path)) {
|
||||
throw new IllegalArgumentException("Expected a safe absolute HTTP path: " + path);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
private static boolean hasForbiddenPathSyntax(String path) {
|
||||
return path.indexOf("..") >= 0
|
||||
|| path.indexOf('\\') >= 0
|
||||
|| path.indexOf('?') >= 0
|
||||
|| path.indexOf('#') >= 0;
|
||||
}
|
||||
|
||||
private static boolean containsControlCharacter(String value) {
|
||||
return value.chars().anyMatch(character -> character < 0x20 || character == 0x7f);
|
||||
}
|
||||
|
||||
private static String requirePublicAddress(String publicAddress) {
|
||||
if (publicAddress == null || publicAddress.isBlank()) {
|
||||
throw new IllegalStateException(
|
||||
"Set hosting.publicAddress before creating public AstraPacks URLs");
|
||||
}
|
||||
String address = publicAddress.replaceFirst("/+$", "");
|
||||
PackConfig.validateUrl(address);
|
||||
return address;
|
||||
}
|
||||
|
||||
public void publish(PackBuilder.Pack pack) {
|
||||
@@ -48,7 +198,7 @@ public final class PackHost implements AutoCloseable {
|
||||
}
|
||||
|
||||
public String issuePath(PackBuilder.Pack pack) {
|
||||
String path = "/astrapacks/" + pack.sha1() + ".zip";
|
||||
String path = PACK_PREFIX + "/" + pack.sha1() + ".zip";
|
||||
if (!config.blockNonGameRequests) {
|
||||
return path;
|
||||
}
|
||||
@@ -71,11 +221,11 @@ public final class PackHost implements AutoCloseable {
|
||||
return;
|
||||
}
|
||||
String path = exchange.getRequestURI().getPath();
|
||||
if (!path.matches("/astrapacks/[a-f0-9]{40}\\.zip")) {
|
||||
if (!path.matches(PACK_PREFIX + "/[a-f0-9]{40}\\.zip")) {
|
||||
exchange.sendResponseHeaders(404, -1);
|
||||
return;
|
||||
}
|
||||
String hash = path.substring("/astrapacks/".length(), path.length() - ".zip".length());
|
||||
String hash = path.substring(PACK_PREFIX.length() + 1, path.length() - ".zip".length());
|
||||
Path file = published.get(hash);
|
||||
if (file == null || !Files.isRegularFile(file)) {
|
||||
exchange.sendResponseHeaders(404, -1);
|
||||
@@ -181,8 +331,15 @@ public final class PackHost implements AutoCloseable {
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (server != null) {
|
||||
server.stop(0);
|
||||
synchronized (webMounts) {
|
||||
if (server != null) {
|
||||
for (WebMount mount : webMounts.values()) {
|
||||
removeContext(mount);
|
||||
}
|
||||
server.stop(0);
|
||||
server = null;
|
||||
}
|
||||
webMounts.clear();
|
||||
}
|
||||
workers.shutdownNow();
|
||||
grants.clear();
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package online.astradev.packs;
|
||||
|
||||
import com.sun.net.httpserver.HttpHandler;
|
||||
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.network.Connection;
|
||||
import net.minecraft.network.chat.Component;
|
||||
@@ -169,6 +171,18 @@ public final class PackRuntime implements AutoCloseable {
|
||||
return address.replaceAll("/+$", "") + host.issuePath(pack);
|
||||
}
|
||||
|
||||
/** Mounts an editor or other web endpoint on AstraPacks' HTTP origin. */
|
||||
public AutoCloseable mountWebContext(String prefix, HttpHandler handler) {
|
||||
if (closed) {
|
||||
throw new IllegalStateException("AstraPacks is closed");
|
||||
}
|
||||
return host.mountWebContext(prefix, handler);
|
||||
}
|
||||
|
||||
public String publicUrl(String path) {
|
||||
return host.publicUrl(config.hosting.publicAddress, path);
|
||||
}
|
||||
|
||||
public void build(CommandSourceStack source) {
|
||||
requestBuild(source, false);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user