Simplify pack hosting with JDK HTTP server and reduce resource handling state

This commit is contained in:
2026-09-06 19:32:43 +03:00
parent bc78299555
commit 222e04c683
7 changed files with 190 additions and 233 deletions
-2
View File
@@ -9,8 +9,6 @@ repositories {
} }
dependencies { dependencies {
testImplementation("com.google.code.gson:gson:2.14.0") testImplementation("com.google.code.gson:gson:2.14.0")
testImplementation("io.netty:netty-codec-http:4.2.15.Final")
testImplementation("io.netty:netty-handler:4.2.15.Final")
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
testRuntimeOnly("org.junit.platform:junit-platform-launcher:1.11.4") testRuntimeOnly("org.junit.platform:junit-platform-launcher:1.11.4")
} }
@@ -1,6 +1,7 @@
package online.astradev.packs; package online.astradev.packs;
import java.io.BufferedOutputStream; import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@@ -30,20 +31,25 @@ public final class PackBuilder {
public Pack build(Path root, String resourceVersion) throws IOException { public Pack build(Path root, String resourceVersion) throws IOException {
Path contents = config.contents(root); Path contents = config.contents(root);
if (!Files.isDirectory(contents) || Files.isSymbolicLink(contents)) { if (!Files.isDirectory(contents)) {
throw new IOException("Resource directory is missing or is a symbolic link: " + contents); throw new IOException("Resource directory is missing: " + contents);
}
for (Path parent = contents; parent != null; parent = parent.getParent()) {
if (Files.isSymbolicLink(parent)) {
throw new IOException("Symbolic links are not supported: " + parent);
}
} }
Path output = config.storage(root).resolve("output"); Path output = config.storage(root).resolve("output");
Files.createDirectories(output); Files.createDirectories(output);
Path temporary = Files.createTempFile(output, "build-", ".tmp"); Path temporary = Files.createTempFile(output, "build-", ".tmp");
try { try {
int files = writeArchive(contents, temporary, resourceVersion); int files = writeArchive(contents, temporary, resourceVersion);
String sha1 = hash(temporary, "SHA-1"); String sha1 = sha1(temporary);
Path destination = output.resolve(sha1 + ".zip"); Path destination = output.resolve(sha1 + ".zip");
boolean created = !Files.exists(destination); boolean created = !Files.exists(destination);
if (created) { if (created) {
Files.move(temporary, destination, StandardCopyOption.ATOMIC_MOVE); Files.move(temporary, destination, StandardCopyOption.ATOMIC_MOVE);
} else if (!hash(destination, "SHA-1").equals(sha1)) { } else if (!sha1(destination).equals(sha1)) {
throw new IOException("Published ZIP was modified: " + destination); throw new IOException("Published ZIP was modified: " + destination);
} }
Pack pack = new Pack(destination, sha1, files, Files.size(destination)); Pack pack = new Pack(destination, sha1, files, Files.size(destination));
@@ -68,7 +74,6 @@ public final class PackBuilder {
private int writeArchive(Path contents, Path target, String resourceVersion) throws IOException { private int writeArchive(Path contents, Path target, String resourceVersion) throws IOException {
int files = 0; int files = 0;
long totalBytes = 0; long totalBytes = 0;
byte[] buffer = new byte[8192];
try (var paths = Files.walk(contents); try (var paths = Files.walk(contents);
var zip = new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(target)))) { var zip = new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(target)))) {
for (Path file : paths.sorted().toList()) { for (Path file : paths.sorted().toList()) {
@@ -78,11 +83,13 @@ public final class PackBuilder {
if (!Files.isRegularFile(file)) { if (!Files.isRegularFile(file)) {
continue; continue;
} }
String name = contents.relativize(file).toString().replace('\\', '/'); String name = contents.relativize(file).toString().replace(File.separatorChar, '/');
if (!name.startsWith("assets/") && !name.equals("pack.png")) { if (!name.startsWith("assets/") && !name.equals("pack.png")) {
continue; continue;
} }
PackFiles.safe(contents, name); if (name.contains("\\") || name.contains(":")) {
throw new IOException("Invalid resource name: " + name);
}
if (++files > config.build.maxFiles) { if (++files > config.build.maxFiles) {
throw new IOException("Too many resources"); throw new IOException("Too many resources");
} }
@@ -90,21 +97,9 @@ public final class PackBuilder {
ZipEntry entry = new ZipEntry(name); ZipEntry entry = new ZipEntry(name);
entry.setTime(0); entry.setTime(0);
zip.putNextEntry(entry); zip.putNextEntry(entry);
long fileBytes = 0; long limit = Math.min(config.build.maxFileMiB * 1024L * 1024L,
try (var input = Files.newInputStream(file)) { config.build.maxTotalMiB * 1024L * 1024L - totalBytes);
int read; totalBytes += copyResource(file, zip, limit);
while ((read = input.read(buffer)) != -1) {
fileBytes += read;
totalBytes += read;
if (fileBytes > config.build.maxFileMiB * 1024L * 1024L) {
throw new IOException("Resource exceeds maxFileMiB: " + file);
}
if (totalBytes > config.build.maxTotalMiB * 1024L * 1024L) {
throw new IOException("Resources exceed maxTotalMiB");
}
zip.write(buffer, 0, read);
}
}
zip.closeEntry(); zip.closeEntry();
} }
ZipEntry metadata = new ZipEntry("pack.mcmeta"); ZipEntry metadata = new ZipEntry("pack.mcmeta");
@@ -116,6 +111,22 @@ public final class PackBuilder {
return files + 1; return files + 1;
} }
private static long copyResource(Path file, OutputStream output, long limit) throws IOException {
byte[] buffer = new byte[8192];
long size = 0;
try (var input = Files.newInputStream(file)) {
int read;
while ((read = input.read(buffer)) != -1) {
size += read;
if (size > limit) {
throw new IOException("Resource exceeds configured size limit: " + file);
}
output.write(buffer, 0, read);
}
}
return size;
}
private byte[] metadata(String resourceVersion) { private byte[] metadata(String resourceVersion) {
var version = JsonParser.parseString(resourceVersion); var version = JsonParser.parseString(resourceVersion);
JsonObject pack = new JsonObject(); JsonObject pack = new JsonObject();
@@ -164,7 +175,7 @@ public final class PackBuilder {
JsonObject info = readManifest(output.resolve("current.json")); JsonObject info = readManifest(output.resolve("current.json"));
String sha1 = info.get("sha1").getAsString(); String sha1 = info.get("sha1").getAsString();
Path path = output.resolve(sha1 + ".zip"); Path path = output.resolve(sha1 + ".zip");
if (!hash(path, "SHA-1").equals(sha1)) { if (!sha1(path).equals(sha1)) {
throw new IOException("Stored resource pack hash mismatch"); throw new IOException("Stored resource pack hash mismatch");
} }
return new Pack(path, sha1, info.get("files").getAsInt(), Files.size(path)); return new Pack(path, sha1, info.get("files").getAsInt(), Files.size(path));
@@ -184,9 +195,9 @@ public final class PackBuilder {
} }
} }
public static String hash(Path file, String algorithm) throws IOException { private static String sha1(Path file) throws IOException {
try { try {
MessageDigest digest = MessageDigest.getInstance(algorithm); MessageDigest digest = MessageDigest.getInstance("SHA-1");
try (var input = new DigestInputStream(Files.newInputStream(file), digest)) { try (var input = new DigestInputStream(Files.newInputStream(file), digest)) {
input.transferTo(OutputStream.nullOutputStream()); input.transferTo(OutputStream.nullOutputStream());
} }
@@ -6,34 +6,9 @@ import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.StandardCopyOption; import java.nio.file.StandardCopyOption;
final class PackFiles { final class PackFiles {
private PackFiles() {} private PackFiles() {}
static Path safe(Path root, String name) throws IOException {
if (name.isBlank() || name.contains("\\") || name.contains(":") || name.startsWith("/")) {
throw new IOException("Unsafe resource path: " + name);
}
for (String part : name.split("/", -1)) {
if (part.isEmpty() || part.equals(".") || part.equals("..")) {
throw new IOException("Unsafe resource path: " + name);
}
}
root = root.toAbsolutePath().normalize();
Path target = root.resolve(name).normalize();
if (!target.startsWith(root)) {
throw new IOException("Resource escapes content root: " + name);
}
for (Path part = target; part != null; part = part.getParent()) {
if (Files.isSymbolicLink(part)) {
throw new IOException("Symbolic links are not supported: " + part);
}
}
return target;
}
static void atomicWrite(Path target, byte[] bytes) throws IOException { static void atomicWrite(Path target, byte[] bytes) throws IOException {
Files.createDirectories(target.getParent()); Files.createDirectories(target.getParent());
Path temporary = Files.createTempFile(target.getParent(), ".astra-", ".tmp"); Path temporary = Files.createTempFile(target.getParent(), ".astra-", ".tmp");
+107 -172
View File
@@ -2,82 +2,43 @@ package online.astradev.packs;
import java.io.IOException; import java.io.IOException;
import java.net.InetSocketAddress; 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.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import io.netty.bootstrap.ServerBootstrap; import com.sun.net.httpserver.HttpExchange;
import io.netty.buffer.Unpooled; import com.sun.net.httpserver.HttpServer;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.MultiThreadIoEventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioIoHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpChunkedInput;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.stream.ChunkedNioFile;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.traffic.ChannelTrafficShapingHandler;
/** Serves published ZIPs only; request paths never map to arbitrary files on disk. */ /** Serves only published archives, with expiring links and bounded downloads. */
public final class PackHost implements AutoCloseable { public final class PackHost implements AutoCloseable {
private record Grant(String hash, long expires) {} private record Grant(String hash, long expires) {}
private final PackConfig.Hosting config; private final PackConfig.Hosting config;
private final ConcurrentMap<String, Grant> grants = new ConcurrentHashMap<>(); private final Map<String, Path> published = new ConcurrentHashMap<>();
private final ConcurrentMap<String, Path> published = new ConcurrentHashMap<>(); private final Map<String, Grant> grants = new ConcurrentHashMap<>();
private final Map<String, Integer> downloadsByIp = new HashMap<>(); private final Map<String, Integer> downloadsByIp = new HashMap<>();
private final ExecutorService workers = Executors.newVirtualThreadPerTaskExecutor();
private HttpServer server;
private int activeDownloads; private int activeDownloads;
private EventLoopGroup eventLoops;
private Channel listeningChannel;
public PackHost(PackConfig.Hosting config) { public PackHost(PackConfig.Hosting config) {
this.config = config; this.config = config;
} }
public void start() throws InterruptedException { public void start() throws IOException {
eventLoops = new MultiThreadIoEventLoopGroup(2, NioIoHandler.newFactory()); server = HttpServer.create(new InetSocketAddress(config.bindAddress, config.port), 0);
ServerBootstrap bootstrap = new ServerBootstrap() server.createContext("/", this::handle);
.group(eventLoops) server.setExecutor(workers);
.channel(NioServerSocketChannel.class) server.start();
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel channel) {
installHttp(channel.pipeline());
}
});
try {
listeningChannel = bootstrap.bind(config.bindAddress, config.port).sync().channel();
} catch (InterruptedException | RuntimeException e) {
close();
throw e;
}
} }
public void publish(PackBuilder.Pack pack) { public void publish(PackBuilder.Pack pack) {
@@ -96,20 +57,100 @@ public final class PackHost implements AutoCloseable {
if (grants.size() >= 10000) { if (grants.size() >= 10000) {
throw new IllegalStateException("Too many resource-pack download grants"); throw new IllegalStateException("Too many resource-pack download grants");
} }
String token = UUID.randomUUID().toString(); String token = UUID.randomUUID().toString();
long expires = now + config.tokenLifetimeSeconds * 1000L; grants.put(token, new Grant(pack.sha1(), now + config.tokenLifetimeSeconds * 1000L));
grants.put(token, new Grant(pack.sha1(), expires));
return path + "?token=" + token; return path + "?token=" + token;
} }
private boolean authorized(QueryStringDecoder uri, String hash) { 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) { if (!config.blockNonGameRequests) {
return true; return true;
} }
String token = uri.parameters().getOrDefault("token", List.of("")).getFirst(); String query = uri.getRawQuery();
Grant grant = grants.get(token); if (query == null) {
return grant != null && grant.expires() >= System.currentTimeMillis() && grant.hash().equals(hash); 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) { private synchronized boolean acquireDownload(String ip) {
@@ -132,118 +173,12 @@ public final class PackHost implements AutoCloseable {
activeDownloads--; activeDownloads--;
} }
private void installHttp(ChannelPipeline pipeline) {
long bytesPerSecond = config.maxSpeedMiBPerSecond * 1024L * 1024L;
pipeline.addLast("astrapacks_timeout", new ReadTimeoutHandler(30));
pipeline.addLast("astrapacks_http", new HttpServerCodec(4096, 8192, 8192));
pipeline.addLast("astrapacks_aggregate", new HttpObjectAggregator(4096));
pipeline.addLast("astrapacks_speed", new ChannelTrafficShapingHandler(bytesPerSecond, 0));
pipeline.addLast("astrapacks_chunks", new ChunkedWriteHandler());
pipeline.addLast("astrapacks_download", new Download());
}
private final class Download extends SimpleChannelInboundHandler<FullHttpRequest> {
private boolean handled;
@Override
protected void channelRead0(ChannelHandlerContext context, FullHttpRequest request) throws IOException {
if (handled) {
return;
}
handled = true;
if (!request.decoderResult().isSuccess()) {
sendError(context, HttpResponseStatus.BAD_REQUEST);
return;
}
if (!request.method().equals(HttpMethod.GET) && !request.method().equals(HttpMethod.HEAD)) {
sendError(context, HttpResponseStatus.METHOD_NOT_ALLOWED);
return;
}
QueryStringDecoder uri = new QueryStringDecoder(request.uri());
String path = uri.path();
if (!path.matches("/astrapacks/[a-f0-9]{40}\\.zip")) {
sendError(context, HttpResponseStatus.NOT_FOUND);
return;
}
String hash = path.substring("/astrapacks/".length(), path.length() - ".zip".length());
Path file = published.get(hash);
if (file == null || !Files.isRegularFile(file)) {
sendError(context, HttpResponseStatus.NOT_FOUND);
return;
}
if (!authorized(uri, hash)) {
sendError(context, HttpResponseStatus.FORBIDDEN);
return;
}
InetSocketAddress remote = (InetSocketAddress) context.channel().remoteAddress();
String ip = remote.getAddress().getHostAddress();
if (!acquireDownload(ip)) {
sendError(context, HttpResponseStatus.TOO_MANY_REQUESTS);
return;
}
// Every response closes its connection, so this releases the slot exactly once.
context.channel().closeFuture().addListener(future -> releaseDownload(ip));
sendFile(context, file, hash, request.method().equals(HttpMethod.HEAD));
}
@Override
public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
context.close();
}
}
private static void sendFile(ChannelHandlerContext context, Path file, String hash, boolean headOnly)
throws IOException {
ChunkedNioFile stream = null;
try {
long size = Files.size(file);
if (!headOnly) {
stream = new ChunkedNioFile(file.toFile(), 65536);
}
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/zip");
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, size);
response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
response.headers().set(HttpHeaderNames.CACHE_CONTROL, "private, max-age=31536000, immutable");
response.headers().set(HttpHeaderNames.ETAG, '"' + hash + '"');
context.write(response);
if (stream != null) {
context.write(new HttpChunkedInput(stream));
} else {
context.write(LastHttpContent.EMPTY_LAST_CONTENT);
}
context.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
} catch (Exception e) {
if (stream != null) {
try {
stream.close();
} catch (Exception closeError) {
e.addSuppressed(closeError);
}
}
context.close();
throw e;
}
}
private static void sendError(ChannelHandlerContext context, HttpResponseStatus status) {
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);
response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
context.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
@Override @Override
public void close() { public void close() {
if (listeningChannel != null) { if (server != null) {
listeningChannel.close().awaitUninterruptibly(); server.stop(0);
}
if (eventLoops != null) {
eventLoops.shutdownGracefully(0, 2, TimeUnit.SECONDS).awaitUninterruptibly();
} }
workers.shutdownNow();
grants.clear(); grants.clear();
} }
} }
@@ -46,7 +46,7 @@ public final class PackRuntime implements AutoCloseable {
this.host = new PackHost(config.hosting); this.host = new PackHost(config.hosting);
} }
public void start() throws IOException, InterruptedException { public void start() throws IOException {
if (!config.enabled) { if (!config.enabled) {
return; return;
} }
@@ -25,7 +25,6 @@ public final class PackSession implements ConfigurationTask {
private long deadlineNanos; private long deadlineNanos;
private int retriesUsed; private int retriesUsed;
private boolean complete; private boolean complete;
private boolean disconnected;
public PackSession(PackRuntime runtime, ServerCommonPacketListenerImpl listener) { public PackSession(PackRuntime runtime, ServerCommonPacketListenerImpl listener) {
this.runtime = runtime; this.runtime = runtime;
@@ -69,16 +68,12 @@ public final class PackSession implements ConfigurationTask {
} }
public void response(ServerboundResourcePackPacket packet) { public void response(ServerboundResourcePackPacket packet) {
if (requestId == null || disconnected || !requestId.equals(packet.id())) { if (complete || requestId == null || !requestId.equals(packet.id())) {
return; return;
} }
if (config.delivery.logStatus) { if (config.delivery.logStatus) {
AstraPacks.LOG.info("Resource pack {}: {} ({})", playerName(), packet.action(), pack.sha1()); AstraPacks.LOG.info("Resource pack {}: {} ({})", playerName(), packet.action(), pack.sha1());
} }
if (complete) {
return;
}
switch (packet.action()) { switch (packet.action()) {
case SUCCESSFULLY_LOADED -> { case SUCCESSFULLY_LOADED -> {
complete = true; complete = true;
@@ -107,7 +102,7 @@ public final class PackSession implements ConfigurationTask {
@Override @Override
public boolean tick() { public boolean tick() {
if (requestId != null && !complete && !disconnected && System.nanoTime() >= deadlineNanos) { if (requestId != null && !complete && System.nanoTime() - deadlineNanos >= 0) {
fail(config.messages.timeout); fail(config.messages.timeout);
} }
return complete; return complete;
@@ -128,7 +123,7 @@ public final class PackSession implements ConfigurationTask {
} }
private void disconnect(String message) { private void disconnect(String message) {
disconnected = true; requestId = null;
listener.disconnect(PackText.of(message, playerName())); listener.disconnect(PackText.of(message, playerName()));
} }
@@ -10,6 +10,7 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.Map; import java.util.Map;
import java.util.Random;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
@@ -257,6 +258,48 @@ class PackCoreTest {
} }
} }
@Test
void hostLimitsDownloadsPerIpAndReleasesCompletedDownloads() throws Exception {
checkDownloadLimit(1, 10);
}
@Test
void hostLimitsTotalDownloadsAndThrottlesTransfer() throws Exception {
checkDownloadLimit(10, 1);
}
private void checkDownloadLimit(int perIp, int total) throws Exception {
PackConfig config = config();
config.hosting.bindAddress = "127.0.0.1";
config.hosting.maxDownloadsPerIp = perIp;
config.hosting.maxConcurrentDownloads = total;
config.hosting.maxSpeedMiBPerSecond = 1;
try (var reservation = new ServerSocket(0)) {
config.hosting.port = reservation.getLocalPort();
}
byte[] content = new byte[1024 * 1024];
new Random(42).nextBytes(content);
asset("assets/demo/data.bin", "");
Files.write(config.contents(root).resolve("assets/demo/data.bin"), content);
var pack = build(config);
try (PackHost host = new PackHost(config.hosting); HttpClient client = HttpClient.newHttpClient()) {
host.publish(pack);
host.start();
URI uri = URI.create("http://127.0.0.1:" + config.hosting.port + host.issuePath(pack));
long started = System.nanoTime();
var download = client.send(HttpRequest.newBuilder(uri).build(), HttpResponse.BodyHandlers.ofInputStream());
assertEquals(200, download.statusCode());
try (var body = download.body()) {
assertEquals(429, get(client, uri.toString()).statusCode());
assertArrayEquals(Files.readAllBytes(pack.path()), body.readAllBytes());
}
assertTrue(System.nanoTime() - started >= 900_000_000L, "Transfer must respect the configured speed");
var head = client.send(HttpRequest.newBuilder(uri).method("HEAD", HttpRequest.BodyPublishers.noBody()).build(),
HttpResponse.BodyHandlers.discarding());
assertEquals(200, head.statusCode(), "Completed downloads must release their slot");
}
}
private static HttpResponse<Void> get(HttpClient client, String url) throws Exception { private static HttpResponse<Void> get(HttpClient client, String url) throws Exception {
return client.send(HttpRequest.newBuilder(URI.create(url)).build(), HttpResponse.BodyHandlers.discarding()); return client.send(HttpRequest.newBuilder(URI.create(url)).build(), HttpResponse.BodyHandlers.discarding());
} }