147 lines
8.4 KiB
Java
147 lines
8.4 KiB
Java
package online.astradev.packs;
|
|||
|
|
|
||
|
|
import io.netty.bootstrap.ServerBootstrap;
|
||
|
|
import io.netty.buffer.ByteBuf;
|
||
|
|
import io.netty.channel.*;
|
||
|
|
import io.netty.channel.nio.NioEventLoopGroup;
|
||
|
|
import io.netty.channel.socket.SocketChannel;
|
||
|
|
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
||
|
|
import io.netty.handler.codec.ByteToMessageDecoder;
|
||
|
|
import io.netty.handler.codec.http.*;
|
||
|
|
import io.netty.handler.stream.ChunkedNioFile;
|
||
|
|
import io.netty.handler.stream.ChunkedWriteHandler;
|
||
|
|
import io.netty.handler.timeout.ReadTimeoutHandler;
|
||
|
|
import io.netty.handler.traffic.ChannelTrafficShapingHandler;
|
||
|
|
import java.io.IOException;
|
||
|
|
import java.net.*;
|
||
|
|
import java.nio.file.*;
|
||
|
|
import java.util.*;
|
||
|
|
import java.util.concurrent.*;
|
||
|
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||
|
|
|
||
|
|
/** Only immutable pack artifacts are exposed; no directory or arbitrary file routes. */
|
||
|
|
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> downloads = new HashMap<>();
|
||
|
|
private int active;
|
||
|
|
private EventLoopGroup group;
|
||
|
|
private Channel listening;
|
||
|
|
public PackHost(PackConfig.Hosting config) { this.config = config; }
|
||
|
|
public void publish(PackBuilder.Pack pack) { published.put(pack.sha1(), pack.path()); }
|
||
|
|
public String issuePath(PackBuilder.Pack pack) {
|
||
|
|
String path = "/astrapacks/" + pack.sha1() + ".zip";
|
||
|
|
if (!config.blockNonGameRequests) return path;
|
||
|
|
long now = System.currentTimeMillis();
|
||
|
|
grants.entrySet().removeIf(e -> e.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;
|
||
|
|
}
|
||
|
|
public void start() throws InterruptedException {
|
||
|
|
if (!config.mode.equals("self_host")) return;
|
||
|
|
group = new NioEventLoopGroup(2);
|
||
|
|
try {
|
||
|
|
listening = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class)
|
||
|
|
.childHandler(new ChannelInitializer<SocketChannel>() {
|
||
|
|
@Override protected void initChannel(SocketChannel ch) { installHttp(ch.pipeline()); }
|
||
|
|
}).bind(config.bindAddress, config.port).sync().channel();
|
||
|
|
} catch (Throwable e) { close(); throw e; }
|
||
|
|
}
|
||
|
|
public void installSniffer(ChannelPipeline pipeline) { pipeline.addFirst("astrapacks_detect", new Sniffer()); }
|
||
|
|
private void installHttp(ChannelPipeline p) {
|
||
|
|
p.addLast("astrapacks_timeout", new ReadTimeoutHandler(30));
|
||
|
|
p.addLast("astrapacks_http", new HttpServerCodec(4096, 8192, 8192));
|
||
|
|
p.addLast("astrapacks_aggregate", new HttpObjectAggregator(4096));
|
||
|
|
p.addLast("astrapacks_speed", new ChannelTrafficShapingHandler(config.maxSpeedMiBPerSecond * 1024L * 1024L, 0));
|
||
|
|
p.addLast("astrapacks_chunks", new ChunkedWriteHandler());
|
||
|
|
p.addLast("astrapacks_download", new Download());
|
||
|
|
}
|
||
|
|
private final class Sniffer extends ByteToMessageDecoder {
|
||
|
|
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
|
||
|
|
if (in.readableBytes() < 4) return;
|
||
|
|
int start = in.readerIndex();
|
||
|
|
boolean http = (in.getByte(start) == 'G' && in.getByte(start + 1) == 'E' && in.getByte(start + 2) == 'T' && in.getByte(start + 3) == ' ')
|
||
|
|
|| (in.getByte(start) == 'H' && in.getByte(start + 1) == 'E' && in.getByte(start + 2) == 'A' && in.getByte(start + 3) == 'D');
|
||
|
|
if (http) {
|
||
|
|
ChannelPipeline p = ctx.pipeline();
|
||
|
|
for (String name : new ArrayList<>(p.names()))
|
||
|
|
if (p.get(name) != null && p.get(name) != this) p.remove(name);
|
||
|
|
installHttp(p);
|
||
|
|
}
|
||
|
|
// Removal forwards all accumulated bytes to the selected protocol decoder.
|
||
|
|
ctx.pipeline().remove(this);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
private synchronized boolean acquire(String ip) {
|
||
|
|
int count = downloads.getOrDefault(ip, 0);
|
||
|
|
if (count >= config.maxDownloadsPerIp || active >= config.maxConcurrentDownloads) return false;
|
||
|
|
downloads.put(ip, count + 1); active++; return true;
|
||
|
|
}
|
||
|
|
private synchronized void release(String ip) {
|
||
|
|
downloads.computeIfPresent(ip, (key, count) -> count <= 1 ? null : count - 1); active--;
|
||
|
|
}
|
||
|
|
private final class Download extends SimpleChannelInboundHandler<FullHttpRequest> {
|
||
|
|
private boolean handled;
|
||
|
|
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws IOException {
|
||
|
|
if (handled) return;
|
||
|
|
handled = true;
|
||
|
|
if (!request.decoderResult().isSuccess()) { error(ctx, HttpResponseStatus.BAD_REQUEST); return; }
|
||
|
|
if (!request.method().equals(HttpMethod.GET) && !request.method().equals(HttpMethod.HEAD)) {
|
||
|
|
error(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED); return;
|
||
|
|
}
|
||
|
|
QueryStringDecoder uri = new QueryStringDecoder(request.uri());
|
||
|
|
String path = uri.path();
|
||
|
|
if (!path.matches("/astrapacks/[a-f0-9]{40}\\.zip")) { error(ctx, HttpResponseStatus.NOT_FOUND); return; }
|
||
|
|
String hash = path.substring(12, 52);
|
||
|
|
Path file = published.get(hash);
|
||
|
|
if (file == null || !Files.isRegularFile(file)) { error(ctx, HttpResponseStatus.NOT_FOUND); return; }
|
||
|
|
if (config.blockNonGameRequests) {
|
||
|
|
String token = uri.parameters().getOrDefault("token", List.of("")).getFirst();
|
||
|
|
Grant grant = grants.get(token);
|
||
|
|
if (grant == null || grant.expires() < System.currentTimeMillis() || !grant.hash().equals(hash)) {
|
||
|
|
error(ctx, HttpResponseStatus.FORBIDDEN); return;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
String ip = ((InetSocketAddress)ctx.channel().remoteAddress()).getAddress().getHostAddress();
|
||
|
|
if (!acquire(ip)) { error(ctx, HttpResponseStatus.TOO_MANY_REQUESTS); return; }
|
||
|
|
AtomicBoolean released = new AtomicBoolean();
|
||
|
|
Runnable cleanup = () -> { if (released.compareAndSet(false, true)) release(ip); };
|
||
|
|
ctx.channel().closeFuture().addListener(f -> cleanup.run());
|
||
|
|
ChunkedNioFile stream = null;
|
||
|
|
try {
|
||
|
|
long size = Files.size(file);
|
||
|
|
if (request.method().equals(HttpMethod.GET)) 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 + '"');
|
||
|
|
ctx.write(response);
|
||
|
|
if (stream != null) ctx.write(new HttpChunkedInput(stream));
|
||
|
|
else ctx.write(LastHttpContent.EMPTY_LAST_CONTENT);
|
||
|
|
ctx.writeAndFlush(io.netty.buffer.Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
|
||
|
|
} catch (Throwable e) {
|
||
|
|
if (stream != null) try { stream.close(); } catch (Exception ignored) { }
|
||
|
|
cleanup.run(); ctx.close();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { ctx.close(); }
|
||
|
|
}
|
||
|
|
private static void error(ChannelHandlerContext ctx, 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);
|
||
|
|
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
|
||
|
|
}
|
||
|
|
@Override public void close() {
|
||
|
|
if (listening != null) listening.close().awaitUninterruptibly();
|
||
|
|
if (group != null) group.shutdownGracefully(0, 2, TimeUnit.SECONDS).awaitUninterruptibly();
|
||
|
|
grants.clear();
|
||
|
|
}
|
||
|
|
}
|