Simplify pack delivery, build lifecycle and HTTP handling; remove project clutter
This commit is contained in:
@@ -1,147 +0,0 @@
|
|||||||
# AstraPacks
|
|
||||||
|
|
||||||
Серверное ядро ресурспаков AstraDev для **Minecraft 26.2 / NeoForge 26.2.0.79 / Java 25+**.
|
|
||||||
Установка мода на клиент не нужна. Paper, Bukkit и ItemsAdder не используются.
|
|
||||||
|
|
||||||
## Установка
|
|
||||||
|
|
||||||
Поместите `AstraPacks-0.2.0.jar` в `mods` и запустите сервер.
|
|
||||||
Настройки создаются в `config/astrapacks.json`, исходные ресурсы — в `astrapacks/contents`,
|
|
||||||
готовые ZIP — в `astrapacks/output`. По умолчанию включены раздача через игровой порт,
|
|
||||||
отправка при входе и обязательная загрузка до допуска в мир.
|
|
||||||
Пустая папка ресурсов создаёт технически корректный пак только с `pack.mcmeta`.
|
|
||||||
Контент остальных проектов добавляется при их переносе; эта версия не переносит предметы и конфигурации ItemsAdder.
|
|
||||||
|
|
||||||
`resource-pack` в `server.properties` должен быть пустым: отправкой управляет AstraPacks.
|
|
||||||
Если одновременно настроена ванильная отправка, мод сообщает об ошибке при старте.
|
|
||||||
Существующие настройки, миры и данные мод не заменяет.
|
|
||||||
|
|
||||||
## Хостинг
|
|
||||||
|
|
||||||
`hosting.mode` принимает ровно одно из трёх значений:
|
|
||||||
|
|
||||||
| Режим | Поведение |
|
|
||||||
| --- | --- |
|
|
||||||
| `simple_self_host` | HTTP и Minecraft работают на одном игровом TCP-порту. Дополнительный порт не требуется. |
|
|
||||||
| `self_host` | Отдельный HTTP-сервер на `bindAddress:port`. Для удалённых игроков нужен доступ к этому порту. |
|
|
||||||
| `no_host` | HTTP-сервер отсутствует. Готовый ZIP размещается владельцем на внешнем хостинге, ссылка задаётся в `externalUrl`. |
|
|
||||||
|
|
||||||
Для встроенных режимов `publicAddress: "auto"` использует адрес, с которым клиент подключился
|
|
||||||
к серверу, и игровой порт (либо `hosting.port` в режиме `self_host`).
|
|
||||||
Для прокси, SRV, перенаправления портов или внешнего HTTPS задайте полный базовый адрес явно:
|
|
||||||
`"http://play.example.org:25565"` или `"https://packs.example.org"`.
|
|
||||||
AstraPacks добавляет `/astrapacks/<sha1>.zip` и временный токен к этому адресу.
|
|
||||||
HTTP не перенаправляется автоматически через Minecraft-прокси: адрес должен вести к HTTP-обработчику AstraPacks.
|
|
||||||
HTTPS завершается на вашем обратном прокси; встроенный обработчик использует HTTP.
|
|
||||||
|
|
||||||
Для внешнего хостинга укажите прямую ссылку на ZIP в `hosting.externalUrl`.
|
|
||||||
`/astrapacks build` сохраняет ZIP локально. Перед публикацией мод скачивает внешний файл
|
|
||||||
и сверяет SHA-1; если файлы различаются, новая версия не отправляется игрокам.
|
|
||||||
Загрузите указанный в сообщении ZIP на хостинг и выполните `/astrapacks publish`.
|
|
||||||
Автоматического доступа к аккаунтам хостинга или загрузки по FTP/S3 в моде нет.
|
|
||||||
Для режима только сборки без отправки установите `delivery.sendOnJoin=false` и `delivery.required=false`.
|
|
||||||
|
|
||||||
## Настройки
|
|
||||||
|
|
||||||
Файл JSON хранится в UTF-8. Отсутствующие поля получают значения по умолчанию.
|
|
||||||
Недопустимые значения дают ошибку; файл автоматически не переписывается.
|
|
||||||
Все пути относительны папке сервера, также допускаются абсолютные пути.
|
|
||||||
|
|
||||||
| Поле | По умолчанию | Назначение |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| `enabled` | `true` | Включить ядро; изменение требует перезапуска |
|
|
||||||
| `build.storageDirectory` | `astrapacks` | Каталог хранения сборок |
|
|
||||||
| `build.sources` | `["astrapacks/contents"]` | Список папок и ZIP в порядке объединения |
|
|
||||||
| `build.scanModJars` | `true` | Читать объявленные наборы ресурсов из JAR в `mods` |
|
|
||||||
| `build.onStartup` | `true` | Собирать при старте; иначе проверять и использовать последнюю сборку |
|
|
||||||
| `build.resendAfterBuild` | `true` | Отправлять опубликованный пак онлайн-игрокам |
|
|
||||||
| `build.description` | `AstraDev — общий серверный ресурспак` | Описание в `pack.mcmeta` |
|
|
||||||
| `build.conflictPolicy` | `error` | `error`: остановить сборку при разных файлах по одному пути; `last_wins`: поздний источник побеждает |
|
|
||||||
| `build.maxFileMiB` | `32` | Максимальный размер одного распакованного ресурса |
|
|
||||||
| `build.maxTotalMiB` | `256` | Максимальный суммарный объём прочитанных ресурсов |
|
|
||||||
| `build.maxFiles` | `50000` | Максимальное число уникальных ресурсов |
|
|
||||||
| `hosting.mode` | `simple_self_host` | Выбор режима из таблицы выше |
|
|
||||||
| `hosting.publicAddress` | `auto` | Публичный базовый HTTP(S)-адрес для встроенного хостинга |
|
|
||||||
| `hosting.bindAddress` | `0.0.0.0` | Интерфейс отдельного HTTP-сервера |
|
|
||||||
| `hosting.port` | `8163` | Порт режима `self_host` |
|
|
||||||
| `hosting.externalUrl` | пусто | Прямая ссылка на внешний ZIP |
|
|
||||||
| `hosting.blockNonGameRequests` | `true` | Для встроенного хостинга требовать временный токен, выданный при отправке пака |
|
|
||||||
| `hosting.maxDownloadsPerIp` | `5` | Одновременные скачивания с одного IP |
|
|
||||||
| `hosting.maxConcurrentDownloads` | `32` | Общий предел одновременных скачиваний |
|
|
||||||
| `hosting.maxSpeedMiBPerSecond` | `30` | Скорость одного скачивания |
|
|
||||||
| `hosting.tokenLifetimeSeconds` | `600` | Срок действия ссылки; не меньше тайм-аута загрузки |
|
|
||||||
| `delivery.sendOnJoin` | `true` | Отправлять во время подключения |
|
|
||||||
| `delivery.required` | `true` | Не допускать в мир без подтверждённой загрузки |
|
|
||||||
| `delivery.kickOnFailure` | `true` | Отключать при ошибке/тайм-ауте и для необязательного пака |
|
|
||||||
| `delivery.timeoutSeconds` | `120` | Предельное время одной попытки, включая окно подтверждения |
|
|
||||||
| `delivery.retries` | `1` | Повторные отправки при ошибке скачивания/применения, но не при отказе или тайм-ауте |
|
|
||||||
| `delivery.logStatus` | `true` | Записывать ответы клиента в журнал |
|
|
||||||
|
|
||||||
`required=true` подразумевает `sendOnJoin=true` и отключение при окончательной ошибке,
|
|
||||||
независимо от `kickOnFailure`. Ответы `ACCEPTED` и `DOWNLOADED` не разрешают вход:
|
|
||||||
нужен `SUCCESSFULLY_LOADED` для UUID текущей попытки. Ответы на старые и неизвестные UUID игнорируются.
|
|
||||||
Если рабочий ZIP недоступен, обязательный режим отказывает во входе с сообщением `unavailable`.
|
|
||||||
Как и стандартный протокол Minecraft, это доверяет ответу клиента; проверить фактическую отрисовку на модифицированном клиенте сервер не может.
|
|
||||||
|
|
||||||
Все пользовательские тексты настраиваются в `messages`:
|
|
||||||
`prompt`, `declined`, `failed`, `timeout`, `unavailable`, `loaded`.
|
|
||||||
Поддерживаются `{player}`, переносы строк, цвета `&0`–`&f`, стили `&k`–`&o`, сброс `&r`.
|
|
||||||
Пустой `prompt` скрывает дополнительный текст окна; пустой `loaded` отключает сообщение об успехе.
|
|
||||||
|
|
||||||
## Команды
|
|
||||||
|
|
||||||
Требуется уровень администратора 3 или консоль.
|
|
||||||
|
|
||||||
| Команда | Действие |
|
|
||||||
| --- | --- |
|
|
||||||
| `/astrapacks status` | Режим, обязательность, текущая сборка, путь ZIP |
|
|
||||||
| `/astrapacks build` | Пересобрать ресурсы и опубликовать проверенную версию |
|
|
||||||
| `/astrapacks reload` | Перечитать настройки и пересобрать; при ошибке остаётся прежняя рабочая конфигурация |
|
|
||||||
| `/astrapacks publish` | Опубликовать уже собранный ZIP, в том числе после загрузки на внешний хостинг |
|
|
||||||
| `/astrapacks send <players>` | Отправить текущий пак игроку или селектору, например `@a` |
|
|
||||||
|
|
||||||
Сборка по команде выполняется в отдельном потоке. Изменение `hosting` или `enabled`
|
|
||||||
требует перезапуска и явно отклоняется командой reload.
|
|
||||||
Старая версия ZIP сохраняется: игроки, уже получившие ссылку, могут закончить скачивание.
|
|
||||||
Автоматической очистки архива ZIP нет; ненужные старые ZIP можно удалять после отключения использующих их клиентов.
|
|
||||||
|
|
||||||
## Ресурсы и модули
|
|
||||||
|
|
||||||
Источником может быть корень ресурспака с `assets/` и необязательным `pack.png`,
|
|
||||||
каталог именованных паков (`contents/module/assets/...`) или ZIP.
|
|
||||||
Одинаковые дубликаты допустимы. Порядок: `build.sources`, затем JAR модов по имени файла;
|
|
||||||
внутри каталога пути обрабатываются по алфавиту.
|
|
||||||
Исходники не переписываются. Собственный `pack.mcmeta` создаёт AstraPacks с форматом **88.0**.
|
|
||||||
Внешние `pack.mcmeta`, data-паки, оверлеи и произвольные файлы не объединяются.
|
|
||||||
JSON-файлы с одинаковым путём не сливаются по ключам: используйте единый исходный файл
|
|
||||||
или явно выбирайте `last_wins`. В ошибке конфликта указаны оба источника.
|
|
||||||
|
|
||||||
Для нового серверного мода добавьте в корень JAR `astra-pack.properties`:
|
|
||||||
|
|
||||||
```properties
|
|
||||||
schema=2
|
|
||||||
```
|
|
||||||
|
|
||||||
Готовые клиентские ресурсы храните в `astra-resourcepack/assets/<namespace>/...`,
|
|
||||||
значок — в `astra-resourcepack/pack.png`. JAR без дескриптора не сканируется как ресурспак.
|
|
||||||
Это формат готовых ресурсов Minecraft; схемы и генераторы предметов ItemsAdder не поддерживаются.
|
|
||||||
Используйте зависимость NeoForge на `astrapacks` со стороной `SERVER` для модов,
|
|
||||||
которые требуют наличия этого ядра. Никаких клиентских каналов или синхронизируемых реестров ядро не добавляет.
|
|
||||||
|
|
||||||
## Сборка и проверка
|
|
||||||
|
|
||||||
`gradlew.bat build` (Windows), `./gradlew build` (Linux).
|
|
||||||
Результат: `build/libs/AstraPacks-0.2.0.jar`.
|
|
||||||
JUnit проверяет детерминизм, конфликты, восстановление предыдущей сборки, опасные пути,
|
|
||||||
лимиты, JAR-модули, настройки и HTTP-раздачу.
|
|
||||||
`tools/smoke_protocol.py` проверяет вход по ванильному протоколу на отдельном локальном
|
|
||||||
тестовом сервере. Условия запуска указаны в самом скрипте. Результаты — в `VERIFICATION.md`.
|
|
||||||
|
|
||||||
## Источники требований
|
|
||||||
|
|
||||||
Поведение режимов и сообщений спроектировано с учётом документации ItemsAdder:
|
|
||||||
[Simple Self Host](https://wiki.itemsadder.com/plugin-usage/plugin-configuration/resourcepack-hosting/simple-self-host/),
|
|
||||||
[Self hosting](https://wiki.itemsadder.com/plugin-usage/plugin-configuration/resourcepack-hosting/self-hosting/),
|
|
||||||
[No Host](https://wiki.itemsadder.com/plugin-usage/plugin-configuration/resourcepack-hosting/no-host/),
|
|
||||||
[Prompt](https://wiki.itemsadder.com/plugin-usage/plugin-configuration/resourcepack-prompt-message-1.17%2B/).
|
|
||||||
Это самостоятельная реализация для NeoForge; файл конфигурации ItemsAdder не импортируется.
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
# Проверка AstraPacks 0.2.0 — 2026-09-06
|
|
||||||
|
|
||||||
Платформа: Minecraft 26.2, NeoForge 26.2.0.79, Java 26.0.2 (целевой байткод Java 25).
|
|
||||||
|
|
||||||
## Автоматические проверки
|
|
||||||
|
|
||||||
`gradlew.bat build`: успешно, 11 JUnit-тестов, 0 ошибок и пропусков.
|
|
||||||
Проверены: одинаковый результат повторной сборки; удаление устаревших ресурсов;
|
|
||||||
сохранение предыдущего ZIP при конфликте; одинаковые дубликаты; last_wins;
|
|
||||||
опасные ZIP-пути; лимиты размера; формат модуля schema=2; валидация конфигурации;
|
|
||||||
повреждение сохранённой сборки; точная HTTP-раздача, HEAD и ограничение токеном;
|
|
||||||
сверка внешнего ZIP перед публикацией.
|
|
||||||
|
|
||||||
## Проверка протокола
|
|
||||||
|
|
||||||
На отдельном сервере, доступном только через 127.0.0.1:25585, запущен
|
|
||||||
`python tools/smoke_protocol.py`. Тестовый сервер использовал отключённую авторизацию
|
|
||||||
и сжатие только для локальных синтетических клиентов; настройки рабочего сервера не менялись.
|
|
||||||
Клиенты использовали ванильный протокол 776 без модовых каналов.
|
|
||||||
|
|
||||||
Все шесть сценариев прошли:
|
|
||||||
|
|
||||||
- DECLINED — отключение до входа в мир с настроенным текстом.
|
|
||||||
- FAILED_DOWNLOAD — отключение до входа в мир.
|
|
||||||
- FAILED_RELOAD — отключение до входа в мир.
|
|
||||||
- SUCCESSFULLY_LOADED — завершение этапа конфигурации, допускающего вход.
|
|
||||||
- ACCEPTED без успешной загрузки — отключение по тайм-ауту; вход не разрешён.
|
|
||||||
- SUCCESSFULLY_LOADED с чужим UUID — игнорируется, затем тайм-аут; вход не разрешён.
|
|
||||||
|
|
||||||
Во всех сценариях ZIP был скачан по выданной ссылке через тот же TCP-порт, что и Minecraft;
|
|
||||||
SHA-1 загруженных байтов совпал с hash в серверном пакете, pack.mcmeta присутствует.
|
|
||||||
Это проверка сетевого протокола; ручная проверка визуального окна и отрисовки
|
|
||||||
ресурсов в графическом Minecraft-клиенте не проводилась.
|
|
||||||
|
|
||||||
## Рабочий сервер
|
|
||||||
|
|
||||||
JAR установлен непосредственно в:
|
|
||||||
`C:\Users\ScarPC\Documents\NeoForge Server 26.2\mods\AstraPacks-0.2.0.jar`.
|
|
||||||
|
|
||||||
SHA-256 сборки и установленного файла совпадает:
|
|
||||||
`23EBDCDC328D763B5B2E9ECFFB51E2B80424768908D4DA69041F96622E75D3AB`.
|
|
||||||
|
|
||||||
При первом размещении прежнего AstraPacks-мода в mods не было.
|
|
||||||
Промежуточная проверенная сборка перед финальной заменой сохранена в:
|
|
||||||
`C:\Users\ScarPC\Documents\NeoForge Server 26.2\old-mods\20260906-182107\AstraPacks-0.2.0.jar`.
|
|
||||||
|
|
||||||
Сервер успешно загружает мод. Проверены команды status, build, reload,
|
|
||||||
создание config/astrapacks.json и ZIP, а также HTTP 403 при обращении без токена.
|
|
||||||
По умолчанию активны simple_self_host, sendOnJoin и required.
|
|
||||||
В текущем ZIP только метаданные: ресурсы других Astra-модулей ещё не перенесены.
|
|
||||||
После проверки сервер штатно остановлен.
|
|
||||||
|
|
||||||
В JAR нет plugin.yml, классов AstraPacksPlugin/ContentSync, библиотек Paper/ItemsAdder,
|
|
||||||
тестового сервера или тестовых ресурсов. HTTP-библиотеки берутся из NeoForge,
|
|
||||||
тестовые зависимости в JAR не включены.
|
|
||||||
Внешняя доступность публичного адреса/NAT и проверка графическим клиентом остаются непроверенными.
|
|
||||||
+15
-4
@@ -16,12 +16,23 @@ dependencies {
|
|||||||
}
|
}
|
||||||
neoForge {
|
neoForge {
|
||||||
version = "26.2.0.79"
|
version = "26.2.0.79"
|
||||||
mods { create("astrapacks") { sourceSet(sourceSets.main.get()) } }
|
mods {
|
||||||
|
create("astrapacks") {
|
||||||
|
sourceSet(sourceSets.main.get())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
java {
|
||||||
|
toolchain.languageVersion.set(JavaLanguageVersion.of(25))
|
||||||
|
}
|
||||||
|
tasks.withType<JavaCompile>().configureEach {
|
||||||
|
options.encoding = "UTF-8"
|
||||||
|
options.release.set(25)
|
||||||
}
|
}
|
||||||
java { toolchain.languageVersion.set(JavaLanguageVersion.of(25)) }
|
|
||||||
tasks.withType<JavaCompile>().configureEach { options.encoding = "UTF-8"; options.release.set(25) }
|
|
||||||
tasks.processResources {
|
tasks.processResources {
|
||||||
inputs.property("modVersion", project.version)
|
inputs.property("modVersion", project.version)
|
||||||
filesMatching("META-INF/neoforge.mods.toml") { expand("version" to project.version) }
|
filesMatching("META-INF/neoforge.mods.toml") { expand("version" to project.version) }
|
||||||
}
|
}
|
||||||
tasks.test { useJUnitPlatform() }
|
tasks.test {
|
||||||
|
useJUnitPlatform()
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
package online.astradev.packs;
|
package online.astradev.packs;
|
||||||
|
|
||||||
import java.nio.file.Path;
|
import com.mojang.brigadier.context.CommandContext;
|
||||||
|
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||||
|
|
||||||
|
import net.minecraft.commands.CommandSourceStack;
|
||||||
import net.minecraft.commands.Commands;
|
import net.minecraft.commands.Commands;
|
||||||
import net.minecraft.commands.arguments.EntityArgument;
|
import net.minecraft.commands.arguments.EntityArgument;
|
||||||
import net.minecraft.network.chat.Component;
|
import net.minecraft.network.chat.Component;
|
||||||
|
import net.minecraft.server.level.ServerPlayer;
|
||||||
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
|
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
|
||||||
import net.neoforged.api.distmarker.Dist;
|
import net.neoforged.api.distmarker.Dist;
|
||||||
import net.neoforged.bus.api.IEventBus;
|
import net.neoforged.bus.api.IEventBus;
|
||||||
@@ -12,15 +16,21 @@ import net.neoforged.fml.loading.FMLPaths;
|
|||||||
import net.neoforged.neoforge.common.NeoForge;
|
import net.neoforged.neoforge.common.NeoForge;
|
||||||
import net.neoforged.neoforge.event.RegisterCommandsEvent;
|
import net.neoforged.neoforge.event.RegisterCommandsEvent;
|
||||||
import net.neoforged.neoforge.event.entity.player.PlayerEvent;
|
import net.neoforged.neoforge.event.entity.player.PlayerEvent;
|
||||||
import net.neoforged.neoforge.event.server.*;
|
import net.neoforged.neoforge.event.server.ServerAboutToStartEvent;
|
||||||
|
import net.neoforged.neoforge.event.server.ServerStoppedEvent;
|
||||||
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
||||||
import net.neoforged.neoforge.network.event.RegisterConfigurationTasksEvent;
|
import net.neoforged.neoforge.network.event.RegisterConfigurationTasksEvent;
|
||||||
|
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Collection;
|
||||||
|
|
||||||
@Mod(value = "astrapacks", dist = Dist.DEDICATED_SERVER)
|
@Mod(value = "astrapacks", dist = Dist.DEDICATED_SERVER)
|
||||||
public final class AstraPacks {
|
public final class AstraPacks {
|
||||||
public static final Logger LOG = LoggerFactory.getLogger("AstraPacks");
|
public static final Logger LOG = LoggerFactory.getLogger("AstraPacks");
|
||||||
|
|
||||||
public AstraPacks(IEventBus modBus) {
|
public AstraPacks(IEventBus modBus) {
|
||||||
modBus.addListener(this::configuration);
|
modBus.addListener(this::configuration);
|
||||||
NeoForge.EVENT_BUS.addListener(this::start);
|
NeoForge.EVENT_BUS.addListener(this::start);
|
||||||
@@ -29,11 +39,13 @@ public final class AstraPacks {
|
|||||||
NeoForge.EVENT_BUS.addListener(this::tick);
|
NeoForge.EVENT_BUS.addListener(this::tick);
|
||||||
NeoForge.EVENT_BUS.addListener(this::login);
|
NeoForge.EVENT_BUS.addListener(this::login);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void start(ServerAboutToStartEvent event) {
|
private void start(ServerAboutToStartEvent event) {
|
||||||
Path root = FMLPaths.GAMEDIR.get().toAbsolutePath();
|
Path root = FMLPaths.GAMEDIR.get().toAbsolutePath();
|
||||||
Path path = FMLPaths.CONFIGDIR.get().resolve("astrapacks.json");
|
Path path = FMLPaths.CONFIGDIR.get().resolve("astrapacks.json");
|
||||||
try {
|
try {
|
||||||
PackRuntime runtime = new PackRuntime(event.getServer(), root, path, PackConfig.load(path));
|
PackRuntime runtime =
|
||||||
|
new PackRuntime(event.getServer(), root, path, PackConfig.load(path));
|
||||||
PackRuntime.INSTANCE = runtime;
|
PackRuntime.INSTANCE = runtime;
|
||||||
runtime.start();
|
runtime.start();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
@@ -42,33 +54,78 @@ public final class AstraPacks {
|
|||||||
throw new IllegalStateException("Cannot initialize AstraPacks", e);
|
throw new IllegalStateException("Cannot initialize AstraPacks", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void configuration(RegisterConfigurationTasksEvent event) {
|
private void configuration(RegisterConfigurationTasksEvent event) {
|
||||||
PackRuntime runtime = PackRuntime.INSTANCE;
|
PackRuntime runtime = PackRuntime.INSTANCE;
|
||||||
if (runtime != null && runtime.config().enabled && runtime.config().delivery.sendOnJoin)
|
if (runtime != null && runtime.config().enabled && runtime.config().delivery.sendOnJoin)
|
||||||
event.register(runtime.session((ServerCommonPacketListenerImpl) event.getListener()));
|
event.register(runtime.session((ServerCommonPacketListenerImpl) event.getListener()));
|
||||||
}
|
}
|
||||||
private void tick(ServerTickEvent.Post event) { if (PackRuntime.INSTANCE != null) PackRuntime.INSTANCE.tick(); }
|
|
||||||
private void login(PlayerEvent.PlayerLoggedInEvent event) {
|
private void tick(ServerTickEvent.Post event) {
|
||||||
if (PackRuntime.INSTANCE != null && event.getEntity() instanceof net.minecraft.server.level.ServerPlayer player) PackRuntime.INSTANCE.welcome(player);
|
if (PackRuntime.INSTANCE != null) PackRuntime.INSTANCE.tick();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void login(PlayerEvent.PlayerLoggedInEvent event) {
|
||||||
|
if (PackRuntime.INSTANCE != null && event.getEntity() instanceof ServerPlayer player)
|
||||||
|
PackRuntime.INSTANCE.welcome(player);
|
||||||
|
}
|
||||||
|
|
||||||
private void stop(ServerStoppedEvent event) {
|
private void stop(ServerStoppedEvent event) {
|
||||||
if (PackRuntime.INSTANCE != null) PackRuntime.INSTANCE.close();
|
if (PackRuntime.INSTANCE != null) PackRuntime.INSTANCE.close();
|
||||||
PackRuntime.INSTANCE = null;
|
PackRuntime.INSTANCE = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void commands(RegisterCommandsEvent event) {
|
private void commands(RegisterCommandsEvent event) {
|
||||||
event.getDispatcher().register(Commands.literal("astrapacks").requires(Commands.hasPermission(Commands.LEVEL_ADMINS))
|
event.getDispatcher()
|
||||||
.executes(ctx -> { ctx.getSource().sendSuccess(() -> Component.literal(PackRuntime.INSTANCE.status()), false); return 1; })
|
.register(
|
||||||
.then(Commands.literal("status").executes(ctx -> { ctx.getSource().sendSuccess(() -> Component.literal(PackRuntime.INSTANCE.status()), false); return 1; }))
|
Commands.literal("astrapacks")
|
||||||
.then(Commands.literal("build").executes(ctx -> { PackRuntime.INSTANCE.rebuild(ctx.getSource(), false, false); return 1; }))
|
.requires(Commands.hasPermission(Commands.LEVEL_ADMINS))
|
||||||
.then(Commands.literal("reload").executes(ctx -> { PackRuntime.INSTANCE.rebuild(ctx.getSource(), true, false); return 1; }))
|
.executes(this::status)
|
||||||
.then(Commands.literal("publish").executes(ctx -> { PackRuntime.INSTANCE.rebuild(ctx.getSource(), false, true); return 1; }))
|
.then(Commands.literal("status").executes(this::status))
|
||||||
.then(Commands.literal("send").then(Commands.argument("players", EntityArgument.players()).executes(ctx -> {
|
.then(
|
||||||
if (!PackRuntime.INSTANCE.config().enabled) {
|
Commands.literal("build")
|
||||||
ctx.getSource().sendFailure(Component.literal("AstraPacks отключён в конфигурации.")); return 0;
|
.executes(ctx -> rebuild(ctx, false, false)))
|
||||||
|
.then(
|
||||||
|
Commands.literal("reload")
|
||||||
|
.executes(ctx -> rebuild(ctx, true, false)))
|
||||||
|
.then(
|
||||||
|
Commands.literal("publish")
|
||||||
|
.executes(ctx -> rebuild(ctx, false, true)))
|
||||||
|
.then(
|
||||||
|
Commands.literal("send")
|
||||||
|
.then(
|
||||||
|
Commands.argument(
|
||||||
|
"players",
|
||||||
|
EntityArgument.players())
|
||||||
|
.executes(this::send))));
|
||||||
}
|
}
|
||||||
var players = EntityArgument.getPlayers(ctx, "players");
|
|
||||||
for (var player : players) PackRuntime.INSTANCE.session(player.connection).start(player.connection::send);
|
private int status(CommandContext<CommandSourceStack> context) {
|
||||||
ctx.getSource().sendSuccess(() -> Component.literal("Ресурспак отправлен: " + players.size()), false); return players.size();
|
context.getSource()
|
||||||
}))));
|
.sendSuccess(() -> Component.literal(PackRuntime.INSTANCE.status()), false);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int rebuild(
|
||||||
|
CommandContext<CommandSourceStack> context, boolean reload, boolean publishOnly) {
|
||||||
|
PackRuntime.INSTANCE.rebuild(context.getSource(), reload, publishOnly);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int send(CommandContext<CommandSourceStack> context) throws CommandSyntaxException {
|
||||||
|
PackRuntime runtime = PackRuntime.INSTANCE;
|
||||||
|
if (!runtime.config().enabled) {
|
||||||
|
context.getSource()
|
||||||
|
.sendFailure(Component.literal("AstraPacks отключён в конфигурации."));
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
Collection<ServerPlayer> players = EntityArgument.getPlayers(context, "players");
|
||||||
|
for (ServerPlayer player : players) {
|
||||||
|
runtime.session(player.connection).start(player.connection::send);
|
||||||
|
}
|
||||||
|
context.getSource()
|
||||||
|
.sendSuccess(
|
||||||
|
() -> Component.literal("Ресурспак отправлен: " + players.size()), false);
|
||||||
|
return players.size();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,72 +1,124 @@
|
|||||||
package online.astradev.packs;
|
package online.astradev.packs;
|
||||||
|
|
||||||
import com.google.gson.*;
|
import com.google.gson.JsonElement;
|
||||||
import java.io.*;
|
import com.google.gson.JsonObject;
|
||||||
import java.net.http.*;
|
import com.google.gson.JsonParser;
|
||||||
import java.time.Duration;
|
|
||||||
|
import java.io.BufferedOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.net.http.HttpClient;
|
||||||
|
import java.net.http.HttpRequest;
|
||||||
|
import java.net.http.HttpResponse;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.nio.file.*;
|
import java.nio.file.Files;
|
||||||
import java.security.*;
|
import java.nio.file.Path;
|
||||||
import java.util.*;
|
import java.nio.file.StandardCopyOption;
|
||||||
import java.util.zip.*;
|
import java.security.DigestInputStream;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.HexFormat;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Properties;
|
||||||
|
import java.util.SortedMap;
|
||||||
|
import java.util.TreeMap;
|
||||||
|
import java.util.zip.ZipEntry;
|
||||||
|
import java.util.zip.ZipFile;
|
||||||
|
import java.util.zip.ZipOutputStream;
|
||||||
|
|
||||||
/** Deterministic, bounded build. Immutable published ZIPs remain valid during later builds. */
|
/** Deterministic, bounded build. Immutable published ZIPs remain valid during later builds. */
|
||||||
public final class PackBuilder {
|
public final class PackBuilder {
|
||||||
public record Pack(Path path, String sha1, int files, long bytes) {}
|
public record Pack(Path path, String sha1, int files, long bytes) {}
|
||||||
|
|
||||||
private record Asset(byte[] data, String owner) {}
|
private record Asset(byte[] data, String owner) {}
|
||||||
|
|
||||||
private final PackConfig config;
|
private final PackConfig config;
|
||||||
private final SortedMap<String, Asset> assets = new TreeMap<>();
|
private final SortedMap<String, Asset> assets = new TreeMap<>();
|
||||||
private long total;
|
private long total;
|
||||||
public PackBuilder(PackConfig config) { this.config = config; }
|
|
||||||
|
public PackBuilder(PackConfig config) {
|
||||||
|
this.config = config;
|
||||||
|
}
|
||||||
|
|
||||||
public Pack build(Path root, String resourceVersion) throws IOException {
|
public Pack build(Path root, String resourceVersion) throws IOException {
|
||||||
|
assets.clear();
|
||||||
|
total = 0;
|
||||||
for (String source : config.build.sources) {
|
for (String source : config.build.sources) {
|
||||||
Path path = root.resolve(source).toAbsolutePath().normalize();
|
Path path = root.resolve(source).toAbsolutePath().normalize();
|
||||||
if (!Files.exists(path)) throw new IOException("Source does not exist: " + path);
|
if (!Files.exists(path)) throw new IOException("Source does not exist: " + path);
|
||||||
if (Files.isDirectory(path)) directory(path); else archive(path, false);
|
if (Files.isDirectory(path)) directory(path);
|
||||||
|
else archive(path, false);
|
||||||
}
|
}
|
||||||
if (config.build.scanModJars && Files.isDirectory(root.resolve("mods"))) {
|
if (config.build.scanModJars && Files.isDirectory(root.resolve("mods"))) {
|
||||||
try (var files = Files.list(root.resolve("mods"))) {
|
try (var files = Files.list(root.resolve("mods"))) {
|
||||||
for (Path jar : files.filter(p -> p.toString().endsWith(".jar")).sorted().toList()) archive(jar, true);
|
for (Path jar : files.filter(p -> p.toString().endsWith(".jar")).sorted().toList())
|
||||||
|
archive(jar, true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
JsonObject pack = new JsonObject();
|
JsonObject pack = new JsonObject();
|
||||||
// 26.2 uses major/minor resource-pack versions.
|
// 26.2 uses major/minor resource-pack versions.
|
||||||
JsonElement version = JsonParser.parseString(resourceVersion);
|
JsonElement version = JsonParser.parseString(resourceVersion);
|
||||||
pack.add("min_format", version); pack.add("max_format", version.deepCopy());
|
pack.add("min_format", version);
|
||||||
|
pack.add("max_format", version.deepCopy());
|
||||||
pack.addProperty("description", config.build.description);
|
pack.addProperty("description", config.build.description);
|
||||||
JsonObject meta = new JsonObject(); meta.add("pack", pack);
|
JsonObject meta = new JsonObject();
|
||||||
assets.put("pack.mcmeta", new Asset(PackConfig.JSON.toJson(meta).getBytes(StandardCharsets.UTF_8), "AstraPacks"));
|
meta.add("pack", pack);
|
||||||
|
assets.put(
|
||||||
|
"pack.mcmeta",
|
||||||
|
new Asset(
|
||||||
|
PackConfig.JSON.toJson(meta).getBytes(StandardCharsets.UTF_8),
|
||||||
|
"AstraPacks"));
|
||||||
Path output = config.storage(root).resolve("output");
|
Path output = config.storage(root).resolve("output");
|
||||||
Files.createDirectories(output);
|
Files.createDirectories(output);
|
||||||
Path temp = Files.createTempFile(output, "build-", ".tmp");
|
Path temp = Files.createTempFile(output, "build-", ".tmp");
|
||||||
try {
|
try {
|
||||||
try (var zip = new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(temp)))) {
|
try (var zip =
|
||||||
|
new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(temp)))) {
|
||||||
for (var item : assets.entrySet()) {
|
for (var item : assets.entrySet()) {
|
||||||
ZipEntry entry = new ZipEntry(item.getKey()); entry.setTime(0);
|
ZipEntry entry = new ZipEntry(item.getKey());
|
||||||
zip.putNextEntry(entry); zip.write(item.getValue().data()); zip.closeEntry();
|
entry.setTime(0);
|
||||||
|
zip.putNextEntry(entry);
|
||||||
|
zip.write(item.getValue().data());
|
||||||
|
zip.closeEntry();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
String hash = hash(temp, "SHA-1");
|
String hash = hash(temp, "SHA-1");
|
||||||
Path destination = output.resolve(hash + ".zip");
|
Path destination = output.resolve(hash + ".zip");
|
||||||
if (!Files.exists(destination)) Files.move(temp, destination, StandardCopyOption.ATOMIC_MOVE);
|
if (!Files.exists(destination))
|
||||||
|
Files.move(temp, destination, StandardCopyOption.ATOMIC_MOVE);
|
||||||
else if (!hash(destination, "SHA-1").equals(hash))
|
else if (!hash(destination, "SHA-1").equals(hash))
|
||||||
throw new IOException("Published ZIP was modified: " + destination);
|
throw new IOException("Published ZIP was modified: " + destination);
|
||||||
PackFiles.atomicWrite(output.resolve("current.json"), PackConfig.JSON.toJson(Map.of("sha1", hash, "files", assets.size())).getBytes(StandardCharsets.UTF_8));
|
PackFiles.atomicWrite(
|
||||||
|
output.resolve("current.json"),
|
||||||
|
PackConfig.JSON
|
||||||
|
.toJson(Map.of("sha1", hash, "files", assets.size()))
|
||||||
|
.getBytes(StandardCharsets.UTF_8));
|
||||||
return new Pack(destination, hash, assets.size(), Files.size(destination));
|
return new Pack(destination, hash, assets.size(), Files.size(destination));
|
||||||
} finally { Files.deleteIfExists(temp); }
|
} finally {
|
||||||
|
Files.deleteIfExists(temp);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public static Pack previous(Path root, PackConfig config) throws IOException {
|
public static Pack previous(Path root, PackConfig config) throws IOException {
|
||||||
Path output = config.storage(root).resolve("output");
|
Path output = config.storage(root).resolve("output");
|
||||||
try {
|
try {
|
||||||
JsonObject info = JsonParser.parseString(Files.readString(output.resolve("current.json"))).getAsJsonObject();
|
JsonObject info =
|
||||||
|
JsonParser.parseString(Files.readString(output.resolve("current.json")))
|
||||||
|
.getAsJsonObject();
|
||||||
String sha1 = info.get("sha1").getAsString();
|
String sha1 = info.get("sha1").getAsString();
|
||||||
if (!sha1.matches("[a-f0-9]{40}")) throw new IOException("Invalid pack hash");
|
if (!sha1.matches("[a-f0-9]{40}")) throw new IOException("Invalid pack hash");
|
||||||
Path path = output.resolve(sha1 + ".zip");
|
Path path = output.resolve(sha1 + ".zip");
|
||||||
if (!hash(path, "SHA-1").equals(sha1)) throw new IOException("Stored resource pack hash mismatch");
|
if (!hash(path, "SHA-1").equals(sha1))
|
||||||
|
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));
|
||||||
} catch (RuntimeException e) { throw new IOException("Invalid previous build", e); }
|
} catch (RuntimeException e) {
|
||||||
|
throw new IOException("Invalid previous build", e);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private void directory(Path root) throws IOException {
|
private void directory(Path root) throws IOException {
|
||||||
if (Files.isSymbolicLink(root)) throw new IOException("Symlink source: " + root);
|
if (Files.isSymbolicLink(root)) throw new IOException("Symlink source: " + root);
|
||||||
try (var walk = Files.walk(root)) {
|
try (var walk = Files.walk(root)) {
|
||||||
@@ -77,14 +129,20 @@ public final class PackBuilder {
|
|||||||
// A source is a pack root, or a directory of named pack roots.
|
// A source is a pack root, or a directory of named pack roots.
|
||||||
if (!isResource(name)) {
|
if (!isResource(name)) {
|
||||||
int slash = name.indexOf('/');
|
int slash = name.indexOf('/');
|
||||||
if (slash >= 0 && isResource(name.substring(slash + 1))) name = name.substring(slash + 1);
|
if (slash >= 0 && isResource(name.substring(slash + 1)))
|
||||||
else if (name.endsWith(".zip")) { archive(p, false); continue; }
|
name = name.substring(slash + 1);
|
||||||
else continue;
|
else if (name.endsWith(".zip")) {
|
||||||
|
archive(p, false);
|
||||||
|
continue;
|
||||||
|
} else continue;
|
||||||
}
|
}
|
||||||
try (var in = Files.newInputStream(p)) { add(name, in, p.toString()); }
|
try (var in = Files.newInputStream(p)) {
|
||||||
|
add(name, in, p.toString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private void archive(Path path, boolean mod) throws IOException {
|
private void archive(Path path, boolean mod) throws IOException {
|
||||||
try (var zip = new ZipFile(path.toFile())) {
|
try (var zip = new ZipFile(path.toFile())) {
|
||||||
String prefix = "";
|
String prefix = "";
|
||||||
@@ -92,7 +150,9 @@ public final class PackBuilder {
|
|||||||
var descriptor = zip.getEntry("astra-pack.properties");
|
var descriptor = zip.getEntry("astra-pack.properties");
|
||||||
if (descriptor == null) return;
|
if (descriptor == null) return;
|
||||||
Properties props = new Properties();
|
Properties props = new Properties();
|
||||||
try (var in = zip.getInputStream(descriptor)) { props.load(in); }
|
try (var in = zip.getInputStream(descriptor)) {
|
||||||
|
props.load(in);
|
||||||
|
}
|
||||||
String schema = props.getProperty("schema", "");
|
String schema = props.getProperty("schema", "");
|
||||||
if (schema.equals("2")) prefix = "astra-resourcepack/";
|
if (schema.equals("2")) prefix = "astra-resourcepack/";
|
||||||
else throw new IOException("Invalid AstraPacks bundle descriptor: " + path);
|
else throw new IOException("Invalid AstraPacks bundle descriptor: " + path);
|
||||||
@@ -102,42 +162,80 @@ public final class PackBuilder {
|
|||||||
if (entry.isDirectory() || !entry.getName().startsWith(prefix)) continue;
|
if (entry.isDirectory() || !entry.getName().startsWith(prefix)) continue;
|
||||||
String name = entry.getName().substring(prefix.length());
|
String name = entry.getName().substring(prefix.length());
|
||||||
if (!isResource(name)) continue;
|
if (!isResource(name)) continue;
|
||||||
try (var in = zip.getInputStream(entry)) { add(name, in, path + "!/" + entry.getName()); }
|
try (var in = zip.getInputStream(entry)) {
|
||||||
|
add(name, in, path + "!/" + entry.getName());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
private static boolean isResource(String name) { return name.startsWith("assets/") || name.equals("pack.png"); }
|
}
|
||||||
|
|
||||||
|
private static boolean isResource(String name) {
|
||||||
|
return name.startsWith("assets/") || name.equals("pack.png");
|
||||||
|
}
|
||||||
|
|
||||||
private void add(String name, InputStream in, String owner) throws IOException {
|
private void add(String name, InputStream in, String owner) throws IOException {
|
||||||
PackFiles.safe(Path.of("."), name);
|
PackFiles.safe(Path.of("."), name);
|
||||||
int limit = config.build.maxFileMiB * 1024 * 1024;
|
int limit = config.build.maxFileMiB * 1024 * 1024;
|
||||||
byte[] bytes = in.readNBytes(limit + 1);
|
byte[] bytes = in.readNBytes(limit + 1);
|
||||||
if (bytes.length > limit) throw new IOException("Resource exceeds maxFileMiB: " + owner);
|
if (bytes.length > limit) throw new IOException("Resource exceeds maxFileMiB: " + owner);
|
||||||
total += bytes.length;
|
total += bytes.length;
|
||||||
if (total > config.build.maxTotalMiB * 1024L * 1024L) throw new IOException("Sources exceed maxTotalMiB");
|
if (total > config.build.maxTotalMiB * 1024L * 1024L)
|
||||||
|
throw new IOException("Sources exceed maxTotalMiB");
|
||||||
Asset old = assets.get(name);
|
Asset old = assets.get(name);
|
||||||
if (old != null && !Arrays.equals(bytes, old.data()) && config.build.conflictPolicy.equals("error"))
|
if (old != null
|
||||||
throw new IOException("Conflicting resource " + name + " from " + old.owner() + " and " + owner);
|
&& !Arrays.equals(bytes, old.data())
|
||||||
|
&& config.build.conflictPolicy.equals("error"))
|
||||||
|
throw new IOException(
|
||||||
|
"Conflicting resource " + name + " from " + old.owner() + " and " + owner);
|
||||||
assets.put(name, new Asset(bytes, owner));
|
assets.put(name, new Asset(bytes, owner));
|
||||||
if (assets.size() > config.build.maxFiles) throw new IOException("Too many resources");
|
if (assets.size() > config.build.maxFiles) throw new IOException("Too many resources");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String hash(Path file, String algorithm) throws IOException {
|
public static String hash(Path file, String algorithm) throws IOException {
|
||||||
try {
|
try {
|
||||||
MessageDigest digest = MessageDigest.getInstance(algorithm);
|
MessageDigest digest = MessageDigest.getInstance(algorithm);
|
||||||
try (var in = new DigestInputStream(Files.newInputStream(file), digest)) { in.transferTo(OutputStream.nullOutputStream()); }
|
try (var in = new DigestInputStream(Files.newInputStream(file), digest)) {
|
||||||
return HexFormat.of().formatHex(digest.digest());
|
in.transferTo(OutputStream.nullOutputStream());
|
||||||
} catch (NoSuchAlgorithmException e) { throw new AssertionError(e); }
|
|
||||||
}
|
}
|
||||||
|
return HexFormat.of().formatHex(digest.digest());
|
||||||
|
} catch (NoSuchAlgorithmException e) {
|
||||||
|
throw new AssertionError(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
static void verifyExternal(PackConfig config, PackBuilder.Pack pack) throws IOException {
|
static void verifyExternal(PackConfig config, PackBuilder.Pack pack) throws IOException {
|
||||||
if (!config.hosting.mode.equals("no_host") || !config.delivery.sendOnJoin) return;
|
if (!config.hosting.mode.equals("no_host") || !config.delivery.sendOnJoin) return;
|
||||||
Path tmp = Files.createTempFile(pack.path().getParent(), "external-", ".tmp");
|
try (HttpClient client =
|
||||||
try (HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).followRedirects(HttpClient.Redirect.NORMAL).build()) {
|
HttpClient.newBuilder()
|
||||||
HttpRequest request = HttpRequest.newBuilder(PackConfig.validateUrl(config.hosting.externalUrl)).timeout(Duration.ofSeconds(30)).GET().build();
|
.connectTimeout(Duration.ofSeconds(10))
|
||||||
|
.followRedirects(HttpClient.Redirect.NORMAL)
|
||||||
|
.build()) {
|
||||||
|
HttpRequest request =
|
||||||
|
HttpRequest.newBuilder(PackConfig.validateUrl(config.hosting.externalUrl))
|
||||||
|
.timeout(Duration.ofSeconds(30))
|
||||||
|
.GET()
|
||||||
|
.build();
|
||||||
// A bounded subscriber prevents an external host from consuming arbitrary memory/disk.
|
// A bounded subscriber prevents an external host from consuming arbitrary memory/disk.
|
||||||
HttpResponse<byte[]> response = client.send(request, info -> HttpResponse.BodySubscribers.limiting(HttpResponse.BodySubscribers.ofByteArray(), pack.bytes() + 1));
|
HttpResponse<byte[]> response =
|
||||||
if (response.statusCode() != 200) throw new IOException("External pack HTTP " + response.statusCode());
|
client.send(
|
||||||
Files.write(tmp, response.body());
|
request,
|
||||||
if (!PackBuilder.hash(tmp, "SHA-1").equals(pack.sha1())) throw new IOException("External ZIP differs from built ZIP. Upload " + pack.path() + ", then /astrapacks publish");
|
HttpResponse.BodyHandlers.limiting(
|
||||||
} catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); }
|
HttpResponse.BodyHandlers.ofByteArray(), pack.bytes()));
|
||||||
finally { Files.deleteIfExists(tmp); }
|
if (response.statusCode() != 200)
|
||||||
|
throw new IOException("External pack HTTP " + response.statusCode());
|
||||||
|
String hash =
|
||||||
|
HexFormat.of()
|
||||||
|
.formatHex(MessageDigest.getInstance("SHA-1").digest(response.body()));
|
||||||
|
if (!hash.equals(pack.sha1()))
|
||||||
|
throw new IOException(
|
||||||
|
"External ZIP differs from built ZIP. Upload "
|
||||||
|
+ pack.path()
|
||||||
|
+ ", then /astrapacks publish");
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
throw new IOException(e);
|
||||||
|
} catch (NoSuchAlgorithmException e) {
|
||||||
|
throw new AssertionError(e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,20 +2,27 @@ package online.astradev.packs;
|
|||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.nio.file.*;
|
import java.nio.file.Files;
|
||||||
import java.util.*;
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
/** Server-local configuration, deliberately never synchronized to clients. */
|
/** Server-local configuration, deliberately never synchronized to clients. */
|
||||||
public final class PackConfig {
|
public final class PackConfig {
|
||||||
public static final Gson JSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
|
public static final Gson JSON =
|
||||||
|
new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
|
||||||
public boolean enabled = true;
|
public boolean enabled = true;
|
||||||
public Build build = new Build();
|
public Build build = new Build();
|
||||||
public Hosting hosting = new Hosting();
|
public Hosting hosting = new Hosting();
|
||||||
public Delivery delivery = new Delivery();
|
public Delivery delivery = new Delivery();
|
||||||
public Messages messages = new Messages();
|
public Messages messages = new Messages();
|
||||||
|
|
||||||
public static final class Build {
|
public static final class Build {
|
||||||
public String storageDirectory = "astrapacks";
|
public String storageDirectory = "astrapacks";
|
||||||
public List<String> sources = new ArrayList<>(List.of("astrapacks/contents"));
|
public List<String> sources = new ArrayList<>(List.of("astrapacks/contents"));
|
||||||
@@ -28,6 +35,7 @@ public final class PackConfig {
|
|||||||
public int maxTotalMiB = 256;
|
public int maxTotalMiB = 256;
|
||||||
public int maxFiles = 50000;
|
public int maxFiles = 50000;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static final class Hosting {
|
public static final class Hosting {
|
||||||
public String mode = "simple_self_host";
|
public String mode = "simple_self_host";
|
||||||
public String publicAddress = "auto";
|
public String publicAddress = "auto";
|
||||||
@@ -39,7 +47,21 @@ public final class PackConfig {
|
|||||||
public int maxConcurrentDownloads = 32;
|
public int maxConcurrentDownloads = 32;
|
||||||
public int maxSpeedMiBPerSecond = 30;
|
public int maxSpeedMiBPerSecond = 30;
|
||||||
public int tokenLifetimeSeconds = 600;
|
public int tokenLifetimeSeconds = 600;
|
||||||
|
|
||||||
|
public boolean sameSettings(Hosting other) {
|
||||||
|
return mode.equals(other.mode)
|
||||||
|
&& publicAddress.equals(other.publicAddress)
|
||||||
|
&& bindAddress.equals(other.bindAddress)
|
||||||
|
&& port == other.port
|
||||||
|
&& externalUrl.equals(other.externalUrl)
|
||||||
|
&& blockNonGameRequests == other.blockNonGameRequests
|
||||||
|
&& maxDownloadsPerIp == other.maxDownloadsPerIp
|
||||||
|
&& maxConcurrentDownloads == other.maxConcurrentDownloads
|
||||||
|
&& maxSpeedMiBPerSecond == other.maxSpeedMiBPerSecond
|
||||||
|
&& tokenLifetimeSeconds == other.tokenLifetimeSeconds;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public static final class Delivery {
|
public static final class Delivery {
|
||||||
public boolean sendOnJoin = true;
|
public boolean sendOnJoin = true;
|
||||||
public boolean required = true;
|
public boolean required = true;
|
||||||
@@ -48,17 +70,29 @@ public final class PackConfig {
|
|||||||
public int retries = 1;
|
public int retries = 1;
|
||||||
public boolean logStatus = true;
|
public boolean logStatus = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static final class Messages {
|
public static final class Messages {
|
||||||
public String prompt = "&6Привет, {player}!\\n&fДля игры на сервере необходим ресурспак AstraDev.\\n&aНажми «Продолжить», чтобы загрузить его.";
|
public String prompt =
|
||||||
public String declined = "&cДля входа необходимо принять ресурспак сервера.\\n&fВ настройках этого сервера включи «Наборы ресурсов сервера» и подключись снова.";
|
"&6Привет, {player}!\\n"
|
||||||
public String failed = "&cНе удалось загрузить ресурспак сервера.\\n&fПопробуй подключиться ещё раз. Если ошибка повторится, сообщи администрации.";
|
+ "&fДля игры на сервере необходим ресурспак AstraDev.\\n"
|
||||||
|
+ "&aНажми «Продолжить», чтобы загрузить его.";
|
||||||
|
public String declined =
|
||||||
|
"&cДля входа необходимо принять ресурспак сервера.\\n"
|
||||||
|
+ "&fВ настройках этого сервера включи «Наборы ресурсов сервера» и подключись"
|
||||||
|
+ " снова.";
|
||||||
|
public String failed =
|
||||||
|
"&cНе удалось загрузить ресурспак сервера.\\n"
|
||||||
|
+ "&fПопробуй подключиться ещё раз. Если ошибка повторится, сообщи"
|
||||||
|
+ " администрации.";
|
||||||
public String timeout = "&cВремя ожидания ресурспака истекло. Попробуй подключиться снова.";
|
public String timeout = "&cВремя ожидания ресурспака истекло. Попробуй подключиться снова.";
|
||||||
public String unavailable = "&cРесурспак сервера пока недоступен. Попробуй зайти позже.";
|
public String unavailable = "&cРесурспак сервера пока недоступен. Попробуй зайти позже.";
|
||||||
public String loaded = "&aРесурспак AstraDev загружен.";
|
public String loaded = "&aРесурспак AstraDev загружен.";
|
||||||
}
|
}
|
||||||
|
|
||||||
public static PackConfig load(Path path) throws IOException {
|
public static PackConfig load(Path path) throws IOException {
|
||||||
if (!Files.exists(path)) {
|
if (!Files.exists(path)) {
|
||||||
PackFiles.atomicWrite(path, (JSON.toJson(new PackConfig()) + "\n").getBytes(StandardCharsets.UTF_8));
|
PackFiles.atomicWrite(
|
||||||
|
path, (JSON.toJson(new PackConfig()) + "\n").getBytes(StandardCharsets.UTF_8));
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
PackConfig config = JSON.fromJson(Files.readString(path), PackConfig.class);
|
PackConfig config = JSON.fromJson(Files.readString(path), PackConfig.class);
|
||||||
@@ -69,14 +103,22 @@ public final class PackConfig {
|
|||||||
throw new IOException("Invalid " + path + ": " + e.getMessage(), e);
|
throw new IOException("Invalid " + path + ": " + e.getMessage(), e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void validate() {
|
public void validate() {
|
||||||
Objects.requireNonNull(build); Objects.requireNonNull(hosting);
|
Objects.requireNonNull(build);
|
||||||
Objects.requireNonNull(delivery); Objects.requireNonNull(messages);
|
Objects.requireNonNull(hosting);
|
||||||
|
Objects.requireNonNull(delivery);
|
||||||
|
Objects.requireNonNull(messages);
|
||||||
|
Objects.requireNonNull(hosting.bindAddress, "hosting.bindAddress");
|
||||||
|
Objects.requireNonNull(hosting.externalUrl, "hosting.externalUrl");
|
||||||
if (!Set.of("simple_self_host", "self_host", "no_host").contains(hosting.mode))
|
if (!Set.of("simple_self_host", "self_host", "no_host").contains(hosting.mode))
|
||||||
throw new IllegalArgumentException("hosting.mode: simple_self_host, self_host or no_host");
|
throw new IllegalArgumentException(
|
||||||
|
"hosting.mode: simple_self_host, self_host or no_host");
|
||||||
if (!Set.of("error", "last_wins").contains(build.conflictPolicy))
|
if (!Set.of("error", "last_wins").contains(build.conflictPolicy))
|
||||||
throw new IllegalArgumentException("build.conflictPolicy: error or last_wins");
|
throw new IllegalArgumentException("build.conflictPolicy: error or last_wins");
|
||||||
if (build.storageDirectory.isBlank() || build.sources == null || build.sources.stream().anyMatch(s -> s == null || s.isBlank()))
|
if (build.storageDirectory.isBlank()
|
||||||
|
|| build.sources == null
|
||||||
|
|| build.sources.stream().anyMatch(s -> s == null || s.isBlank()))
|
||||||
throw new IllegalArgumentException("Invalid build paths");
|
throw new IllegalArgumentException("Invalid build paths");
|
||||||
Objects.requireNonNull(build.description);
|
Objects.requireNonNull(build.description);
|
||||||
range(build.maxFileMiB, 1, 128, "maxFileMiB");
|
range(build.maxFileMiB, 1, 128, "maxFileMiB");
|
||||||
@@ -91,23 +133,43 @@ public final class PackConfig {
|
|||||||
range(delivery.retries, 0, 5, "retries");
|
range(delivery.retries, 0, 5, "retries");
|
||||||
if (enabled && delivery.required && !delivery.sendOnJoin)
|
if (enabled && delivery.required && !delivery.sendOnJoin)
|
||||||
throw new IllegalArgumentException("required needs sendOnJoin=true");
|
throw new IllegalArgumentException("required needs sendOnJoin=true");
|
||||||
if (!hosting.publicAddress.equals("auto") && validateUrl(hosting.publicAddress).getQuery() != null)
|
if (!hosting.publicAddress.equals("auto")
|
||||||
throw new IllegalArgumentException("hosting.publicAddress must not contain query parameters");
|
&& validateUrl(hosting.publicAddress).getQuery() != null)
|
||||||
if (!hosting.mode.equals("no_host") && hosting.tokenLifetimeSeconds < delivery.timeoutSeconds)
|
throw new IllegalArgumentException(
|
||||||
|
"hosting.publicAddress must not contain query parameters");
|
||||||
|
if (!hosting.mode.equals("no_host")
|
||||||
|
&& hosting.tokenLifetimeSeconds < delivery.timeoutSeconds)
|
||||||
throw new IllegalArgumentException("tokenLifetimeSeconds must be >= timeoutSeconds");
|
throw new IllegalArgumentException("tokenLifetimeSeconds must be >= timeoutSeconds");
|
||||||
if (hosting.mode.equals("no_host") && enabled && delivery.sendOnJoin) validateUrl(hosting.externalUrl);
|
if (hosting.mode.equals("no_host") && enabled && delivery.sendOnJoin)
|
||||||
for (String s : List.of(messages.prompt, messages.declined, messages.failed, messages.timeout, messages.unavailable, messages.loaded))
|
validateUrl(hosting.externalUrl);
|
||||||
if (s.length() > 8192) throw new IllegalArgumentException("Message exceeds 8192 characters");
|
for (String s :
|
||||||
|
List.of(
|
||||||
|
messages.prompt,
|
||||||
|
messages.declined,
|
||||||
|
messages.failed,
|
||||||
|
messages.timeout,
|
||||||
|
messages.unavailable,
|
||||||
|
messages.loaded))
|
||||||
|
if (s.length() > 8192)
|
||||||
|
throw new IllegalArgumentException("Message exceeds 8192 characters");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static URI validateUrl(String value) {
|
public static URI validateUrl(String value) {
|
||||||
URI uri = URI.create(value);
|
URI uri = URI.create(value);
|
||||||
if (!("http".equals(uri.getScheme()) || "https".equals(uri.getScheme())) || uri.getHost() == null
|
if (!("http".equals(uri.getScheme()) || "https".equals(uri.getScheme()))
|
||||||
|| uri.getUserInfo() != null || uri.getFragment() != null)
|
|| uri.getHost() == null
|
||||||
|
|| uri.getUserInfo() != null
|
||||||
|
|| uri.getFragment() != null)
|
||||||
throw new IllegalArgumentException("Expected a direct http(s) URL: " + value);
|
throw new IllegalArgumentException("Expected a direct http(s) URL: " + value);
|
||||||
return uri;
|
return uri;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void range(int n, int min, int max, String key) {
|
private static void range(int n, int min, int max, String key) {
|
||||||
if (n < min || n > max) throw new IllegalArgumentException(key + " must be " + min + ".." + max);
|
if (n < min || n > max)
|
||||||
|
throw new IllegalArgumentException(key + " must be " + min + ".." + max);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Path storage(Path root) {
|
||||||
|
return root.resolve(build.storageDirectory).toAbsolutePath().normalize();
|
||||||
}
|
}
|
||||||
public Path storage(Path root) { return root.resolve(build.storageDirectory).toAbsolutePath().normalize(); }
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,29 +1,49 @@
|
|||||||
package online.astradev.packs;
|
package online.astradev.packs;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.file.*;
|
import java.nio.file.AtomicMoveNotSupportedException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.StandardCopyOption;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
|
|
||||||
final class PackFiles {
|
final class PackFiles {
|
||||||
private PackFiles() {}
|
private PackFiles() {}
|
||||||
|
|
||||||
static Path safe(Path root, String name) throws IOException {
|
static Path safe(Path root, String name) throws IOException {
|
||||||
if (name.isBlank() || name.contains("\\") || name.contains(":") || name.startsWith("/")
|
if (name.isBlank()
|
||||||
|| Arrays.stream(name.split("/", -1)).anyMatch(p -> p.isEmpty() || p.equals(".") || p.equals("..")))
|
|| name.contains("\\")
|
||||||
|
|| name.contains(":")
|
||||||
|
|| name.startsWith("/")
|
||||||
|
|| Arrays.stream(name.split("/", -1))
|
||||||
|
.anyMatch(p -> p.isEmpty() || p.equals(".") || p.equals("..")))
|
||||||
throw new IOException("Unsafe resource path: " + name);
|
throw new IOException("Unsafe resource path: " + name);
|
||||||
root = root.toAbsolutePath().normalize();
|
root = root.toAbsolutePath().normalize();
|
||||||
Path target = root.resolve(name).normalize();
|
Path target = root.resolve(name).normalize();
|
||||||
if (!target.startsWith(root)) throw new IOException("Resource escapes content root: " + name);
|
if (!target.startsWith(root))
|
||||||
|
throw new IOException("Resource escapes content root: " + name);
|
||||||
for (Path part = target; part != null; part = part.getParent())
|
for (Path part = target; part != null; part = part.getParent())
|
||||||
if (Files.isSymbolicLink(part)) throw new IOException("Symbolic links are not supported: " + part);
|
if (Files.isSymbolicLink(part))
|
||||||
|
throw new IOException("Symbolic links are not supported: " + part);
|
||||||
return target;
|
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 temp = Files.createTempFile(target.getParent(), ".astra-", ".tmp");
|
Path temp = Files.createTempFile(target.getParent(), ".astra-", ".tmp");
|
||||||
try {
|
try {
|
||||||
Files.write(temp, bytes);
|
Files.write(temp, bytes);
|
||||||
try { Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); }
|
try {
|
||||||
catch (AtomicMoveNotSupportedException e) { Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING); }
|
Files.move(
|
||||||
} finally { Files.deleteIfExists(temp); }
|
temp,
|
||||||
|
target,
|
||||||
|
StandardCopyOption.ATOMIC_MOVE,
|
||||||
|
StandardCopyOption.REPLACE_EXISTING);
|
||||||
|
} catch (AtomicMoveNotSupportedException e) {
|
||||||
|
Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
Files.deleteIfExists(temp);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,26 +2,55 @@ package online.astradev.packs;
|
|||||||
|
|
||||||
import io.netty.bootstrap.ServerBootstrap;
|
import io.netty.bootstrap.ServerBootstrap;
|
||||||
import io.netty.buffer.ByteBuf;
|
import io.netty.buffer.ByteBuf;
|
||||||
import io.netty.channel.*;
|
import io.netty.channel.Channel;
|
||||||
import io.netty.channel.nio.NioEventLoopGroup;
|
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.SocketChannel;
|
||||||
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
||||||
import io.netty.handler.codec.ByteToMessageDecoder;
|
import io.netty.handler.codec.ByteToMessageDecoder;
|
||||||
import io.netty.handler.codec.http.*;
|
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.ChunkedNioFile;
|
||||||
import io.netty.handler.stream.ChunkedWriteHandler;
|
import io.netty.handler.stream.ChunkedWriteHandler;
|
||||||
import io.netty.handler.timeout.ReadTimeoutHandler;
|
import io.netty.handler.timeout.ReadTimeoutHandler;
|
||||||
import io.netty.handler.traffic.ChannelTrafficShapingHandler;
|
import io.netty.handler.traffic.ChannelTrafficShapingHandler;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.*;
|
import java.net.InetSocketAddress;
|
||||||
import java.nio.file.*;
|
import java.nio.file.Files;
|
||||||
import java.util.*;
|
import java.nio.file.Path;
|
||||||
import java.util.concurrent.*;
|
import java.util.ArrayList;
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
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;
|
||||||
|
|
||||||
/** Only immutable pack artifacts are exposed; no directory or arbitrary file routes. */
|
/** Only immutable pack artifacts are exposed; no directory or arbitrary file routes. */
|
||||||
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 ConcurrentMap<String, Grant> grants = new ConcurrentHashMap<>();
|
||||||
private final ConcurrentMap<String, Path> published = new ConcurrentHashMap<>();
|
private final ConcurrentMap<String, Path> published = new ConcurrentHashMap<>();
|
||||||
@@ -29,43 +58,80 @@ public final class PackHost implements AutoCloseable {
|
|||||||
private int active;
|
private int active;
|
||||||
private EventLoopGroup group;
|
private EventLoopGroup group;
|
||||||
private Channel listening;
|
private Channel listening;
|
||||||
public PackHost(PackConfig.Hosting config) { this.config = config; }
|
|
||||||
public void publish(PackBuilder.Pack pack) { published.put(pack.sha1(), pack.path()); }
|
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) {
|
public String issuePath(PackBuilder.Pack pack) {
|
||||||
String path = "/astrapacks/" + pack.sha1() + ".zip";
|
String path = "/astrapacks/" + pack.sha1() + ".zip";
|
||||||
if (!config.blockNonGameRequests) return path;
|
if (!config.blockNonGameRequests) return path;
|
||||||
long now = System.currentTimeMillis();
|
long now = System.currentTimeMillis();
|
||||||
grants.entrySet().removeIf(e -> e.getValue().expires() < now);
|
grants.entrySet().removeIf(e -> e.getValue().expires() < now);
|
||||||
if (grants.size() >= 10000) throw new IllegalStateException("Too many resource-pack download grants");
|
if (grants.size() >= 10000)
|
||||||
|
throw new IllegalStateException("Too many resource-pack download grants");
|
||||||
String token = UUID.randomUUID().toString();
|
String token = UUID.randomUUID().toString();
|
||||||
grants.put(token, new Grant(pack.sha1(), now + config.tokenLifetimeSeconds * 1000L));
|
grants.put(token, new Grant(pack.sha1(), now + config.tokenLifetimeSeconds * 1000L));
|
||||||
return path + "?token=" + token;
|
return path + "?token=" + token;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void start() throws InterruptedException {
|
public void start() throws InterruptedException {
|
||||||
if (!config.mode.equals("self_host")) return;
|
if (!config.mode.equals("self_host")) return;
|
||||||
group = new NioEventLoopGroup(2);
|
group = new MultiThreadIoEventLoopGroup(2, NioIoHandler.newFactory());
|
||||||
try {
|
try {
|
||||||
listening = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class)
|
listening =
|
||||||
.childHandler(new ChannelInitializer<SocketChannel>() {
|
new ServerBootstrap()
|
||||||
@Override protected void initChannel(SocketChannel ch) { installHttp(ch.pipeline()); }
|
.group(group)
|
||||||
}).bind(config.bindAddress, config.port).sync().channel();
|
.channel(NioServerSocketChannel.class)
|
||||||
} catch (Throwable e) { close(); throw e; }
|
.childHandler(
|
||||||
|
new ChannelInitializer<SocketChannel>() {
|
||||||
|
@Override
|
||||||
|
protected void initChannel(SocketChannel ch) {
|
||||||
|
installHttp(ch.pipeline());
|
||||||
}
|
}
|
||||||
public void installSniffer(ChannelPipeline pipeline) { pipeline.addFirst("astrapacks_detect", new Sniffer()); }
|
})
|
||||||
|
.bind(config.bindAddress, config.port)
|
||||||
|
.sync()
|
||||||
|
.channel();
|
||||||
|
} catch (InterruptedException | RuntimeException e) {
|
||||||
|
close();
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void installSniffer(ChannelPipeline pipeline) {
|
||||||
|
pipeline.addFirst("astrapacks_detect", new Sniffer());
|
||||||
|
}
|
||||||
|
|
||||||
private void installHttp(ChannelPipeline p) {
|
private void installHttp(ChannelPipeline p) {
|
||||||
p.addLast("astrapacks_timeout", new ReadTimeoutHandler(30));
|
p.addLast("astrapacks_timeout", new ReadTimeoutHandler(30));
|
||||||
p.addLast("astrapacks_http", new HttpServerCodec(4096, 8192, 8192));
|
p.addLast("astrapacks_http", new HttpServerCodec(4096, 8192, 8192));
|
||||||
p.addLast("astrapacks_aggregate", new HttpObjectAggregator(4096));
|
p.addLast("astrapacks_aggregate", new HttpObjectAggregator(4096));
|
||||||
p.addLast("astrapacks_speed", new ChannelTrafficShapingHandler(config.maxSpeedMiBPerSecond * 1024L * 1024L, 0));
|
p.addLast(
|
||||||
|
"astrapacks_speed",
|
||||||
|
new ChannelTrafficShapingHandler(config.maxSpeedMiBPerSecond * 1024L * 1024L, 0));
|
||||||
p.addLast("astrapacks_chunks", new ChunkedWriteHandler());
|
p.addLast("astrapacks_chunks", new ChunkedWriteHandler());
|
||||||
p.addLast("astrapacks_download", new Download());
|
p.addLast("astrapacks_download", new Download());
|
||||||
}
|
}
|
||||||
|
|
||||||
private final class Sniffer extends ByteToMessageDecoder {
|
private final class Sniffer extends ByteToMessageDecoder {
|
||||||
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
|
@Override
|
||||||
|
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
|
||||||
if (in.readableBytes() < 4) return;
|
if (in.readableBytes() < 4) return;
|
||||||
int start = in.readerIndex();
|
int start = in.readerIndex();
|
||||||
boolean http = (in.getByte(start) == 'G' && in.getByte(start + 1) == 'E' && in.getByte(start + 2) == 'T' && in.getByte(start + 3) == ' ')
|
boolean http =
|
||||||
|| (in.getByte(start) == 'H' && in.getByte(start + 1) == 'E' && in.getByte(start + 2) == 'A' && in.getByte(start + 3) == 'D');
|
(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) {
|
if (http) {
|
||||||
ChannelPipeline p = ctx.pipeline();
|
ChannelPipeline p = ctx.pipeline();
|
||||||
for (String name : new ArrayList<>(p.names()))
|
for (String name : new ArrayList<>(p.names()))
|
||||||
@@ -76,69 +142,116 @@ public final class PackHost implements AutoCloseable {
|
|||||||
ctx.pipeline().remove(this);
|
ctx.pipeline().remove(this);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private synchronized boolean acquire(String ip) {
|
private synchronized boolean acquire(String ip) {
|
||||||
int count = downloads.getOrDefault(ip, 0);
|
int count = downloads.getOrDefault(ip, 0);
|
||||||
if (count >= config.maxDownloadsPerIp || active >= config.maxConcurrentDownloads) return false;
|
if (count >= config.maxDownloadsPerIp || active >= config.maxConcurrentDownloads)
|
||||||
downloads.put(ip, count + 1); active++; return true;
|
return false;
|
||||||
|
downloads.put(ip, count + 1);
|
||||||
|
active++;
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private synchronized void release(String ip) {
|
private synchronized void release(String ip) {
|
||||||
downloads.computeIfPresent(ip, (key, count) -> count <= 1 ? null : count - 1); active--;
|
downloads.computeIfPresent(ip, (key, count) -> count <= 1 ? null : count - 1);
|
||||||
|
active--;
|
||||||
}
|
}
|
||||||
|
|
||||||
private final class Download extends SimpleChannelInboundHandler<FullHttpRequest> {
|
private final class Download extends SimpleChannelInboundHandler<FullHttpRequest> {
|
||||||
private boolean handled;
|
private boolean handled;
|
||||||
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws IOException {
|
|
||||||
|
@Override
|
||||||
|
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request)
|
||||||
|
throws IOException {
|
||||||
if (handled) return;
|
if (handled) return;
|
||||||
handled = true;
|
handled = true;
|
||||||
if (!request.decoderResult().isSuccess()) { error(ctx, HttpResponseStatus.BAD_REQUEST); return; }
|
if (!request.decoderResult().isSuccess()) {
|
||||||
if (!request.method().equals(HttpMethod.GET) && !request.method().equals(HttpMethod.HEAD)) {
|
error(ctx, HttpResponseStatus.BAD_REQUEST);
|
||||||
error(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED); return;
|
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());
|
QueryStringDecoder uri = new QueryStringDecoder(request.uri());
|
||||||
String path = uri.path();
|
String path = uri.path();
|
||||||
if (!path.matches("/astrapacks/[a-f0-9]{40}\\.zip")) { error(ctx, HttpResponseStatus.NOT_FOUND); return; }
|
if (!path.matches("/astrapacks/[a-f0-9]{40}\\.zip")) {
|
||||||
String hash = path.substring(12, 52);
|
error(ctx, HttpResponseStatus.NOT_FOUND);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String hash = path.substring("/astrapacks/".length(), path.length() - ".zip".length());
|
||||||
Path file = published.get(hash);
|
Path file = published.get(hash);
|
||||||
if (file == null || !Files.isRegularFile(file)) { error(ctx, HttpResponseStatus.NOT_FOUND); return; }
|
if (file == null || !Files.isRegularFile(file)) {
|
||||||
|
error(ctx, HttpResponseStatus.NOT_FOUND);
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (config.blockNonGameRequests) {
|
if (config.blockNonGameRequests) {
|
||||||
String token = uri.parameters().getOrDefault("token", List.of("")).getFirst();
|
String token = uri.parameters().getOrDefault("token", List.of("")).getFirst();
|
||||||
Grant grant = grants.get(token);
|
Grant grant = grants.get(token);
|
||||||
if (grant == null || grant.expires() < System.currentTimeMillis() || !grant.hash().equals(hash)) {
|
if (grant == null
|
||||||
error(ctx, HttpResponseStatus.FORBIDDEN); return;
|
|| grant.expires() < System.currentTimeMillis()
|
||||||
|
|| !grant.hash().equals(hash)) {
|
||||||
|
error(ctx, HttpResponseStatus.FORBIDDEN);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
String ip = ((InetSocketAddress)ctx.channel().remoteAddress()).getAddress().getHostAddress();
|
String ip =
|
||||||
if (!acquire(ip)) { error(ctx, HttpResponseStatus.TOO_MANY_REQUESTS); return; }
|
((InetSocketAddress) ctx.channel().remoteAddress())
|
||||||
AtomicBoolean released = new AtomicBoolean();
|
.getAddress()
|
||||||
Runnable cleanup = () -> { if (released.compareAndSet(false, true)) release(ip); };
|
.getHostAddress();
|
||||||
ctx.channel().closeFuture().addListener(f -> cleanup.run());
|
if (!acquire(ip)) {
|
||||||
|
error(ctx, HttpResponseStatus.TOO_MANY_REQUESTS);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Every response closes its connection; release the slot exactly once there.
|
||||||
|
ctx.channel().closeFuture().addListener(f -> release(ip));
|
||||||
ChunkedNioFile stream = null;
|
ChunkedNioFile stream = null;
|
||||||
try {
|
try {
|
||||||
long size = Files.size(file);
|
long size = Files.size(file);
|
||||||
if (request.method().equals(HttpMethod.GET)) stream = new ChunkedNioFile(file.toFile(), 65536);
|
if (request.method().equals(HttpMethod.GET))
|
||||||
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
|
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_TYPE, "application/zip");
|
||||||
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, size);
|
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, size);
|
||||||
response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
|
response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
|
||||||
response.headers().set(HttpHeaderNames.CACHE_CONTROL, "private, max-age=31536000, immutable");
|
response.headers()
|
||||||
|
.set(HttpHeaderNames.CACHE_CONTROL, "private, max-age=31536000, immutable");
|
||||||
response.headers().set(HttpHeaderNames.ETAG, '"' + hash + '"');
|
response.headers().set(HttpHeaderNames.ETAG, '"' + hash + '"');
|
||||||
ctx.write(response);
|
ctx.write(response);
|
||||||
if (stream != null) ctx.write(new HttpChunkedInput(stream));
|
if (stream != null) ctx.write(new HttpChunkedInput(stream));
|
||||||
else ctx.write(LastHttpContent.EMPTY_LAST_CONTENT);
|
else ctx.write(LastHttpContent.EMPTY_LAST_CONTENT);
|
||||||
ctx.writeAndFlush(io.netty.buffer.Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
|
ctx.writeAndFlush(io.netty.buffer.Unpooled.EMPTY_BUFFER)
|
||||||
} catch (Throwable e) {
|
.addListener(ChannelFutureListener.CLOSE);
|
||||||
if (stream != null) try { stream.close(); } catch (Exception ignored) { }
|
} catch (Exception e) {
|
||||||
cleanup.run(); ctx.close();
|
if (stream != null) {
|
||||||
|
try {
|
||||||
|
stream.close();
|
||||||
|
} catch (Exception closeError) {
|
||||||
|
e.addSuppressed(closeError);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { ctx.close(); }
|
ctx.close();
|
||||||
|
throw e;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
|
||||||
|
ctx.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static void error(ChannelHandlerContext ctx, HttpResponseStatus status) {
|
private static void error(ChannelHandlerContext ctx, HttpResponseStatus status) {
|
||||||
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
|
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
|
||||||
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);
|
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);
|
||||||
response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
|
response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
|
||||||
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
|
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
|
||||||
}
|
}
|
||||||
@Override public void close() {
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
if (listening != null) listening.close().awaitUninterruptibly();
|
if (listening != null) listening.close().awaitUninterruptibly();
|
||||||
if (group != null) group.shutdownGracefully(0, 2, TimeUnit.SECONDS).awaitUninterruptibly();
|
if (group != null) group.shutdownGracefully(0, 2, TimeUnit.SECONDS).awaitUninterruptibly();
|
||||||
grants.clear();
|
grants.clear();
|
||||||
|
|||||||
@@ -1,19 +1,25 @@
|
|||||||
package online.astradev.packs;
|
package online.astradev.packs;
|
||||||
|
|
||||||
import java.io.*;
|
|
||||||
import java.net.*;
|
|
||||||
import java.nio.file.*;
|
|
||||||
import java.util.*;
|
|
||||||
import java.util.concurrent.*;
|
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
|
||||||
import net.minecraft.commands.CommandSourceStack;
|
import net.minecraft.commands.CommandSourceStack;
|
||||||
import net.minecraft.network.Connection;
|
import net.minecraft.network.Connection;
|
||||||
import net.minecraft.network.chat.Component;
|
import net.minecraft.network.chat.Component;
|
||||||
import net.minecraft.network.protocol.common.ServerboundResourcePackPacket;
|
import net.minecraft.network.protocol.common.ServerboundResourcePackPacket;
|
||||||
import net.minecraft.server.MinecraftServer;
|
import net.minecraft.server.MinecraftServer;
|
||||||
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
|
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
|
||||||
|
|
||||||
import online.astradev.packs.mixin.CommonAccessor;
|
import online.astradev.packs.mixin.CommonAccessor;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.URISyntaxException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
|
||||||
public final class PackRuntime implements AutoCloseable {
|
public final class PackRuntime implements AutoCloseable {
|
||||||
public static volatile PackRuntime INSTANCE;
|
public static volatile PackRuntime INSTANCE;
|
||||||
private final MinecraftServer server;
|
private final MinecraftServer server;
|
||||||
@@ -22,113 +28,236 @@ public final class PackRuntime implements AutoCloseable {
|
|||||||
private volatile PackConfig config;
|
private volatile PackConfig config;
|
||||||
private volatile PackBuilder.Pack current;
|
private volatile PackBuilder.Pack current;
|
||||||
private final PackHost host;
|
private final PackHost host;
|
||||||
private final Map<ServerCommonPacketListenerImpl, PackSession> sessions = new ConcurrentHashMap<>();
|
private final Map<ServerCommonPacketListenerImpl, PackSession> sessions =
|
||||||
|
new ConcurrentHashMap<>();
|
||||||
private final Map<UUID, String> welcome = new ConcurrentHashMap<>();
|
private final Map<UUID, String> welcome = new ConcurrentHashMap<>();
|
||||||
private final ExecutorService worker = Executors.newSingleThreadExecutor(Thread.ofPlatform().daemon().name("AstraPacks-build").factory());
|
private final ExecutorService worker =
|
||||||
private final AtomicBoolean busy = new AtomicBoolean();
|
Executors.newSingleThreadExecutor(
|
||||||
|
Thread.ofPlatform().daemon().name("AstraPacks-build").factory());
|
||||||
|
// Read and written on the server thread, including build completion callbacks.
|
||||||
|
private boolean busy;
|
||||||
private volatile boolean closed;
|
private volatile boolean closed;
|
||||||
|
|
||||||
public PackRuntime(MinecraftServer server, Path root, Path configPath, PackConfig config) {
|
public PackRuntime(MinecraftServer server, Path root, Path configPath, PackConfig config) {
|
||||||
this.server = server; this.root = root; this.configPath = configPath; this.config = config;
|
this.server = server;
|
||||||
|
this.root = root;
|
||||||
|
this.configPath = configPath;
|
||||||
|
this.config = config;
|
||||||
this.host = new PackHost(config.hosting);
|
this.host = new PackHost(config.hosting);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void start() throws Exception {
|
public void start() throws Exception {
|
||||||
if (!config.enabled) return;
|
if (!config.enabled) return;
|
||||||
if (server.getServerResourcePack().isPresent())
|
if (server.getServerResourcePack().isPresent())
|
||||||
throw new IOException("AstraPacks must be the only pack sender: clear resource-pack in server.properties");
|
throw new IOException(
|
||||||
|
"AstraPacks must be the only pack sender: clear resource-pack in"
|
||||||
|
+ " server.properties");
|
||||||
// Only create the default source automatically. A typo in a custom path must fail visibly.
|
// Only create the default source automatically. A typo in a custom path must fail visibly.
|
||||||
Files.createDirectories(root.resolve("astrapacks/contents"));
|
Files.createDirectories(root.resolve("astrapacks/contents"));
|
||||||
PackBuilder.Pack candidate;
|
PackBuilder.Pack candidate;
|
||||||
try { candidate = config.build.onStartup ? new PackBuilder(config).build(root, "[88,0]") : PackBuilder.previous(root, config); }
|
try {
|
||||||
catch (IOException e) {
|
candidate =
|
||||||
|
config.build.onStartup
|
||||||
|
? new PackBuilder(config).build(root, "[88,0]")
|
||||||
|
: PackBuilder.previous(root, config);
|
||||||
|
} catch (IOException e) {
|
||||||
AstraPacks.LOG.error("Resource-pack build failed; trying the last successful build", e);
|
AstraPacks.LOG.error("Resource-pack build failed; trying the last successful build", e);
|
||||||
try { candidate = PackBuilder.previous(root, config); }
|
try {
|
||||||
catch (IOException absent) { AstraPacks.LOG.error("No usable pack. Required-pack logins will be refused.", absent); candidate = null; }
|
candidate = PackBuilder.previous(root, config);
|
||||||
|
} catch (IOException absent) {
|
||||||
|
AstraPacks.LOG.error(
|
||||||
|
"No usable pack. Required-pack logins will be refused.", absent);
|
||||||
|
candidate = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (candidate != null) {
|
if (candidate != null) {
|
||||||
try { PackBuilder.verifyExternal(config, candidate); current = candidate; host.publish(candidate); }
|
try {
|
||||||
catch (IOException e) { AstraPacks.LOG.error("External ZIP is not ready. Required-pack logins will be refused.", e); }
|
PackBuilder.verifyExternal(config, candidate);
|
||||||
|
current = candidate;
|
||||||
|
host.publish(candidate);
|
||||||
|
} catch (IOException e) {
|
||||||
|
AstraPacks.LOG.error(
|
||||||
|
"External ZIP is not ready. Required-pack logins will be refused.", e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
host.start();
|
host.start();
|
||||||
AstraPacks.LOG.info("AstraPacks: mode={}, required={}, pack={}", config.hosting.mode, config.delivery.required, current == null ? "UNAVAILABLE" : current.path());
|
AstraPacks.LOG.info(
|
||||||
|
"AstraPacks: mode={}, required={}, pack={}",
|
||||||
|
config.hosting.mode,
|
||||||
|
config.delivery.required,
|
||||||
|
current == null ? "UNAVAILABLE" : current.path());
|
||||||
}
|
}
|
||||||
public PackConfig config() { return config; }
|
|
||||||
public PackBuilder.Pack current() { return current; }
|
public PackConfig config() {
|
||||||
public PackHost host() { return host; }
|
return config;
|
||||||
|
}
|
||||||
|
|
||||||
|
public PackBuilder.Pack current() {
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
public PackHost host() {
|
||||||
|
return host;
|
||||||
|
}
|
||||||
|
|
||||||
public PackSession session(ServerCommonPacketListenerImpl listener) {
|
public PackSession session(ServerCommonPacketListenerImpl listener) {
|
||||||
PackSession session = new PackSession(this, listener);
|
PackSession session = new PackSession(this, listener);
|
||||||
PackSession old = sessions.put(listener, session);
|
PackSession old = sessions.put(listener, session);
|
||||||
if (old != null) old.replace();
|
if (old != null) old.replace();
|
||||||
return session;
|
return session;
|
||||||
}
|
}
|
||||||
public boolean intercept(ServerCommonPacketListenerImpl listener, ServerboundResourcePackPacket packet) {
|
|
||||||
|
public boolean intercept(
|
||||||
|
ServerCommonPacketListenerImpl listener, ServerboundResourcePackPacket packet) {
|
||||||
if (!config.enabled) return false;
|
if (!config.enabled) return false;
|
||||||
// Vanilla configuration handling finishes its own task for ANY terminal UUID.
|
// Vanilla configuration handling finishes its own task for ANY terminal UUID.
|
||||||
// Consume unrelated/stale replies too, so they cannot finish our gate or another task.
|
// Consume unrelated/stale replies too, so they cannot finish our gate or another task.
|
||||||
server.execute(() -> {
|
server.execute(
|
||||||
|
() -> {
|
||||||
PackSession session = sessions.get(listener);
|
PackSession session = sessions.get(listener);
|
||||||
if (session != null) session.response(packet);
|
if (session != null) session.response(packet);
|
||||||
});
|
});
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void tick() {
|
public void tick() {
|
||||||
sessions.entrySet().removeIf(entry -> {
|
sessions.entrySet()
|
||||||
if (!((CommonAccessor)entry.getKey()).astrapacks$connection().isConnected()) {
|
.removeIf(
|
||||||
|
entry -> {
|
||||||
|
if (!((CommonAccessor) entry.getKey())
|
||||||
|
.astrapacks$connection()
|
||||||
|
.isConnected()) {
|
||||||
welcome.remove(entry.getKey().getOwner().id());
|
welcome.remove(entry.getKey().getOwner().id());
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
entry.getValue().tick(); return false;
|
entry.getValue().tick();
|
||||||
|
return false;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public void loaded(ServerCommonPacketListenerImpl listener, String message) {
|
public void loaded(ServerCommonPacketListenerImpl listener, String message) {
|
||||||
if (listener instanceof net.minecraft.server.network.ServerGamePacketListenerImpl game) {
|
if (listener instanceof net.minecraft.server.network.ServerGamePacketListenerImpl game) {
|
||||||
if (!message.isBlank()) game.player.sendSystemMessage(PackText.of(message, listener.getOwner().name()));
|
if (!message.isBlank())
|
||||||
|
game.player.sendSystemMessage(PackText.of(message, listener.getOwner().name()));
|
||||||
} else welcome.put(listener.getOwner().id(), message);
|
} else welcome.put(listener.getOwner().id(), message);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void welcome(net.minecraft.server.level.ServerPlayer player) {
|
public void welcome(net.minecraft.server.level.ServerPlayer player) {
|
||||||
String text = welcome.remove(player.getUUID());
|
String text = welcome.remove(player.getUUID());
|
||||||
if (text != null && !text.isBlank()) player.sendSystemMessage(PackText.of(text, player.getGameProfile().name()));
|
if (text != null && !text.isBlank())
|
||||||
|
player.sendSystemMessage(PackText.of(text, player.getGameProfile().name()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public String url(ServerCommonPacketListenerImpl listener, PackBuilder.Pack pack) {
|
public String url(ServerCommonPacketListenerImpl listener, PackBuilder.Pack pack) {
|
||||||
if (config.hosting.mode.equals("no_host")) return config.hosting.externalUrl;
|
if (config.hosting.mode.equals("no_host")) return config.hosting.externalUrl;
|
||||||
Connection connection = ((CommonAccessor) listener).astrapacks$connection();
|
Connection connection = ((CommonAccessor) listener).astrapacks$connection();
|
||||||
String base = config.hosting.publicAddress;
|
String base = config.hosting.publicAddress;
|
||||||
if (base.equals("auto")) {
|
if (base.equals("auto")) {
|
||||||
String address = ((ConnectionData) connection).astrapacks$host();
|
String address = ((ConnectionData) connection).astrapacks$host();
|
||||||
if (address == null || address.isBlank()) throw new IllegalArgumentException("Cannot determine server address; set hosting.publicAddress");
|
if (address == null || address.isBlank())
|
||||||
int port = config.hosting.mode.equals("self_host") ? config.hosting.port : server.getPort();
|
throw new IllegalArgumentException(
|
||||||
try { base = new URI("http", null, address, port, null, null, null).toASCIIString(); }
|
"Cannot determine server address; set hosting.publicAddress");
|
||||||
catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid server address", e); }
|
int port =
|
||||||
|
config.hosting.mode.equals("self_host")
|
||||||
|
? config.hosting.port
|
||||||
|
: server.getPort();
|
||||||
|
try {
|
||||||
|
base = new URI("http", null, address, port, null, null, null).toASCIIString();
|
||||||
|
} catch (URISyntaxException e) {
|
||||||
|
throw new IllegalArgumentException("Invalid server address", e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return base.replaceAll("/+$", "") + host.issuePath(pack);
|
return base.replaceAll("/+$", "") + host.issuePath(pack);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void rebuild(CommandSourceStack source, boolean reload, boolean publishOnly) {
|
public void rebuild(CommandSourceStack source, boolean reload, boolean publishOnly) {
|
||||||
if (!busy.compareAndSet(false, true)) { source.sendFailure(Component.literal("Сборка AstraPacks уже выполняется.")); return; }
|
if (closed) {
|
||||||
source.sendSuccess(() -> Component.literal("AstraPacks: проверка и подготовка ресурспака…"), false);
|
source.sendFailure(Component.literal("AstraPacks остановлен."));
|
||||||
worker.submit(() -> {
|
return;
|
||||||
|
}
|
||||||
|
if (busy) {
|
||||||
|
source.sendFailure(Component.literal("Сборка AstraPacks уже выполняется."));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
busy = true;
|
||||||
|
source.sendSuccess(
|
||||||
|
() -> Component.literal("AstraPacks: проверка и подготовка ресурспака…"), false);
|
||||||
|
worker.execute(() -> preparePack(source, reload, publishOnly));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void preparePack(CommandSourceStack source, boolean reload, boolean publishOnly) {
|
||||||
try {
|
try {
|
||||||
PackConfig next = reload ? PackConfig.load(configPath) : config;
|
PackConfig next = reload ? PackConfig.load(configPath) : config;
|
||||||
if (next.enabled != config.enabled || !PackConfig.JSON.toJson(next.hosting).equals(PackConfig.JSON.toJson(config.hosting)))
|
if (next.enabled != config.enabled || !next.hosting.sameSettings(config.hosting)) {
|
||||||
throw new IOException("Изменение enabled или hosting требует перезапуска сервера.");
|
throw new IOException("Изменение enabled или hosting требует перезапуска сервера.");
|
||||||
PackBuilder.Pack pack = publishOnly ? PackBuilder.previous(root, next) : new PackBuilder(next).build(root, "[88,0]");
|
}
|
||||||
|
PackBuilder.Pack pack =
|
||||||
|
publishOnly
|
||||||
|
? PackBuilder.previous(root, next)
|
||||||
|
: new PackBuilder(next).build(root, "[88,0]");
|
||||||
PackBuilder.verifyExternal(next, pack);
|
PackBuilder.verifyExternal(next, pack);
|
||||||
server.execute(() -> {
|
server.execute(() -> publishPack(source, next, pack));
|
||||||
if (closed) return;
|
|
||||||
config = next; current = pack; host.publish(pack);
|
|
||||||
source.sendSuccess(() -> Component.literal("AstraPacks: готово, " + pack.files() + " файлов, " + pack.bytes() + " байт. SHA-1: " + pack.sha1()), true);
|
|
||||||
if (config.enabled && config.build.resendAfterBuild) resendAll();
|
|
||||||
});
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
AstraPacks.LOG.error("Pack build/publication failed; active pack retained", e);
|
AstraPacks.LOG.error("Pack build/publication failed; active pack retained", e);
|
||||||
server.execute(() -> source.sendFailure(Component.literal("AstraPacks: " + e.getMessage() + " Рабочий пак сохранён.")));
|
server.execute(
|
||||||
} finally { busy.set(false); }
|
() -> {
|
||||||
|
busy = false;
|
||||||
|
if (!closed) {
|
||||||
|
source.sendFailure(
|
||||||
|
Component.literal(
|
||||||
|
"AstraPacks: "
|
||||||
|
+ e.getMessage()
|
||||||
|
+ " Рабочий пак сохранён."));
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void publishPack(CommandSourceStack source, PackConfig next, PackBuilder.Pack pack) {
|
||||||
|
busy = false;
|
||||||
|
if (closed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
config = next;
|
||||||
|
current = pack;
|
||||||
|
host.publish(pack);
|
||||||
|
String message =
|
||||||
|
"AstraPacks: готово, "
|
||||||
|
+ pack.files()
|
||||||
|
+ " файлов, "
|
||||||
|
+ pack.bytes()
|
||||||
|
+ " байт. SHA-1: "
|
||||||
|
+ pack.sha1();
|
||||||
|
source.sendSuccess(() -> Component.literal(message), true);
|
||||||
|
if (config.enabled && config.build.resendAfterBuild) {
|
||||||
|
resendAll();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public void resendAll() {
|
public void resendAll() {
|
||||||
for (var player : server.getPlayerList().getPlayers()) session(player.connection).start(player.connection::send);
|
for (var player : server.getPlayerList().getPlayers())
|
||||||
|
session(player.connection).start(player.connection::send);
|
||||||
}
|
}
|
||||||
|
|
||||||
public String status() {
|
public String status() {
|
||||||
return "AstraPacks " + config.hosting.mode + ", required=" + config.delivery.required
|
return "AstraPacks "
|
||||||
+ ", build=" + busy.get() + ", pack=" + (current == null ? "UNAVAILABLE" : current.path() + " (" + current.files() + " files)");
|
+ config.hosting.mode
|
||||||
|
+ ", required="
|
||||||
|
+ config.delivery.required
|
||||||
|
+ ", build="
|
||||||
|
+ busy
|
||||||
|
+ ", pack="
|
||||||
|
+ (current == null
|
||||||
|
? "UNAVAILABLE"
|
||||||
|
: current.path() + " (" + current.files() + " files)");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
closed = true;
|
||||||
|
worker.shutdownNow();
|
||||||
|
host.close();
|
||||||
|
sessions.clear();
|
||||||
|
welcome.clear();
|
||||||
}
|
}
|
||||||
@Override public void close() { closed = true; worker.shutdownNow(); host.close(); sessions.clear(); welcome.clear(); }
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,21 @@
|
|||||||
package online.astradev.packs;
|
package online.astradev.packs;
|
||||||
|
|
||||||
import java.util.*;
|
|
||||||
import java.util.function.Consumer;
|
|
||||||
import net.minecraft.network.protocol.Packet;
|
import net.minecraft.network.protocol.Packet;
|
||||||
import net.minecraft.network.protocol.common.*;
|
import net.minecraft.network.protocol.common.ClientboundResourcePackPopPacket;
|
||||||
import net.minecraft.server.network.*;
|
import net.minecraft.network.protocol.common.ClientboundResourcePackPushPacket;
|
||||||
|
import net.minecraft.network.protocol.common.ServerboundResourcePackPacket;
|
||||||
|
import net.minecraft.server.network.ConfigurationTask;
|
||||||
|
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
/** Configuration only completes on SUCCESSFULLY_LOADED, never merely ACCEPTED or DOWNLOADED. */
|
/** Configuration only completes on SUCCESSFULLY_LOADED, never merely ACCEPTED or DOWNLOADED. */
|
||||||
public final class PackSession implements ConfigurationTask {
|
public final class PackSession implements ConfigurationTask {
|
||||||
public static final Type TYPE = new Type("astrapacks:resource_pack");
|
public static final Type TYPE = new Type("astrapacks:resource_pack");
|
||||||
private final PackRuntime runtime;
|
private final PackRuntime runtime;
|
||||||
final ServerCommonPacketListenerImpl listener;
|
private final ServerCommonPacketListenerImpl listener;
|
||||||
private final PackConfig config;
|
private final PackConfig config;
|
||||||
private final PackBuilder.Pack pack;
|
private final PackBuilder.Pack pack;
|
||||||
private UUID id;
|
private UUID id;
|
||||||
@@ -19,55 +24,105 @@ public final class PackSession implements ConfigurationTask {
|
|||||||
private boolean done;
|
private boolean done;
|
||||||
private boolean failed;
|
private boolean failed;
|
||||||
private boolean started;
|
private boolean started;
|
||||||
|
|
||||||
public PackSession(PackRuntime runtime, ServerCommonPacketListenerImpl listener) {
|
public PackSession(PackRuntime runtime, ServerCommonPacketListenerImpl listener) {
|
||||||
this.runtime = runtime; this.listener = listener;
|
this.runtime = runtime;
|
||||||
this.config = runtime.config(); this.pack = runtime.current();
|
this.listener = listener;
|
||||||
|
this.config = runtime.config();
|
||||||
|
this.pack = runtime.current();
|
||||||
}
|
}
|
||||||
@Override public Type type() { return TYPE; }
|
|
||||||
@Override public void start(Consumer<Packet<?>> sender) {
|
@Override
|
||||||
|
public Type type() {
|
||||||
|
return TYPE;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void start(Consumer<Packet<?>> sender) {
|
||||||
started = true;
|
started = true;
|
||||||
if (pack == null) {
|
if (pack == null) {
|
||||||
if (config.delivery.required) disconnect(config.messages.unavailable); else done = true;
|
if (config.delivery.required) disconnect(config.messages.unavailable);
|
||||||
|
else done = true;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
send();
|
send();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void send() {
|
private void send() {
|
||||||
if (id != null) listener.send(new ClientboundResourcePackPopPacket(Optional.of(id)));
|
if (id != null) listener.send(new ClientboundResourcePackPopPacket(Optional.of(id)));
|
||||||
id = UUID.randomUUID();
|
id = UUID.randomUUID();
|
||||||
deadline = System.nanoTime() + config.delivery.timeoutSeconds * 1_000_000_000L;
|
deadline = System.nanoTime() + config.delivery.timeoutSeconds * 1_000_000_000L;
|
||||||
try {
|
try {
|
||||||
listener.send(new ClientboundResourcePackPushPacket(id, runtime.url(listener, pack), pack.sha1(),
|
listener.send(
|
||||||
config.delivery.required, config.messages.prompt.isBlank() ? Optional.empty() : Optional.of(PackText.of(config.messages.prompt, player()))));
|
new ClientboundResourcePackPushPacket(
|
||||||
|
id,
|
||||||
|
runtime.url(listener, pack),
|
||||||
|
pack.sha1(),
|
||||||
|
config.delivery.required,
|
||||||
|
config.messages.prompt.isBlank()
|
||||||
|
? Optional.empty()
|
||||||
|
: Optional.of(PackText.of(config.messages.prompt, player()))));
|
||||||
} catch (RuntimeException e) {
|
} catch (RuntimeException e) {
|
||||||
AstraPacks.LOG.error("Cannot send resource pack to {}", player(), e);
|
AstraPacks.LOG.error("Cannot send resource pack to {}", player(), e);
|
||||||
if (config.delivery.required || config.delivery.kickOnFailure) disconnect(config.messages.unavailable); else done = true;
|
fail(config.messages.unavailable);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void response(ServerboundResourcePackPacket packet) {
|
public void response(ServerboundResourcePackPacket packet) {
|
||||||
if (!started || failed || !packet.id().equals(id)) return;
|
if (!started || failed || !packet.id().equals(id)) return;
|
||||||
if (config.delivery.logStatus) AstraPacks.LOG.info("Resource pack {}: {} ({})", player(), packet.action(), pack.sha1());
|
if (config.delivery.logStatus)
|
||||||
|
AstraPacks.LOG.info(
|
||||||
|
"Resource pack {}: {} ({})", player(), packet.action(), pack.sha1());
|
||||||
if (done) return;
|
if (done) return;
|
||||||
switch (packet.action()) {
|
switch (packet.action()) {
|
||||||
case SUCCESSFULLY_LOADED -> { done = true; runtime.loaded(listener, config.messages.loaded); }
|
case SUCCESSFULLY_LOADED -> {
|
||||||
case DECLINED -> { if (config.delivery.required) disconnect(config.messages.declined); else done = true; }
|
done = true;
|
||||||
case FAILED_DOWNLOAD, FAILED_RELOAD, INVALID_URL, DISCARDED -> {
|
runtime.loaded(listener, config.messages.loaded);
|
||||||
if (retries++ < config.delivery.retries) send();
|
}
|
||||||
else if (config.delivery.required || config.delivery.kickOnFailure) disconnect(config.messages.failed);
|
case DECLINED -> {
|
||||||
|
if (config.delivery.required) disconnect(config.messages.declined);
|
||||||
else done = true;
|
else done = true;
|
||||||
}
|
}
|
||||||
default -> { /* Accept/download progress does not extend the bounded deadline. */ }
|
case FAILED_DOWNLOAD, FAILED_RELOAD, INVALID_URL, DISCARDED -> {
|
||||||
|
if (retries < config.delivery.retries) {
|
||||||
|
retries++;
|
||||||
|
send();
|
||||||
|
} else {
|
||||||
|
fail(config.messages.failed);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@Override public boolean tick() {
|
default -> {
|
||||||
|
/* Accept/download progress does not extend the bounded deadline. */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean tick() {
|
||||||
if (started && !done && !failed && System.nanoTime() >= deadline) {
|
if (started && !done && !failed && System.nanoTime() >= deadline) {
|
||||||
if (config.delivery.required || config.delivery.kickOnFailure) disconnect(config.messages.timeout); else done = true;
|
fail(config.messages.timeout);
|
||||||
}
|
}
|
||||||
return done;
|
return done;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void replace() {
|
public void replace() {
|
||||||
if (id != null) listener.send(new ClientboundResourcePackPopPacket(Optional.of(id)));
|
if (id != null) listener.send(new ClientboundResourcePackPopPacket(Optional.of(id)));
|
||||||
}
|
}
|
||||||
private String player() { return listener.getOwner().name(); }
|
|
||||||
private void disconnect(String message) { failed = true; listener.disconnect(PackText.of(message, player())); }
|
private String player() {
|
||||||
|
return listener.getOwner().name();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void fail(String message) {
|
||||||
|
if (config.delivery.required || config.delivery.kickOnFailure) {
|
||||||
|
disconnect(message);
|
||||||
|
} else {
|
||||||
|
done = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void disconnect(String message) {
|
||||||
|
failed = true;
|
||||||
|
listener.disconnect(PackText.of(message, player()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
package online.astradev.packs;
|
package online.astradev.packs;
|
||||||
|
|
||||||
import net.minecraft.ChatFormatting;
|
import net.minecraft.ChatFormatting;
|
||||||
import net.minecraft.network.chat.*;
|
import net.minecraft.network.chat.Component;
|
||||||
|
import net.minecraft.network.chat.MutableComponent;
|
||||||
|
import net.minecraft.network.chat.Style;
|
||||||
|
|
||||||
public final class PackText {
|
public final class PackText {
|
||||||
private PackText() {}
|
private PackText() {}
|
||||||
|
|
||||||
public static Component of(String text, String player) {
|
public static Component of(String text, String player) {
|
||||||
text = text.replace("{player}", player).replace("\\n", "\n");
|
text = text.replace("{player}", player).replace("\\n", "\n");
|
||||||
MutableComponent result = Component.empty();
|
MutableComponent result = Component.empty();
|
||||||
@@ -15,9 +18,18 @@ public final class PackText {
|
|||||||
if ((ch == '&' || ch == '§') && i + 1 < text.length()) {
|
if ((ch == '&' || ch == '§') && i + 1 < text.length()) {
|
||||||
ChatFormatting code = ChatFormatting.getByCode(text.charAt(i + 1));
|
ChatFormatting code = ChatFormatting.getByCode(text.charAt(i + 1));
|
||||||
if (code != null) {
|
if (code != null) {
|
||||||
result.append(Component.literal(part.toString()).setStyle(style)); part.setLength(0);
|
result.append(Component.literal(part.toString()).setStyle(style));
|
||||||
style = code == ChatFormatting.RESET ? Style.EMPTY : "0123456789abcdef".indexOf(Character.toLowerCase(text.charAt(i + 1))) >= 0 ? Style.EMPTY.applyFormat(code) : style.applyFormat(code);
|
part.setLength(0);
|
||||||
i++; continue;
|
if (code == ChatFormatting.RESET) {
|
||||||
|
style = Style.EMPTY;
|
||||||
|
} else if ("0123456789abcdef".indexOf(Character.toLowerCase(text.charAt(i + 1)))
|
||||||
|
>= 0) {
|
||||||
|
style = Style.EMPTY.applyFormat(code);
|
||||||
|
} else {
|
||||||
|
style = style.applyFormat(code);
|
||||||
|
}
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
part.append(ch);
|
part.append(ch);
|
||||||
|
|||||||
@@ -29,11 +29,12 @@ class PackCoreTest {
|
|||||||
}
|
}
|
||||||
@Test void deterministicAndDeletedResourcesDisappear() throws Exception {
|
@Test void deterministicAndDeletedResourcesDisappear() throws Exception {
|
||||||
PackConfig c = config(); asset("assets/demo/lang/en_us.json", "{\"hello\":\"world\"}");
|
PackConfig c = config(); asset("assets/demo/lang/en_us.json", "{\"hello\":\"world\"}");
|
||||||
var a = new PackBuilder(c).build(root, "[88,0]");
|
var builder = new PackBuilder(c);
|
||||||
var b = new PackBuilder(c).build(root, "[88,0]");
|
var a = builder.build(root, "[88,0]");
|
||||||
|
var b = builder.build(root, "[88,0]");
|
||||||
assertEquals(a.sha1(), b.sha1());
|
assertEquals(a.sha1(), b.sha1());
|
||||||
Files.delete(root.resolve("astrapacks/contents/assets/demo/lang/en_us.json"));
|
Files.delete(root.resolve("astrapacks/contents/assets/demo/lang/en_us.json"));
|
||||||
var changed = new PackBuilder(c).build(root, "[88,0]");
|
var changed = builder.build(root, "[88,0]");
|
||||||
assertNotEquals(a.sha1(), changed.sha1());
|
assertNotEquals(a.sha1(), changed.sha1());
|
||||||
assertTrue(Files.exists(a.path()), "in-flight clients must still be able to fetch the old ZIP");
|
assertTrue(Files.exists(a.path()), "in-flight clients must still be able to fetch the old ZIP");
|
||||||
try (var z = new ZipFile(changed.path().toFile())) { assertNull(z.getEntry("assets/demo/lang/en_us.json")); assertNotNull(z.getEntry("pack.mcmeta")); }
|
try (var z = new ZipFile(changed.path().toFile())) { assertNull(z.getEntry("assets/demo/lang/en_us.json")); assertNotNull(z.getEntry("pack.mcmeta")); }
|
||||||
|
|||||||
@@ -1,121 +0,0 @@
|
|||||||
"""Vanilla protocol 776 probe against an isolated, localhost offline test server.
|
|
||||||
|
|
||||||
Does not render resources or claim to be a graphical Minecraft client.
|
|
||||||
Requires network-compression-threshold=-1, timeoutSeconds=10 and retries=0.
|
|
||||||
"""
|
|
||||||
import hashlib
|
|
||||||
import io
|
|
||||||
import socket
|
|
||||||
import struct
|
|
||||||
import sys
|
|
||||||
import time
|
|
||||||
import urllib.request
|
|
||||||
import uuid
|
|
||||||
import zipfile
|
|
||||||
|
|
||||||
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 25585
|
|
||||||
|
|
||||||
|
|
||||||
def varint(n):
|
|
||||||
out = bytearray()
|
|
||||||
while n > 127:
|
|
||||||
out.append((n & 127) | 128)
|
|
||||||
n >>= 7
|
|
||||||
out.append(n)
|
|
||||||
return bytes(out)
|
|
||||||
|
|
||||||
|
|
||||||
def readint(read):
|
|
||||||
n = 0
|
|
||||||
for i in range(5):
|
|
||||||
b = read(1)
|
|
||||||
if not b:
|
|
||||||
raise EOFError()
|
|
||||||
n |= (b[0] & 127) << (7 * i)
|
|
||||||
if b[0] < 128:
|
|
||||||
return n
|
|
||||||
raise ValueError("Bad VarInt")
|
|
||||||
|
|
||||||
|
|
||||||
def string(s):
|
|
||||||
b = s.encode()
|
|
||||||
return varint(len(b)) + b
|
|
||||||
|
|
||||||
|
|
||||||
class Client:
|
|
||||||
def __init__(self, name):
|
|
||||||
self.s = socket.create_connection(("127.0.0.1", PORT), timeout=20)
|
|
||||||
self.f = self.s.makefile("rb")
|
|
||||||
self.send(0, varint(776) + string("127.0.0.1") + struct.pack(">H", PORT) + varint(2))
|
|
||||||
self.send(0, string(name) + uuid.uuid4().bytes)
|
|
||||||
while True:
|
|
||||||
kind, data = self.recv()
|
|
||||||
if kind == 2:
|
|
||||||
break
|
|
||||||
if kind == 4: # Login query: vanilla client does not understand mod channels.
|
|
||||||
query = readint(data.read)
|
|
||||||
self.send(2, varint(query) + b"\x00")
|
|
||||||
elif kind == 0:
|
|
||||||
raise AssertionError("Login disconnected: " + repr(data.read()))
|
|
||||||
elif kind == 3:
|
|
||||||
raise AssertionError("Disable compression in the isolated test server")
|
|
||||||
self.send(3) # login acknowledged
|
|
||||||
|
|
||||||
def send(self, kind, data=b""):
|
|
||||||
payload = varint(kind) + data
|
|
||||||
self.s.sendall(varint(len(payload)) + payload)
|
|
||||||
|
|
||||||
def recv(self):
|
|
||||||
size = readint(self.f.read)
|
|
||||||
data = io.BytesIO(self.f.read(size))
|
|
||||||
return readint(data.read), data
|
|
||||||
|
|
||||||
def config(self):
|
|
||||||
while True:
|
|
||||||
kind, data = self.recv()
|
|
||||||
if kind == 14:
|
|
||||||
self.send(7, varint(0)) # request registry data; no known packs
|
|
||||||
elif kind == 4:
|
|
||||||
self.send(4, data.read())
|
|
||||||
elif kind == 5:
|
|
||||||
self.send(5, data.read())
|
|
||||||
elif kind in (2, 3, 9):
|
|
||||||
return kind, data
|
|
||||||
|
|
||||||
def pack(self):
|
|
||||||
kind, data = self.config()
|
|
||||||
assert kind == 9, (kind, data.read())
|
|
||||||
self.id = data.read(16)
|
|
||||||
self.url = data.read(readint(data.read)).decode()
|
|
||||||
self.sha1 = data.read(readint(data.read)).decode()
|
|
||||||
assert data.read(1) == b"\x01", "Pack must be required"
|
|
||||||
with urllib.request.urlopen(self.url, timeout=10) as response:
|
|
||||||
payload = response.read()
|
|
||||||
assert hashlib.sha1(payload).hexdigest() == self.sha1
|
|
||||||
with zipfile.ZipFile(io.BytesIO(payload)) as archive:
|
|
||||||
assert "pack.mcmeta" in archive.namelist()
|
|
||||||
|
|
||||||
def respond(self, action, identity=None):
|
|
||||||
self.send(6, (identity or self.id) + varint(action))
|
|
||||||
|
|
||||||
def close(self):
|
|
||||||
self.f.close()
|
|
||||||
self.s.close()
|
|
||||||
|
|
||||||
|
|
||||||
for mode, action in [("declined", 1), ("failed_download", 2), ("failed_reload", 7), ("loaded", 0), ("accepted_timeout", 3), ("wrong_uuid", None)]:
|
|
||||||
client = Client("Astra_" + mode[:10])
|
|
||||||
try:
|
|
||||||
client.pack()
|
|
||||||
if action is not None:
|
|
||||||
client.respond(action)
|
|
||||||
else:
|
|
||||||
client.respond(0, uuid.uuid4().bytes)
|
|
||||||
start = time.monotonic()
|
|
||||||
kind, data = client.config()
|
|
||||||
assert kind == (3 if mode == "loaded" else 2), (mode, kind, data.read())
|
|
||||||
if mode in ("accepted_timeout", "wrong_uuid"):
|
|
||||||
assert time.monotonic() - start >= 8, "Unexpected early gate completion"
|
|
||||||
print("PASS", mode, "HTTP SHA-1 verified;", "configuration finished" if kind == 3 else "disconnected before world", flush=True)
|
|
||||||
finally:
|
|
||||||
client.close()
|
|
||||||
Reference in New Issue
Block a user