package online.astradev.packs; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; import java.io.IOException; import java.net.InetSocketAddress; import java.net.URI; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** Serves only published archives, with expiring links and bounded downloads. */ public final class PackHost implements AutoCloseable { private record Grant(String hash, long expires) {} private final PackConfig.Hosting config; private final Map published = new ConcurrentHashMap<>(); private final Map grants = new ConcurrentHashMap<>(); private final Map downloadsByIp = new HashMap<>(); private final ExecutorService workers = Executors.newVirtualThreadPerTaskExecutor(); private HttpServer server; private int activeDownloads; public PackHost(PackConfig.Hosting config) { this.config = config; } public void start() throws IOException { server = HttpServer.create(new InetSocketAddress(config.bindAddress, config.port), 0); server.createContext("/", this::handle); server.setExecutor(workers); server.start(); } public void publish(PackBuilder.Pack pack) { published.put(pack.sha1(), pack.path()); published.entrySet().removeIf(entry -> !Files.isRegularFile(entry.getValue())); grants.entrySet().removeIf(entry -> !published.containsKey(entry.getValue().hash())); } public String issuePath(PackBuilder.Pack pack) { String path = "/astrapacks/" + pack.sha1() + ".zip"; if (!config.blockNonGameRequests) { return path; } long now = System.currentTimeMillis(); grants.entrySet().removeIf(entry -> entry.getValue().expires() < now); if (grants.size() >= 10000) { throw new IllegalStateException("Too many resource-pack download grants"); } String token = UUID.randomUUID().toString(); grants.put(token, new Grant(pack.sha1(), now + config.tokenLifetimeSeconds * 1000L)); return path + "?token=" + token; } private void handle(HttpExchange exchange) throws IOException { try (exchange) { exchange.getResponseHeaders().set("Connection", "close"); String method = exchange.getRequestMethod(); if (!method.equals("GET") && !method.equals("HEAD")) { exchange.sendResponseHeaders(405, -1); return; } String path = exchange.getRequestURI().getPath(); if (!path.matches("/astrapacks/[a-f0-9]{40}\\.zip")) { exchange.sendResponseHeaders(404, -1); return; } String hash = path.substring("/astrapacks/".length(), path.length() - ".zip".length()); Path file = published.get(hash); if (file == null || !Files.isRegularFile(file)) { exchange.sendResponseHeaders(404, -1); return; } if (!authorized(exchange.getRequestURI(), hash)) { exchange.sendResponseHeaders(403, -1); return; } String ip = exchange.getRemoteAddress().getAddress().getHostAddress(); if (!acquireDownload(ip)) { exchange.sendResponseHeaders(429, -1); return; } try { sendFile(exchange, file, hash); } finally { releaseDownload(ip); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } private boolean authorized(URI uri, String hash) { if (!config.blockNonGameRequests) { return true; } String query = uri.getRawQuery(); if (query == null) { return false; } for (String parameter : query.split("&")) { if (parameter.startsWith("token=")) { try { String token = URLDecoder.decode(parameter.substring(6), StandardCharsets.UTF_8); Grant grant = grants.get(token); return grant != null && grant.hash().equals(hash) && grant.expires() >= System.currentTimeMillis(); } catch (IllegalArgumentException e) { return false; } } } return false; } private void sendFile(HttpExchange exchange, Path file, String hash) throws IOException, InterruptedException { var headers = exchange.getResponseHeaders(); headers.set("Content-Type", "application/zip"); headers.set("ETag", '"' + hash + '"'); headers.set("Cache-Control", "private, max-age=31536000, immutable"); long size = Files.size(file); if (exchange.getRequestMethod().equals("HEAD")) { headers.set("Content-Length", Long.toString(size)); exchange.sendResponseHeaders(200, -1); return; } try (var input = Files.newInputStream(file)) { exchange.sendResponseHeaders(200, size); var output = exchange.getResponseBody(); byte[] buffer = new byte[65536]; long transferred = 0; long started = System.nanoTime(); long bytesPerSecond = config.maxSpeedMiBPerSecond * 1024L * 1024L; int read; while ((read = input.read(buffer)) != -1) { transferred += read; long delay = transferred * 1_000_000_000L / bytesPerSecond - (System.nanoTime() - started); if (delay > 0) { TimeUnit.NANOSECONDS.sleep(delay); } output.write(buffer, 0, read); } } } private synchronized boolean acquireDownload(String ip) { int count = downloadsByIp.getOrDefault(ip, 0); if (count >= config.maxDownloadsPerIp || activeDownloads >= config.maxConcurrentDownloads) { return false; } downloadsByIp.put(ip, count + 1); activeDownloads++; return true; } private synchronized void releaseDownload(String ip) { int remaining = downloadsByIp.get(ip) - 1; if (remaining == 0) { downloadsByIp.remove(ip); } else { downloadsByIp.put(ip, remaining); } activeDownloads--; } @Override public void close() { if (server != null) { server.stop(0); } workers.shutdownNow(); grants.clear(); } }