Files
AstraPacks/src/main/java/online/astradev/packs/PackHost.java
T

250 lines
10 KiB
Java
Raw Normal View History

package online.astradev.packs;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
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. */
public final class PackHost implements AutoCloseable {
private record Grant(String hash, long expires) {}
private final PackConfig.Hosting config;
private final ConcurrentMap<String, Grant> grants = new ConcurrentHashMap<>();
private final ConcurrentMap<String, Path> published = new ConcurrentHashMap<>();
private final Map<String, Integer> downloadsByIp = new HashMap<>();
private int activeDownloads;
private EventLoopGroup eventLoops;
private Channel listeningChannel;
public PackHost(PackConfig.Hosting config) {
this.config = config;
}
public void start() throws InterruptedException {
eventLoops = new MultiThreadIoEventLoopGroup(2, NioIoHandler.newFactory());
ServerBootstrap bootstrap = new ServerBootstrap()
.group(eventLoops)
.channel(NioServerSocketChannel.class)
.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) {
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();
long expires = now + config.tokenLifetimeSeconds * 1000L;
grants.put(token, new Grant(pack.sha1(), expires));
return path + "?token=" + token;
}
private boolean authorized(QueryStringDecoder uri, String hash) {
if (!config.blockNonGameRequests) {
return true;
}
String token = uri.parameters().getOrDefault("token", List.of("")).getFirst();
Grant grant = grants.get(token);
return grant != null && grant.expires() >= System.currentTimeMillis() && grant.hash().equals(hash);
}
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--;
}
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
public void close() {
if (listeningChannel != null) {
listeningChannel.close().awaitUninterruptibly();
}
if (eventLoops != null) {
eventLoops.shutdownGracefully(0, 2, TimeUnit.SECONDS).awaitUninterruptibly();
}
grants.clear();
}
}