Replace Paper pack bridge with server-only NeoForge resource-pack core
This commit is contained in:
@@ -1,55 +1,23 @@
|
||||
# Общие правила работы с плагинами AstraDev
|
||||
# AstraPacks — серверный мод NeoForge
|
||||
|
||||
Эти правила действуют для всех проектов в `C:\Users\ScarPC\Documents\Plugins`.
|
||||
Общая копия хранится в `Plugins\AGENTS.md`; копии в репозиториях нужны, чтобы правила
|
||||
сохранялись при клонировании отдельного плагина. При изменении общих правил обновлять все копии.
|
||||
Этот проект перенесён с Paper на NeoForge по прямому указанию пользователя.
|
||||
Правила ниже заменяют устаревшие указания о Paper-сервере из родительского AGENTS.md для AstraPacks.
|
||||
|
||||
## Расположение проектов и сервера
|
||||
|
||||
- Каждый плагин имеет отдельную папку исходников и собственный Git-репозиторий в `C:\Users\ScarPC\Documents\Plugins`.
|
||||
- Рабочий сервер: `C:\Users\ScarPC\Documents\26.2 Paper`.
|
||||
- Установленные JAR: `C:\Users\ScarPC\Documents\26.2 Paper\plugins`.
|
||||
- Архив старых JAR: `C:\Users\ScarPC\Documents\26.2 Paper\old-plugins`.
|
||||
|
||||
## Обязательная установка собранного JAR
|
||||
|
||||
После изменений кода, встроенных ресурсов или сборки плагина работа включает не только
|
||||
сборку артефакта, но и обновление соответствующего JAR в папке плагинов рабочего сервера.
|
||||
|
||||
1. Выполнить сборку и проверки, необходимые для сделанных изменений. Устанавливать только успешно собранный JAR.
|
||||
2. Найти установленный JAR именно этого плагина. Сопоставлять имя плагина, а не только номер версии файла.
|
||||
3. Перед заменой перенести старую версию в `old-plugins\YYYYMMDD-HHMMSS\`, сохранив исходное имя JAR.
|
||||
Если папка уже существует, выбрать уникальное имя. Не удалять и не перезаписывать старые версии в архиве.
|
||||
4. Скопировать новый JAR непосредственно в корень `C:\Users\ScarPC\Documents\26.2 Paper\plugins`.
|
||||
Не оставлять там одновременно старую и новую версии одного плагина.
|
||||
5. Проверить по SHA-256 именно JAR в корне `plugins`: он должен совпадать с собранным артефактом.
|
||||
6. При обновлении нескольких плагинов выполнить эти действия для каждого изменённого плагина.
|
||||
|
||||
Не заменять конфигурации, данные плагинов и миры при обычном обновлении JAR.
|
||||
Если установка не выполнена, явно сообщить об этом; не объявлять обновление сервера завершённым.
|
||||
Изменения только документации и правил не требуют пересборки и замены неизменного JAR.
|
||||
|
||||
### Только прямая замена в корне plugins
|
||||
|
||||
- Запрошенное обновление означает фактическую замену JAR в корне `plugins`, а не подготовку к следующему запуску.
|
||||
- Не создавать и не использовать `plugins/update`, другие промежуточные папки, отложенную установку,
|
||||
фоновые скрипты замены или второй JAR под другим именем как обход прямой замены.
|
||||
- Если работающий сервер или другой процесс блокирует JAR, сообщить о блокировке и необходимости
|
||||
освободить файл для прямой замены. Блокировка не разрешает переносить обновление в `plugins/update`.
|
||||
- После освобождения файла выполнить обычную процедуру: перенести старый JAR в архив,
|
||||
скопировать новый непосредственно в корень `plugins` и сравнить SHA-256.
|
||||
- Пока новый JAR не находится в корне `plugins` и его SHA-256 не проверен, установка не завершена.
|
||||
Наличие сборки или копии в промежуточной папке не считается установкой.
|
||||
|
||||
## Обязательная фиксация в Git
|
||||
|
||||
- Каждая завершённая задача с изменениями файлов должна быть зафиксирована коммитом
|
||||
в соответствующем репозитории. Коммит — обязательная часть работы, отдельное напоминание пользователя не требуется.
|
||||
- Если задача затрагивает несколько репозиториев, создать отдельный коммит в каждом из них.
|
||||
- Перед коммитом проверить diff и результаты необходимых проверок.
|
||||
- Коммитить изменения текущей задачи. Не включать посторонние изменения пользователя и не откатывать их.
|
||||
- Сообщение коммита должно описывать конкретное изменение.
|
||||
- Не добавлять в Git собранные JAR, каталоги build/.gradle, журналы, тестовые серверы и резервные копии.
|
||||
- Push выполнять, когда он запрошен пользователем или уже разрешён в текущей задаче; сам коммит обязателен независимо от push.
|
||||
- В итоговом ответе указать результат установки JAR, расположение сохранённой старой версии и созданные коммиты,
|
||||
когда соответствующие действия выполнялись в этой задаче.
|
||||
- Исходники: `C:\Users\ScarPC\Documents\Plugins\AstraPacks`.
|
||||
- Рабочий сервер: `C:\Users\ScarPC\Documents\NeoForge Server 26.2`.
|
||||
- Платформа: Minecraft 26.2, NeoForge 26.2.0.79, Java 25+.
|
||||
- Мод только серверный. Клиент не обязан устанавливать NeoForge или AstraPacks.
|
||||
- Не добавлять зависимости на Bukkit, Paper, ItemsAdder или обязательные клиентские каналы.
|
||||
- После изменений кода/ресурсов выполнить сборку и соответствующие проверки.
|
||||
- Установить только успешно собранный JAR непосредственно в `mods` рабочего NeoForge-сервера.
|
||||
- Старый JAR именно AstraPacks, если он есть, перенести в `old-mods/YYYYMMDD-HHMMSS/`,
|
||||
не перезаписывая архивы. После копирования сверить SHA-256 установленного и собранного JAR.
|
||||
- Не использовать отложенную установку; не оставлять несколько версий в mods.
|
||||
- Не заменять конфигурацию, миры или пользовательские ресурсы при обновлении JAR.
|
||||
- Paper-сервер и его плагины при работе над этим модом не изменять.
|
||||
- Изменения завершённой задачи обязательно зафиксировать отдельным Git-коммитом;
|
||||
перед коммитом проверить diff. Не включать посторонние изменения пользователя.
|
||||
- JAR сборки, build, .gradle, журналы, тестовые серверы и резервные копии не коммитить.
|
||||
Стандартный `gradle/wrapper/gradle-wrapper.jar` является частью исходников сборочной системы.
|
||||
- Push только по запросу пользователя.
|
||||
- В итоге сообщить результат установки, путь архива прежнего JAR (если был) и коммит.
|
||||
|
||||
@@ -1,72 +1,147 @@
|
||||
# AstraPacks
|
||||
|
||||
Общий ресурспак AstraDev для Paper 26.2, Java 25+ и ItemsAdder 4.0.18.
|
||||
Серверное ядро ресурспаков AstraDev для **Minecraft 26.2 / NeoForge 26.2.0.79 / Java 25+**.
|
||||
Установка мода на клиент не нужна. Paper, Bukkit и ItemsAdder не используются.
|
||||
|
||||
## Установка и обновление
|
||||
## Установка
|
||||
|
||||
Один раз установите AstraPacks вместе с обновлёнными AstraArmorStatues, AstraBanners,
|
||||
AstraMonitor и AstraFertilizers. ItemsAdder и его настроенный хостинг должны оставаться на сервере.
|
||||
Дальше заменяйте JAR нужного плагина и перезапускайте сервер. Ручная установка ZIP,
|
||||
копирование контента и команда `/iazip` не требуются. В папке plugins оставляйте одну версию каждого плагина.
|
||||
AstraSpears использует ванильные ресурсы и не нуждается в интеграции.
|
||||
Поместите `AstraPacks-0.2.0.jar` в `mods` и запустите сервер.
|
||||
Настройки создаются в `config/astrapacks.json`, исходные ресурсы — в `astrapacks/contents`,
|
||||
готовые ZIP — в `astrapacks/output`. По умолчанию включены раздача через игровой порт,
|
||||
отправка при входе и обязательная загрузка до допуска в мир.
|
||||
Пустая папка ресурсов создаёт технически корректный пак только с `pack.mcmeta`.
|
||||
Контент остальных проектов добавляется при их переносе; эта версия не переносит предметы и конфигурации ItemsAdder.
|
||||
|
||||
AstraPacks до включения ItemsAdder извлекает контент из JAR в отдельные папки:
|
||||
`resource-pack` в `server.properties` должен быть пустым: отправкой управляет AstraPacks.
|
||||
Если одновременно настроена ванильная отправка, мод сообщает об ошибке при старте.
|
||||
Существующие настройки, миры и данные мод не заменяет.
|
||||
|
||||
| Плагин | Папка внутри ItemsAdder/contents |
|
||||
## Хостинг
|
||||
|
||||
`hosting.mode` принимает ровно одно из трёх значений:
|
||||
|
||||
| Режим | Поведение |
|
||||
| --- | --- |
|
||||
| AstraBanners | astradev_pixelbanners |
|
||||
| AstraArmorStatues | astradev_armorstatues |
|
||||
| AstraMonitor | astradev_monitor |
|
||||
| AstraFertilizers | astradev_fertilizers |
|
||||
| `simple_self_host` | HTTP и Minecraft работают на одном игровом TCP-порту. Дополнительный порт не требуется. |
|
||||
| `self_host` | Отдельный HTTP-сервер на `bindAddress:port`. Для удалённых игроков нужен доступ к этому порту. |
|
||||
| `no_host` | HTTP-сервер отсутствует. Готовый ZIP размещается владельцем на внешнем хостинге, ссылка задаётся в `externalUrl`. |
|
||||
|
||||
После готовности ItemsAdder запускается одна пересборка на все изменения.
|
||||
При неизменном контенте и готовом ZIP пересборка пропускается. При неудачной сборке
|
||||
обновление остаётся ожидающим и повторяется при следующем запуске.
|
||||
Отправкой пакета и настройками входа занимается ItemsAdder. Редакторы не проверяют
|
||||
подтверждение загрузки пака и не закрываются при отказе от него.
|
||||
Старые параметры resource-pack в конфигурациях этих двух плагинов больше не используются.
|
||||
Для встроенных режимов `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.
|
||||
|
||||
Контент внутри управляемых папок обновляется при изменении соответствующего ресурса в JAR.
|
||||
Неизменные ресурсы не перезаписываются: это сохраняет оптимизацию PNG, выполненную ItemsAdder.
|
||||
Заменяемые и удаляемые файлы
|
||||
сохраняются в `plugins/AstraPacks/backups`. Файлы, которых никогда не было в поставке,
|
||||
сохраняются на месте. Для собственных дополнений используйте отдельную папку ItemsAdder/contents.
|
||||
При удалении плагина его ранее учтённые ресурсы удаляются из общей сборки после перезапуска;
|
||||
файлы сохраняются в резервной копии. Настройки, миры и данные плагинов не удаляются.
|
||||
Для внешнего хостинга укажите прямую ссылку на ZIP в `hosting.externalUrl`.
|
||||
`/astrapacks build` сохраняет ZIP локально. Перед публикацией мод скачивает внешний файл
|
||||
и сверяет SHA-1; если файлы различаются, новая версия не отправляется игрокам.
|
||||
Загрузите указанный в сообщении ZIP на хостинг и выполните `/astrapacks publish`.
|
||||
Автоматического доступа к аккаунтам хостинга или загрузки по FTP/S3 в моде нет.
|
||||
Для режима только сборки без отправки установите `delivery.sendOnJoin=false` и `delivery.required=false`.
|
||||
|
||||
Хостинг ItemsAdder не перенастраивается. Автоматическая публикация работает с настроенным
|
||||
встроенным хостингом; при ручном внешнем хостинге загрузка нового ZIP на внешний сервис
|
||||
по-прежнему должна быть автоматизирована самим владельцем сервера.
|
||||
## Настройки
|
||||
|
||||
## Формат для новых плагинов
|
||||
Файл JSON хранится в UTF-8. Отсутствующие поля получают значения по умолчанию.
|
||||
Недопустимые значения дают ошибку; файл автоматически не переписывается.
|
||||
Все пути относительны папке сервера, также допускаются абсолютные пути.
|
||||
|
||||
В корне JAR разместите `astra-pack.properties`:
|
||||
| Поле | По умолчанию | Назначение |
|
||||
| --- | --- | --- |
|
||||
| `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=1
|
||||
plugin=ExamplePlugin
|
||||
folder=astradev_example
|
||||
schema=2
|
||||
```
|
||||
|
||||
Контент ItemsAdder хранится внутри JAR в `astra-itemsadder/astradev_example/`.
|
||||
Готовые ресурсы Minecraft: `resourcepack/assets/<namespace>/...`.
|
||||
Предметы ItemsAdder: `configs/*.yml` и соответствующие исходные текстуры/модели.
|
||||
Добавьте `depend: [AstraPacks, ItemsAdder]` в plugin.yml. Не меняйте пространство имён
|
||||
существующих моделей при переходе на этот формат.
|
||||
Готовые клиентские ресурсы храните в `astra-resourcepack/assets/<namespace>/...`,
|
||||
значок — в `astra-resourcepack/pack.png`. JAR без дескриптора не сканируется как ресурспак.
|
||||
Это формат готовых ресурсов Minecraft; схемы и генераторы предметов ItemsAdder не поддерживаются.
|
||||
Используйте зависимость NeoForge на `astrapacks` со стороной `SERVER` для модов,
|
||||
которые требуют наличия этого ядра. Никаких клиентских каналов или синхронизируемых реестров ядро не добавляет.
|
||||
|
||||
Пример структуры JAR:
|
||||
## Сборка и проверка
|
||||
|
||||
```text
|
||||
plugin.yml
|
||||
astra-pack.properties
|
||||
astra-itemsadder/astradev_example/
|
||||
resourcepack/assets/example/items/tool.json
|
||||
resourcepack/assets/example/models/item/tool.json
|
||||
resourcepack/assets/example/textures/item/tool.png
|
||||
```
|
||||
`gradlew.bat build` (Windows), `./gradlew build` (Linux).
|
||||
Результат: `build/libs/AstraPacks-0.2.0.jar`.
|
||||
JUnit проверяет детерминизм, конфликты, восстановление предыдущей сборки, опасные пути,
|
||||
лимиты, JAR-модули, настройки и HTTP-раздачу.
|
||||
`tools/smoke_protocol.py` проверяет вход по ванильному протоколу на отдельном локальном
|
||||
тестовом сервере. Условия запуска указаны в самом скрипте. Результаты — в `VERIFICATION.md`.
|
||||
|
||||
## Сборка
|
||||
## Источники требований
|
||||
|
||||
`gradlew.bat build` в этой папке. Результат: `build/libs/AstraPacks-0.1.0.jar`.
|
||||
Для всего набора используйте `../PixelBanners/tools/build-server-plugins.ps1`.
|
||||
Исходники плагинов лежат в отдельных соседних папках внутри `Documents/Plugins`.
|
||||
Поведение режимов и сообщений спроектировано с учётом документации 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 не импортируется.
|
||||
|
||||
+52
-24
@@ -1,28 +1,56 @@
|
||||
# Проверка интеграции ItemsAdder
|
||||
# Проверка AstraPacks 0.2.0 — 2026-09-06
|
||||
|
||||
Проверено 2026-09-05 на отдельном сервере Paper 26.2-121 с ItemsAdder 4.0.18,
|
||||
его штатной защитой ZIP/PNG и simple_self_host.
|
||||
Платформа: Minecraft 26.2, NeoForge 26.2.0.79, Java 26.0.2 (целевой байткод Java 25).
|
||||
|
||||
- Четыре пакета автоматически извлечены из пяти установленных JAR (включая AstraPacks).
|
||||
- Ресурсы извлекаются в onLoad AstraPacks до включения ItemsAdder.
|
||||
- После первоначальной готовности ItemsAdder вызывается одна общая сборка.
|
||||
- Готовый generated.zip содержит маркер текущей сборки; неподтверждённая сборка остаётся pending.
|
||||
- Повторный запуск: 0 изменённых файлов, сообщение `Shared resource pack is current; no rebuild needed`.
|
||||
- ItemsAdder изменяет восемь исходных PNG при оптимизации. Это не вызывает повторную установку или сборку.
|
||||
- Проверены 68 ресурсов PixelBanners, ArmorStatues и AstraMonitor в итоговом ZIP: геометрия,
|
||||
tintindex, шрифты и декодированные пиксели совпадают с ресурсами JAR.
|
||||
Проверка учитывает переименование ссылок на текстуры в atlas ItemsAdder и его настройку
|
||||
fix_dark_in_inventory, добавляющую gui_light=front в модели без этого параметра.
|
||||
Для защищённых PNG использован stb_image из библиотек установленного клиента Minecraft.
|
||||
- Проверены цепочки текстура → модель → item definition/atlas 26.2 для трёх удобрений;
|
||||
ItemsAdder зарегистрировал все пять предметов удобрений и губок.
|
||||
- Удалены обработчики статуса ресурспака в ArmorStatues и AstraMonitor; удалены команды pack,
|
||||
их автодополнение и подсказки. У ArmorStatues удалён собственный HTTP-сервер.
|
||||
## Автоматические проверки
|
||||
|
||||
Unit-тесты: PixelBanners 64, ArmorStatues 28, AstraFertilizers 28, AstraMonitor 5,
|
||||
AstraPacks 4; все прошли. Тесты синхронизации проверяют обновление, удаление старых
|
||||
ресурсов, резервные копии, сохранение пользовательских файлов, восстановление после
|
||||
незавершённой сборки, запрет выхода за папку и конфликтующих поставок.
|
||||
`gradlew.bat build`: успешно, 11 JUnit-тестов, 0 ошибок и пропусков.
|
||||
Проверены: одинаковый результат повторной сборки; удаление устаревших ресурсов;
|
||||
сохранение предыдущего ZIP при конфликте; одинаковые дубликаты; last_wins;
|
||||
опасные ZIP-пути; лимиты размера; формат модуля schema=2; валидация конфигурации;
|
||||
повреждение сохранённой сборки; точная HTTP-раздача, HEAD и ограничение токеном;
|
||||
сверка внешнего ZIP перед публикацией.
|
||||
|
||||
Полный визуальный сеанс с игроком после объединения не проводился. Пакет проверен на уровне
|
||||
содержимого и декодирования текстур, загрузка плагинов и автоматическая сборка — на реальном Paper.
|
||||
## Проверка протокола
|
||||
|
||||
На отдельном сервере, доступном только через 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 и проверка графическим клиентом остаются непроверенными.
|
||||
|
||||
+14
-6
@@ -1,19 +1,27 @@
|
||||
plugins { java }
|
||||
plugins {
|
||||
java
|
||||
id("net.neoforged.moddev") version "2.0.146"
|
||||
}
|
||||
group = "online.astradev"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven("https://repo.papermc.io/repository/maven-public/")
|
||||
}
|
||||
dependencies {
|
||||
compileOnly("io.papermc.paper:paper-api:26.2.build.121-stable")
|
||||
testImplementation("com.google.code.gson:gson:2.14.0")
|
||||
testImplementation("io.netty:netty-codec-http:4.2.15.Final")
|
||||
testImplementation("io.netty:netty-handler:4.2.15.Final")
|
||||
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
|
||||
testRuntimeOnly("org.junit.platform:junit-platform-launcher:1.11.4")
|
||||
}
|
||||
neoForge {
|
||||
version = "26.2.0.79"
|
||||
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) }
|
||||
tasks.processResources {
|
||||
inputs.property("pluginVersion", project.version)
|
||||
filesMatching("plugin.yml") { expand("version" to project.version) }
|
||||
inputs.property("modVersion", project.version)
|
||||
filesMatching("META-INF/neoforge.mods.toml") { expand("version" to project.version) }
|
||||
}
|
||||
tasks.test { useJUnitPlatform() }
|
||||
|
||||
Vendored
BIN
Binary file not shown.
+10
@@ -0,0 +1,10 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip
|
||||
networkTimeout=10000
|
||||
retries=0
|
||||
retryBackOffMs=500
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
distributionSha256Sum=acd53f1edaf02f1a8ff99879f8a34b302661a057d9b063ae9e35b552f804d20a
|
||||
@@ -1,27 +1,248 @@
|
||||
#!/usr/bin/env sh
|
||||
set -eu
|
||||
#!/bin/sh
|
||||
|
||||
GRADLE_VERSION="9.7.1"
|
||||
APP_HOME=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
DIST_ROOT="${HOME}/.gradle/pixelbanners-bootstrap"
|
||||
DIST_DIR="${DIST_ROOT}/gradle-${GRADLE_VERSION}"
|
||||
DIST_ZIP="${DIST_ROOT}/gradle-${GRADLE_VERSION}-bin.zip"
|
||||
GRADLE_BIN="${DIST_DIR}/bin/gradle"
|
||||
#
|
||||
# Copyright © 2015 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
if [ ! -x "$GRADLE_BIN" ]; then
|
||||
mkdir -p "$DIST_ROOT"
|
||||
echo "[PixelBanners] Gradle ${GRADLE_VERSION} not found. Downloading..."
|
||||
if command -v curl >/dev/null 2>&1; then
|
||||
curl -fL "https://services.gradle.org/distributions/gradle-${GRADLE_VERSION}-bin.zip" -o "$DIST_ZIP"
|
||||
elif command -v wget >/dev/null 2>&1; then
|
||||
wget -O "$DIST_ZIP" "https://services.gradle.org/distributions/gradle-${GRADLE_VERSION}-bin.zip"
|
||||
else
|
||||
echo "curl or wget is required." >&2
|
||||
##############################################################################
|
||||
#
|
||||
# gradlew start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh gradlew
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
echo "[PixelBanners] Extracting Gradle..."
|
||||
unzip -q -o "$DIST_ZIP" -d "$DIST_ROOT"
|
||||
rm -f "$DIST_ZIP"
|
||||
fi
|
||||
|
||||
exec "$GRADLE_BIN" -p "$APP_HOME" "$@"
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
|
||||
Vendored
+74
-28
@@ -1,36 +1,82 @@
|
||||
@echo off
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem gradlew startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables, and ensure extensions are enabled
|
||||
setlocal EnableExtensions
|
||||
|
||||
set "GRADLE_VERSION=9.7.1"
|
||||
set "APP_HOME=%~dp0"
|
||||
if "%APP_HOME:~-1%"=="\" set "APP_HOME=%APP_HOME:~0,-1%"
|
||||
set "DIST_ROOT=%USERPROFILE%\.gradle\pixelbanners-bootstrap"
|
||||
set "DIST_DIR=%DIST_ROOT%\gradle-%GRADLE_VERSION%"
|
||||
set "DIST_ZIP=%DIST_ROOT%\gradle-%GRADLE_VERSION%-bin.zip"
|
||||
set "GRADLE_BAT=%DIST_DIR%\bin\gradle.bat"
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
if exist "%GRADLE_BAT%" goto run
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
if not exist "%DIST_ROOT%" mkdir "%DIST_ROOT%"
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
echo [AstraFertilizers] Gradle %GRADLE_VERSION% not found. Downloading...
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference='Stop'; Invoke-WebRequest -UseBasicParsing 'https://services.gradle.org/distributions/gradle-%GRADLE_VERSION%-bin.zip' -OutFile '%DIST_ZIP%'"
|
||||
if errorlevel 1 (
|
||||
echo.
|
||||
echo [AstraFertilizers] ERROR: Could not download Gradle %GRADLE_VERSION%.
|
||||
exit /b 1
|
||||
)
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
echo [AstraFertilizers] Extracting Gradle...
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference='Stop'; Expand-Archive -LiteralPath '%DIST_ZIP%' -DestinationPath '%DIST_ROOT%' -Force"
|
||||
if errorlevel 1 (
|
||||
echo.
|
||||
echo [AstraFertilizers] ERROR: Could not extract Gradle.
|
||||
exit /b 1
|
||||
)
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
del /q "%DIST_ZIP%" >nul 2>&1
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
:run
|
||||
call "%GRADLE_BAT%" -p "%APP_HOME%" %*
|
||||
exit /b %ERRORLEVEL%
|
||||
"%COMSPEC%" /c exit 1
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
"%COMSPEC%" /c exit 1
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
|
||||
|
||||
@rem Execute gradlew
|
||||
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
|
||||
@rem which allows us to clear the local environment before executing the java command
|
||||
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel
|
||||
|
||||
:exitWithErrorLevel
|
||||
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
|
||||
"%COMSPEC%" /c exit %ERRORLEVEL%
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package online.astradev.packs;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.commands.arguments.EntityArgument;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
|
||||
import net.neoforged.api.distmarker.Dist;
|
||||
import net.neoforged.bus.api.IEventBus;
|
||||
import net.neoforged.fml.common.Mod;
|
||||
import net.neoforged.fml.loading.FMLPaths;
|
||||
import net.neoforged.neoforge.common.NeoForge;
|
||||
import net.neoforged.neoforge.event.RegisterCommandsEvent;
|
||||
import net.neoforged.neoforge.event.entity.player.PlayerEvent;
|
||||
import net.neoforged.neoforge.event.server.*;
|
||||
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
||||
import net.neoforged.neoforge.network.event.RegisterConfigurationTasksEvent;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@Mod(value = "astrapacks", dist = Dist.DEDICATED_SERVER)
|
||||
public final class AstraPacks {
|
||||
public static final Logger LOG = LoggerFactory.getLogger("AstraPacks");
|
||||
public AstraPacks(IEventBus modBus) {
|
||||
modBus.addListener(this::configuration);
|
||||
NeoForge.EVENT_BUS.addListener(this::start);
|
||||
NeoForge.EVENT_BUS.addListener(this::stop);
|
||||
NeoForge.EVENT_BUS.addListener(this::commands);
|
||||
NeoForge.EVENT_BUS.addListener(this::tick);
|
||||
NeoForge.EVENT_BUS.addListener(this::login);
|
||||
}
|
||||
private void start(ServerAboutToStartEvent event) {
|
||||
Path root = FMLPaths.GAMEDIR.get().toAbsolutePath();
|
||||
Path path = FMLPaths.CONFIGDIR.get().resolve("astrapacks.json");
|
||||
try {
|
||||
PackRuntime runtime = new PackRuntime(event.getServer(), root, path, PackConfig.load(path));
|
||||
PackRuntime.INSTANCE = runtime;
|
||||
runtime.start();
|
||||
} catch (Exception e) {
|
||||
if (PackRuntime.INSTANCE != null) PackRuntime.INSTANCE.close();
|
||||
PackRuntime.INSTANCE = null;
|
||||
throw new IllegalStateException("Cannot initialize AstraPacks", e);
|
||||
}
|
||||
}
|
||||
private void configuration(RegisterConfigurationTasksEvent event) {
|
||||
PackRuntime runtime = PackRuntime.INSTANCE;
|
||||
if (runtime != null && runtime.config().enabled && runtime.config().delivery.sendOnJoin)
|
||||
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) {
|
||||
if (PackRuntime.INSTANCE != null && event.getEntity() instanceof net.minecraft.server.level.ServerPlayer player) PackRuntime.INSTANCE.welcome(player);
|
||||
}
|
||||
private void stop(ServerStoppedEvent event) {
|
||||
if (PackRuntime.INSTANCE != null) PackRuntime.INSTANCE.close();
|
||||
PackRuntime.INSTANCE = null;
|
||||
}
|
||||
private void commands(RegisterCommandsEvent event) {
|
||||
event.getDispatcher().register(Commands.literal("astrapacks").requires(Commands.hasPermission(Commands.LEVEL_ADMINS))
|
||||
.executes(ctx -> { ctx.getSource().sendSuccess(() -> Component.literal(PackRuntime.INSTANCE.status()), false); return 1; })
|
||||
.then(Commands.literal("status").executes(ctx -> { ctx.getSource().sendSuccess(() -> Component.literal(PackRuntime.INSTANCE.status()), false); return 1; }))
|
||||
.then(Commands.literal("build").executes(ctx -> { PackRuntime.INSTANCE.rebuild(ctx.getSource(), false, false); return 1; }))
|
||||
.then(Commands.literal("reload").executes(ctx -> { PackRuntime.INSTANCE.rebuild(ctx.getSource(), true, false); return 1; }))
|
||||
.then(Commands.literal("publish").executes(ctx -> { PackRuntime.INSTANCE.rebuild(ctx.getSource(), false, true); return 1; }))
|
||||
.then(Commands.literal("send").then(Commands.argument("players", EntityArgument.players()).executes(ctx -> {
|
||||
if (!PackRuntime.INSTANCE.config().enabled) {
|
||||
ctx.getSource().sendFailure(Component.literal("AstraPacks отключён в конфигурации.")); return 0;
|
||||
}
|
||||
var players = EntityArgument.getPlayers(ctx, "players");
|
||||
for (var player : players) PackRuntime.INSTANCE.session(player.connection).start(player.connection::send);
|
||||
ctx.getSource().sendSuccess(() -> Component.literal("Ресурспак отправлен: " + players.size()), false); return players.size();
|
||||
}))));
|
||||
}
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
package online.astradev.packs;
|
||||
|
||||
import org.bukkit.event.*;
|
||||
import org.bukkit.event.server.ServerLoadEvent;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.bukkit.scheduler.BukkitRunnable;
|
||||
|
||||
import java.nio.file.*;
|
||||
import java.util.logging.Level;
|
||||
|
||||
public final class AstraPacksPlugin extends JavaPlugin implements Listener {
|
||||
private ContentSync sync;
|
||||
private ContentSync.Result result;
|
||||
private boolean started;
|
||||
private Throwable failure;
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
try {
|
||||
Path plugins = getDataFolder().toPath().toAbsolutePath().getParent();
|
||||
sync =
|
||||
new ContentSync(
|
||||
plugins.resolve("ItemsAdder/contents"), getDataFolder().toPath());
|
||||
result = sync.sync(plugins);
|
||||
getLogger()
|
||||
.info(
|
||||
"ItemsAdder content: "
|
||||
+ result.modules()
|
||||
+ " bundles, "
|
||||
+ result.written()
|
||||
+ " updated files, "
|
||||
+ result.removed()
|
||||
+ " obsolete files removed.");
|
||||
} catch (Exception e) {
|
||||
failure = e;
|
||||
getLogger().log(Level.SEVERE, "Cannot install bundled content", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
if (failure != null) {
|
||||
getServer().getPluginManager().disablePlugin(this);
|
||||
return;
|
||||
}
|
||||
getServer().getPluginManager().registerEvents(this, this);
|
||||
if (!result.buildRequired())
|
||||
getLogger().info("Shared resource pack is current; no rebuild needed.");
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void loaded(ServerLoadEvent event) {
|
||||
if (started || !result.buildRequired()) return;
|
||||
started = true;
|
||||
new BukkitRunnable() {
|
||||
int attempts, readySeconds;
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
if (++attempts > 120) {
|
||||
cancel();
|
||||
getLogger()
|
||||
.severe(
|
||||
"ItemsAdder did not become ready. Pack update remains pending for next restart.");
|
||||
return;
|
||||
}
|
||||
var ia = getServer().getPluginManager().getPlugin("ItemsAdder");
|
||||
if (ia == null || !ia.isEnabled()) return;
|
||||
try {
|
||||
// Use the installed ItemsAdder's public API without an early class-loader
|
||||
// dependency.
|
||||
Class<?> api =
|
||||
Class.forName(
|
||||
"dev.lone.itemsadder.api.ItemsAdder",
|
||||
true,
|
||||
ia.getClass().getClassLoader());
|
||||
if (!(boolean) api.getMethod("areItemsLoaded").invoke(null)) {
|
||||
readySeconds = 0;
|
||||
return;
|
||||
}
|
||||
// ItemsAdder exposes the item registry before its startup lock is released.
|
||||
// Wait for the registry to stay ready across subsequent scheduler ticks.
|
||||
if (++readySeconds < 5) return;
|
||||
var command = getServer().getPluginCommand("itemsadder:iazip");
|
||||
if (command == null || command.getPlugin() != ia)
|
||||
throw new IllegalStateException("ItemsAdder /iazip is unavailable");
|
||||
cancel();
|
||||
getLogger()
|
||||
.info(
|
||||
"Building the shared resource pack once for all updated plugins...");
|
||||
if (!command.execute(getServer().getConsoleSender(), "iazip", new String[0]))
|
||||
throw new IllegalStateException("ItemsAdder rejected /iazip");
|
||||
awaitPack();
|
||||
} catch (Exception e) {
|
||||
cancel();
|
||||
getLogger()
|
||||
.log(
|
||||
Level.SEVERE,
|
||||
"Pack build could not start; update remains pending",
|
||||
e);
|
||||
}
|
||||
}
|
||||
}.runTaskTimer(this, 1, 20);
|
||||
}
|
||||
|
||||
private void awaitPack() {
|
||||
Path zip =
|
||||
getDataFolder()
|
||||
.toPath()
|
||||
.toAbsolutePath()
|
||||
.getParent()
|
||||
.resolve("ItemsAdder/output/generated.zip");
|
||||
new BukkitRunnable() {
|
||||
int attempts, stable;
|
||||
long previousSize = -1, previousTime = -1;
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
if (++attempts > 300) {
|
||||
cancel();
|
||||
getLogger()
|
||||
.severe(
|
||||
"Shared pack was not completed in 5 minutes. Update remains pending for next restart.");
|
||||
return;
|
||||
}
|
||||
if (!ContentSync.validPack(zip, result.fingerprint())) {
|
||||
stable = 0;
|
||||
return;
|
||||
}
|
||||
long size = Files.size(zip), time = Files.getLastModifiedTime(zip).toMillis();
|
||||
stable = size == previousSize && time == previousTime ? stable + 1 : 0;
|
||||
previousSize = size;
|
||||
previousTime = time;
|
||||
if (stable < 3) return;
|
||||
sync.confirmed(result.fingerprint());
|
||||
cancel();
|
||||
getLogger()
|
||||
.info(
|
||||
"Shared resource pack ready: "
|
||||
+ result.modules()
|
||||
+ " bundles. Delivery is managed by ItemsAdder.");
|
||||
} catch (Exception e) {
|
||||
cancel();
|
||||
getLogger()
|
||||
.log(
|
||||
Level.SEVERE,
|
||||
"Could not confirm pack build; update remains pending",
|
||||
e);
|
||||
}
|
||||
}
|
||||
}.runTaskTimerAsynchronously(this, 20, 20);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package online.astradev.packs;
|
||||
|
||||
public interface ConnectionData {
|
||||
String astrapacks$host();
|
||||
void astrapacks$host(String host);
|
||||
}
|
||||
@@ -1,242 +0,0 @@
|
||||
package online.astradev.packs;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.security.*;
|
||||
import java.util.*;
|
||||
import java.util.zip.*;
|
||||
|
||||
/** Installs bundled resources while preserving unmanaged files. */
|
||||
public final class ContentSync {
|
||||
static final String PREFIX = "astra-itemsadder/";
|
||||
static final String MARKER = "assets/astrapacks/lang/en_us.json";
|
||||
private final Path contents, state;
|
||||
|
||||
public ContentSync(Path contents, Path state) {
|
||||
this.contents = contents.toAbsolutePath().normalize();
|
||||
this.state = state.toAbsolutePath().normalize();
|
||||
}
|
||||
|
||||
public record Result(
|
||||
String fingerprint, int modules, int written, int removed, boolean buildRequired) {}
|
||||
|
||||
public Result sync(Path plugins) throws IOException {
|
||||
SortedMap<String, byte[]> desired = new TreeMap<>();
|
||||
Set<String> owners = new HashSet<>();
|
||||
Set<String> folders = new HashSet<>();
|
||||
List<byte[]> itemsAdderDescriptors = new ArrayList<>();
|
||||
try (var paths = Files.list(plugins)) {
|
||||
for (Path jar :
|
||||
paths.filter(p -> p.getFileName().toString().endsWith(".jar"))
|
||||
.sorted()
|
||||
.toList()) {
|
||||
try (var zip = new ZipFile(jar.toFile())) {
|
||||
var plugin = zip.getEntry("plugin.yml");
|
||||
if (plugin != null) {
|
||||
try (var in = zip.getInputStream(plugin)) {
|
||||
byte[] bytes = in.readAllBytes();
|
||||
String yaml = new String(bytes, StandardCharsets.UTF_8);
|
||||
if (yaml.matches("(?s).*\\bname:\\s*['\"]?ItemsAdder['\"]?\\s.*"))
|
||||
itemsAdderDescriptors.add(bytes);
|
||||
}
|
||||
}
|
||||
var descriptor = zip.getEntry("astra-pack.properties");
|
||||
if (descriptor == null) continue;
|
||||
Properties info = new Properties();
|
||||
try (var in = zip.getInputStream(descriptor)) {
|
||||
info.load(in);
|
||||
}
|
||||
String owner = info.getProperty("plugin", "");
|
||||
String folder = info.getProperty("folder", "");
|
||||
if (!"1".equals(info.getProperty("schema"))
|
||||
|| !owner.matches("[A-Za-z0-9_]+")
|
||||
|| !folder.matches("[a-z0-9_]+")
|
||||
|| folder.equals("astrapacks_meta"))
|
||||
throw new IOException("Invalid astra-pack.properties in " + jar);
|
||||
if (!owners.add(owner) || !folders.add(folder))
|
||||
throw new IOException(
|
||||
"Duplicate plugin/content bundle: " + owner + " in " + jar);
|
||||
int count = 0;
|
||||
for (var entries = zip.entries(); entries.hasMoreElements(); ) {
|
||||
ZipEntry entry = entries.nextElement();
|
||||
if (entry.isDirectory() || !entry.getName().startsWith(PREFIX)) continue;
|
||||
String name = entry.getName().substring(PREFIX.length());
|
||||
safe(contents, name);
|
||||
if (!name.startsWith(folder + "/"))
|
||||
throw new IOException("Bundle writes outside its folder: " + name);
|
||||
try (var in = zip.getInputStream(entry)) {
|
||||
byte[] bytes = in.readNBytes(32 * 1024 * 1024 + 1);
|
||||
if (bytes.length > 32 * 1024 * 1024)
|
||||
throw new IOException("Oversized resource: " + name);
|
||||
if (desired.putIfAbsent(name, bytes) != null)
|
||||
throw new IOException("Duplicate resource: " + name);
|
||||
}
|
||||
count++;
|
||||
}
|
||||
if (count == 0) throw new IOException("Empty resource bundle: " + jar);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Shared client paths must have identical contents.
|
||||
Map<String, byte[]> assets = new HashMap<>();
|
||||
for (var entry : desired.entrySet()) {
|
||||
int offset = entry.getKey().indexOf("/resourcepack/assets/");
|
||||
if (offset < 0) continue;
|
||||
String asset = entry.getKey().substring(offset + "/resourcepack/".length());
|
||||
byte[] previous = assets.putIfAbsent(asset, entry.getValue());
|
||||
if (previous != null && !Arrays.equals(previous, entry.getValue()))
|
||||
throw new IOException("Conflicting client resource: " + asset);
|
||||
}
|
||||
MessageDigest digest = sha256();
|
||||
for (var entry : desired.entrySet()) {
|
||||
digest.update(entry.getKey().getBytes(StandardCharsets.UTF_8));
|
||||
digest.update((byte) 0);
|
||||
digest.update(sha256().digest(entry.getValue()));
|
||||
}
|
||||
// Rebuild after ItemsAdder upgrades or changes to its generation/hosting settings too.
|
||||
Path iaConfig = plugins.resolve("ItemsAdder/config.yml");
|
||||
if (Files.exists(iaConfig)) digest.update(Files.readAllBytes(iaConfig));
|
||||
itemsAdderDescriptors.forEach(digest::update);
|
||||
String fingerprint = HexFormat.of().formatHex(digest.digest());
|
||||
desired.put("astrapacks_meta/resourcepack/" + MARKER, marker(fingerprint));
|
||||
Properties previous = read(state.resolve("managed.properties"));
|
||||
Properties confirmed = read(state.resolve("built.properties"));
|
||||
Path output = plugins.resolve("ItemsAdder/output/generated.zip");
|
||||
boolean needsBuild =
|
||||
!fingerprint.equals(confirmed.getProperty("fingerprint"))
|
||||
|| Files.exists(state.resolve("pending"))
|
||||
|| !validPack(output, fingerprint);
|
||||
// Validate every destination before modifying any content, including stale manifest
|
||||
// entries.
|
||||
for (String name : desired.keySet()) safe(contents, name);
|
||||
for (String name : previous.stringPropertyNames()) safe(contents, name);
|
||||
int written = 0, removed = 0;
|
||||
String backup = "backups/" + System.currentTimeMillis() + "-" + UUID.randomUUID();
|
||||
Properties managed = new Properties();
|
||||
for (var entry : desired.entrySet()) {
|
||||
Path target = safe(contents, entry.getKey());
|
||||
String hash = hash(entry.getValue());
|
||||
managed.setProperty(entry.getKey(), hash);
|
||||
// ItemsAdder optimizes some source PNGs in place. Reinstall only changed JAR
|
||||
// payloads or missing files; otherwise every restart would undo its optimization.
|
||||
if (Files.isRegularFile(target)
|
||||
&& (hash.equals(previous.getProperty(entry.getKey()))
|
||||
|| hash(Files.readAllBytes(target)).equals(hash))) continue;
|
||||
if (written == 0)
|
||||
atomicWrite(state.resolve("pending"), fingerprint.getBytes(StandardCharsets.UTF_8));
|
||||
if (Files.exists(target)) backup(target, backup, entry.getKey());
|
||||
atomicWrite(target, entry.getValue());
|
||||
written++;
|
||||
}
|
||||
for (String name : previous.stringPropertyNames()) {
|
||||
if (desired.containsKey(name)) continue;
|
||||
Path target = safe(contents, name);
|
||||
if (!Files.exists(target)) continue;
|
||||
if (written == 0 && removed == 0)
|
||||
atomicWrite(state.resolve("pending"), fingerprint.getBytes(StandardCharsets.UTF_8));
|
||||
backup(target, backup, name);
|
||||
Files.delete(target);
|
||||
removed++;
|
||||
}
|
||||
store(state.resolve("managed.properties"), managed);
|
||||
needsBuild |= written > 0 || removed > 0;
|
||||
if (needsBuild && written == 0 && removed == 0)
|
||||
atomicWrite(state.resolve("pending"), fingerprint.getBytes(StandardCharsets.UTF_8));
|
||||
return new Result(fingerprint, owners.size(), written, removed, needsBuild);
|
||||
}
|
||||
|
||||
public void confirmed(String fingerprint) throws IOException {
|
||||
Properties built = new Properties();
|
||||
built.setProperty("fingerprint", fingerprint);
|
||||
store(state.resolve("built.properties"), built);
|
||||
Files.deleteIfExists(state.resolve("pending"));
|
||||
}
|
||||
|
||||
public static boolean validPack(Path path, String fingerprint) {
|
||||
if (!Files.isRegularFile(path)) return false;
|
||||
try (var zip = new ZipFile(path.toFile())) {
|
||||
var entry = zip.getEntry(MARKER);
|
||||
if (entry == null || zip.getEntry("pack.mcmeta") == null) return false;
|
||||
try (var in = zip.getInputStream(entry)) {
|
||||
String json = new String(in.readAllBytes(), StandardCharsets.UTF_8);
|
||||
return json.contains("\"" + fingerprint + "\"");
|
||||
}
|
||||
} catch (IOException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] marker(String fingerprint) {
|
||||
return ("{\"astrapacks.build\":\"" + fingerprint + "\"}\n")
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private void backup(Path source, String backup, String name) throws IOException {
|
||||
atomicWrite(safe(state, backup + "/" + name), Files.readAllBytes(source));
|
||||
}
|
||||
|
||||
static Path safe(Path root, String name) throws IOException {
|
||||
if (name.isBlank()
|
||||
|| 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);
|
||||
root = root.toAbsolutePath().normalize();
|
||||
Path target = root.resolve(name).normalize();
|
||||
if (!target.startsWith(root))
|
||||
throw new IOException("Resource escapes content root: " + name);
|
||||
for (Path part = target; part != null; part = part.getParent())
|
||||
if (Files.isSymbolicLink(part))
|
||||
throw new IOException("Symbolic links are not supported: " + part);
|
||||
return target;
|
||||
}
|
||||
|
||||
static void atomicWrite(Path target, byte[] bytes) throws IOException {
|
||||
Files.createDirectories(target.getParent());
|
||||
Path temp = Files.createTempFile(target.getParent(), ".astra-", ".tmp");
|
||||
try {
|
||||
Files.write(temp, bytes);
|
||||
try {
|
||||
Files.move(
|
||||
temp,
|
||||
target,
|
||||
StandardCopyOption.ATOMIC_MOVE,
|
||||
StandardCopyOption.REPLACE_EXISTING);
|
||||
} catch (AtomicMoveNotSupportedException e) {
|
||||
Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
} finally {
|
||||
Files.deleteIfExists(temp);
|
||||
}
|
||||
}
|
||||
|
||||
static Properties read(Path path) throws IOException {
|
||||
Properties result = new Properties();
|
||||
if (Files.exists(path))
|
||||
try (var in = Files.newInputStream(path)) {
|
||||
result.load(in);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
static void store(Path path, Properties props) throws IOException {
|
||||
var bytes = new ByteArrayOutputStream();
|
||||
props.store(bytes, "Managed by AstraPacks");
|
||||
atomicWrite(path, bytes.toByteArray());
|
||||
}
|
||||
|
||||
static MessageDigest sha256() {
|
||||
try {
|
||||
return MessageDigest.getInstance("SHA-256");
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
static String hash(byte[] bytes) {
|
||||
return HexFormat.of().formatHex(sha256().digest(bytes));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package online.astradev.packs;
|
||||
|
||||
import com.google.gson.*;
|
||||
import java.io.*;
|
||||
import java.net.http.*;
|
||||
import java.time.Duration;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.security.*;
|
||||
import java.util.*;
|
||||
import java.util.zip.*;
|
||||
|
||||
/** Deterministic, bounded build. Immutable published ZIPs remain valid during later builds. */
|
||||
public final class PackBuilder {
|
||||
public record Pack(Path path, String sha1, int files, long bytes) {}
|
||||
private record Asset(byte[] data, String owner) {}
|
||||
private final PackConfig config;
|
||||
private final SortedMap<String, Asset> assets = new TreeMap<>();
|
||||
private long total;
|
||||
public PackBuilder(PackConfig config) { this.config = config; }
|
||||
|
||||
public Pack build(Path root, String resourceVersion) throws IOException {
|
||||
for (String source : config.build.sources) {
|
||||
Path path = root.resolve(source).toAbsolutePath().normalize();
|
||||
if (!Files.exists(path)) throw new IOException("Source does not exist: " + path);
|
||||
if (Files.isDirectory(path)) directory(path); else archive(path, false);
|
||||
}
|
||||
if (config.build.scanModJars && Files.isDirectory(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);
|
||||
}
|
||||
}
|
||||
JsonObject pack = new JsonObject();
|
||||
// 26.2 uses major/minor resource-pack versions.
|
||||
JsonElement version = JsonParser.parseString(resourceVersion);
|
||||
pack.add("min_format", version); pack.add("max_format", version.deepCopy());
|
||||
pack.addProperty("description", config.build.description);
|
||||
JsonObject meta = new JsonObject(); 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");
|
||||
Files.createDirectories(output);
|
||||
Path temp = Files.createTempFile(output, "build-", ".tmp");
|
||||
try {
|
||||
try (var zip = new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(temp)))) {
|
||||
for (var item : assets.entrySet()) {
|
||||
ZipEntry entry = new ZipEntry(item.getKey()); entry.setTime(0);
|
||||
zip.putNextEntry(entry); zip.write(item.getValue().data()); zip.closeEntry();
|
||||
}
|
||||
}
|
||||
String hash = hash(temp, "SHA-1");
|
||||
Path destination = output.resolve(hash + ".zip");
|
||||
if (!Files.exists(destination)) Files.move(temp, destination, StandardCopyOption.ATOMIC_MOVE);
|
||||
else if (!hash(destination, "SHA-1").equals(hash))
|
||||
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));
|
||||
return new Pack(destination, hash, assets.size(), Files.size(destination));
|
||||
} finally { Files.deleteIfExists(temp); }
|
||||
}
|
||||
public static Pack previous(Path root, PackConfig config) throws IOException {
|
||||
Path output = config.storage(root).resolve("output");
|
||||
try {
|
||||
JsonObject info = JsonParser.parseString(Files.readString(output.resolve("current.json"))).getAsJsonObject();
|
||||
String sha1 = info.get("sha1").getAsString();
|
||||
if (!sha1.matches("[a-f0-9]{40}")) throw new IOException("Invalid pack hash");
|
||||
Path path = output.resolve(sha1 + ".zip");
|
||||
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));
|
||||
} catch (RuntimeException e) { throw new IOException("Invalid previous build", e); }
|
||||
}
|
||||
private void directory(Path root) throws IOException {
|
||||
if (Files.isSymbolicLink(root)) throw new IOException("Symlink source: " + root);
|
||||
try (var walk = Files.walk(root)) {
|
||||
for (Path p : walk.sorted().toList()) {
|
||||
if (Files.isSymbolicLink(p)) throw new IOException("Symlink resource: " + p);
|
||||
if (!Files.isRegularFile(p)) continue;
|
||||
String name = root.relativize(p).toString().replace('\\', '/');
|
||||
// A source is a pack root, or a directory of named pack roots.
|
||||
if (!isResource(name)) {
|
||||
int slash = name.indexOf('/');
|
||||
if (slash >= 0 && isResource(name.substring(slash + 1))) name = name.substring(slash + 1);
|
||||
else if (name.endsWith(".zip")) { archive(p, false); continue; }
|
||||
else continue;
|
||||
}
|
||||
try (var in = Files.newInputStream(p)) { add(name, in, p.toString()); }
|
||||
}
|
||||
}
|
||||
}
|
||||
private void archive(Path path, boolean mod) throws IOException {
|
||||
try (var zip = new ZipFile(path.toFile())) {
|
||||
String prefix = "";
|
||||
if (mod) {
|
||||
var descriptor = zip.getEntry("astra-pack.properties");
|
||||
if (descriptor == null) return;
|
||||
Properties props = new Properties();
|
||||
try (var in = zip.getInputStream(descriptor)) { props.load(in); }
|
||||
String schema = props.getProperty("schema", "");
|
||||
if (schema.equals("2")) prefix = "astra-resourcepack/";
|
||||
else throw new IOException("Invalid AstraPacks bundle descriptor: " + path);
|
||||
}
|
||||
for (var entries = zip.entries(); entries.hasMoreElements();) {
|
||||
ZipEntry entry = entries.nextElement();
|
||||
if (entry.isDirectory() || !entry.getName().startsWith(prefix)) continue;
|
||||
String name = entry.getName().substring(prefix.length());
|
||||
if (!isResource(name)) continue;
|
||||
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 void add(String name, InputStream in, String owner) throws IOException {
|
||||
PackFiles.safe(Path.of("."), name);
|
||||
int limit = config.build.maxFileMiB * 1024 * 1024;
|
||||
byte[] bytes = in.readNBytes(limit + 1);
|
||||
if (bytes.length > limit) throw new IOException("Resource exceeds maxFileMiB: " + owner);
|
||||
total += bytes.length;
|
||||
if (total > config.build.maxTotalMiB * 1024L * 1024L) throw new IOException("Sources exceed maxTotalMiB");
|
||||
Asset old = assets.get(name);
|
||||
if (old != null && !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));
|
||||
if (assets.size() > config.build.maxFiles) throw new IOException("Too many resources");
|
||||
}
|
||||
public static String hash(Path file, String algorithm) throws IOException {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance(algorithm);
|
||||
try (var in = new DigestInputStream(Files.newInputStream(file), digest)) { in.transferTo(OutputStream.nullOutputStream()); }
|
||||
return HexFormat.of().formatHex(digest.digest());
|
||||
} catch (NoSuchAlgorithmException e) { throw new AssertionError(e); }
|
||||
}
|
||||
static void verifyExternal(PackConfig config, PackBuilder.Pack pack) throws IOException {
|
||||
if (!config.hosting.mode.equals("no_host") || !config.delivery.sendOnJoin) return;
|
||||
Path tmp = Files.createTempFile(pack.path().getParent(), "external-", ".tmp");
|
||||
try (HttpClient client = HttpClient.newBuilder().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.
|
||||
HttpResponse<byte[]> response = client.send(request, info -> HttpResponse.BodySubscribers.limiting(HttpResponse.BodySubscribers.ofByteArray(), pack.bytes() + 1));
|
||||
if (response.statusCode() != 200) throw new IOException("External pack HTTP " + response.statusCode());
|
||||
Files.write(tmp, response.body());
|
||||
if (!PackBuilder.hash(tmp, "SHA-1").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); }
|
||||
finally { Files.deleteIfExists(tmp); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package online.astradev.packs;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
|
||||
/** Server-local configuration, deliberately never synchronized to clients. */
|
||||
public final class PackConfig {
|
||||
public static final Gson JSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
|
||||
public boolean enabled = true;
|
||||
public Build build = new Build();
|
||||
public Hosting hosting = new Hosting();
|
||||
public Delivery delivery = new Delivery();
|
||||
public Messages messages = new Messages();
|
||||
public static final class Build {
|
||||
public String storageDirectory = "astrapacks";
|
||||
public List<String> sources = new ArrayList<>(List.of("astrapacks/contents"));
|
||||
public boolean scanModJars = true;
|
||||
public boolean onStartup = true;
|
||||
public boolean resendAfterBuild = true;
|
||||
public String description = "AstraDev — общий серверный ресурспак";
|
||||
public String conflictPolicy = "error";
|
||||
public int maxFileMiB = 32;
|
||||
public int maxTotalMiB = 256;
|
||||
public int maxFiles = 50000;
|
||||
}
|
||||
public static final class Hosting {
|
||||
public String mode = "simple_self_host";
|
||||
public String publicAddress = "auto";
|
||||
public String bindAddress = "0.0.0.0";
|
||||
public int port = 8163;
|
||||
public String externalUrl = "";
|
||||
public boolean blockNonGameRequests = true;
|
||||
public int maxDownloadsPerIp = 5;
|
||||
public int maxConcurrentDownloads = 32;
|
||||
public int maxSpeedMiBPerSecond = 30;
|
||||
public int tokenLifetimeSeconds = 600;
|
||||
}
|
||||
public static final class Delivery {
|
||||
public boolean sendOnJoin = true;
|
||||
public boolean required = true;
|
||||
public boolean kickOnFailure = true;
|
||||
public int timeoutSeconds = 120;
|
||||
public int retries = 1;
|
||||
public boolean logStatus = true;
|
||||
}
|
||||
public static final class Messages {
|
||||
public String prompt = "&6Привет, {player}!\\n&fДля игры на сервере необходим ресурспак AstraDev.\\n&aНажми «Продолжить», чтобы загрузить его.";
|
||||
public String declined = "&cДля входа необходимо принять ресурспак сервера.\\n&fВ настройках этого сервера включи «Наборы ресурсов сервера» и подключись снова.";
|
||||
public String failed = "&cНе удалось загрузить ресурспак сервера.\\n&fПопробуй подключиться ещё раз. Если ошибка повторится, сообщи администрации.";
|
||||
public String timeout = "&cВремя ожидания ресурспака истекло. Попробуй подключиться снова.";
|
||||
public String unavailable = "&cРесурспак сервера пока недоступен. Попробуй зайти позже.";
|
||||
public String loaded = "&aРесурспак AstraDev загружен.";
|
||||
}
|
||||
public static PackConfig load(Path path) throws IOException {
|
||||
if (!Files.exists(path)) {
|
||||
PackFiles.atomicWrite(path, (JSON.toJson(new PackConfig()) + "\n").getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
try {
|
||||
PackConfig config = JSON.fromJson(Files.readString(path), PackConfig.class);
|
||||
if (config == null) throw new IllegalArgumentException("Empty config");
|
||||
config.validate();
|
||||
return config;
|
||||
} catch (RuntimeException e) {
|
||||
throw new IOException("Invalid " + path + ": " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
public void validate() {
|
||||
Objects.requireNonNull(build); Objects.requireNonNull(hosting);
|
||||
Objects.requireNonNull(delivery); Objects.requireNonNull(messages);
|
||||
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");
|
||||
if (!Set.of("error", "last_wins").contains(build.conflictPolicy))
|
||||
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()))
|
||||
throw new IllegalArgumentException("Invalid build paths");
|
||||
Objects.requireNonNull(build.description);
|
||||
range(build.maxFileMiB, 1, 128, "maxFileMiB");
|
||||
range(build.maxTotalMiB, build.maxFileMiB, 1024, "maxTotalMiB");
|
||||
range(build.maxFiles, 1, 200000, "maxFiles");
|
||||
range(hosting.port, 1, 65535, "port");
|
||||
range(hosting.maxDownloadsPerIp, 1, 100, "maxDownloadsPerIp");
|
||||
range(hosting.maxConcurrentDownloads, 1, 256, "maxConcurrentDownloads");
|
||||
range(hosting.maxSpeedMiBPerSecond, 1, 1024, "maxSpeedMiBPerSecond");
|
||||
range(hosting.tokenLifetimeSeconds, 30, 86400, "tokenLifetimeSeconds");
|
||||
range(delivery.timeoutSeconds, 10, 3600, "timeoutSeconds");
|
||||
range(delivery.retries, 0, 5, "retries");
|
||||
if (enabled && delivery.required && !delivery.sendOnJoin)
|
||||
throw new IllegalArgumentException("required needs sendOnJoin=true");
|
||||
if (!hosting.publicAddress.equals("auto") && validateUrl(hosting.publicAddress).getQuery() != null)
|
||||
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");
|
||||
if (hosting.mode.equals("no_host") && enabled && delivery.sendOnJoin) validateUrl(hosting.externalUrl);
|
||||
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) {
|
||||
URI uri = URI.create(value);
|
||||
if (!("http".equals(uri.getScheme()) || "https".equals(uri.getScheme())) || uri.getHost() == null
|
||||
|| uri.getUserInfo() != null || uri.getFragment() != null)
|
||||
throw new IllegalArgumentException("Expected a direct http(s) URL: " + value);
|
||||
return uri;
|
||||
}
|
||||
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);
|
||||
}
|
||||
public Path storage(Path root) { return root.resolve(build.storageDirectory).toAbsolutePath().normalize(); }
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package online.astradev.packs;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.util.Arrays;
|
||||
|
||||
final class PackFiles {
|
||||
private PackFiles() {}
|
||||
static Path safe(Path root, String name) throws IOException {
|
||||
if (name.isBlank() || 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);
|
||||
root = root.toAbsolutePath().normalize();
|
||||
Path target = root.resolve(name).normalize();
|
||||
if (!target.startsWith(root)) throw new IOException("Resource escapes content root: " + name);
|
||||
for (Path part = target; part != null; part = part.getParent())
|
||||
if (Files.isSymbolicLink(part)) throw new IOException("Symbolic links are not supported: " + part);
|
||||
return target;
|
||||
}
|
||||
static void atomicWrite(Path target, byte[] bytes) throws IOException {
|
||||
Files.createDirectories(target.getParent());
|
||||
Path temp = Files.createTempFile(target.getParent(), ".astra-", ".tmp");
|
||||
try {
|
||||
Files.write(temp, bytes);
|
||||
try { Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); }
|
||||
catch (AtomicMoveNotSupportedException e) { Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING); }
|
||||
} finally { Files.deleteIfExists(temp); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package online.astradev.packs;
|
||||
|
||||
import io.netty.bootstrap.ServerBootstrap;
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.channel.*;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.socket.SocketChannel;
|
||||
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
||||
import io.netty.handler.codec.ByteToMessageDecoder;
|
||||
import io.netty.handler.codec.http.*;
|
||||
import io.netty.handler.stream.ChunkedNioFile;
|
||||
import io.netty.handler.stream.ChunkedWriteHandler;
|
||||
import io.netty.handler.timeout.ReadTimeoutHandler;
|
||||
import io.netty.handler.traffic.ChannelTrafficShapingHandler;
|
||||
import java.io.IOException;
|
||||
import java.net.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/** Only immutable pack artifacts are exposed; no directory or arbitrary file routes. */
|
||||
public final class PackHost implements AutoCloseable {
|
||||
private record Grant(String hash, long expires) {}
|
||||
private final PackConfig.Hosting config;
|
||||
private final ConcurrentMap<String, Grant> grants = new ConcurrentHashMap<>();
|
||||
private final ConcurrentMap<String, Path> published = new ConcurrentHashMap<>();
|
||||
private final Map<String, Integer> downloads = new HashMap<>();
|
||||
private int active;
|
||||
private EventLoopGroup group;
|
||||
private Channel listening;
|
||||
public PackHost(PackConfig.Hosting config) { this.config = config; }
|
||||
public void publish(PackBuilder.Pack pack) { published.put(pack.sha1(), pack.path()); }
|
||||
public String issuePath(PackBuilder.Pack pack) {
|
||||
String path = "/astrapacks/" + pack.sha1() + ".zip";
|
||||
if (!config.blockNonGameRequests) return path;
|
||||
long now = System.currentTimeMillis();
|
||||
grants.entrySet().removeIf(e -> e.getValue().expires() < now);
|
||||
if (grants.size() >= 10000) throw new IllegalStateException("Too many resource-pack download grants");
|
||||
String token = UUID.randomUUID().toString();
|
||||
grants.put(token, new Grant(pack.sha1(), now + config.tokenLifetimeSeconds * 1000L));
|
||||
return path + "?token=" + token;
|
||||
}
|
||||
public void start() throws InterruptedException {
|
||||
if (!config.mode.equals("self_host")) return;
|
||||
group = new NioEventLoopGroup(2);
|
||||
try {
|
||||
listening = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class)
|
||||
.childHandler(new ChannelInitializer<SocketChannel>() {
|
||||
@Override protected void initChannel(SocketChannel ch) { installHttp(ch.pipeline()); }
|
||||
}).bind(config.bindAddress, config.port).sync().channel();
|
||||
} catch (Throwable e) { close(); throw e; }
|
||||
}
|
||||
public void installSniffer(ChannelPipeline pipeline) { pipeline.addFirst("astrapacks_detect", new Sniffer()); }
|
||||
private void installHttp(ChannelPipeline p) {
|
||||
p.addLast("astrapacks_timeout", new ReadTimeoutHandler(30));
|
||||
p.addLast("astrapacks_http", new HttpServerCodec(4096, 8192, 8192));
|
||||
p.addLast("astrapacks_aggregate", new HttpObjectAggregator(4096));
|
||||
p.addLast("astrapacks_speed", new ChannelTrafficShapingHandler(config.maxSpeedMiBPerSecond * 1024L * 1024L, 0));
|
||||
p.addLast("astrapacks_chunks", new ChunkedWriteHandler());
|
||||
p.addLast("astrapacks_download", new Download());
|
||||
}
|
||||
private final class Sniffer extends ByteToMessageDecoder {
|
||||
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
|
||||
if (in.readableBytes() < 4) return;
|
||||
int start = in.readerIndex();
|
||||
boolean http = (in.getByte(start) == 'G' && in.getByte(start + 1) == 'E' && in.getByte(start + 2) == 'T' && in.getByte(start + 3) == ' ')
|
||||
|| (in.getByte(start) == 'H' && in.getByte(start + 1) == 'E' && in.getByte(start + 2) == 'A' && in.getByte(start + 3) == 'D');
|
||||
if (http) {
|
||||
ChannelPipeline p = ctx.pipeline();
|
||||
for (String name : new ArrayList<>(p.names()))
|
||||
if (p.get(name) != null && p.get(name) != this) p.remove(name);
|
||||
installHttp(p);
|
||||
}
|
||||
// Removal forwards all accumulated bytes to the selected protocol decoder.
|
||||
ctx.pipeline().remove(this);
|
||||
}
|
||||
}
|
||||
private synchronized boolean acquire(String ip) {
|
||||
int count = downloads.getOrDefault(ip, 0);
|
||||
if (count >= config.maxDownloadsPerIp || active >= config.maxConcurrentDownloads) return false;
|
||||
downloads.put(ip, count + 1); active++; return true;
|
||||
}
|
||||
private synchronized void release(String ip) {
|
||||
downloads.computeIfPresent(ip, (key, count) -> count <= 1 ? null : count - 1); active--;
|
||||
}
|
||||
private final class Download extends SimpleChannelInboundHandler<FullHttpRequest> {
|
||||
private boolean handled;
|
||||
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws IOException {
|
||||
if (handled) return;
|
||||
handled = true;
|
||||
if (!request.decoderResult().isSuccess()) { error(ctx, HttpResponseStatus.BAD_REQUEST); return; }
|
||||
if (!request.method().equals(HttpMethod.GET) && !request.method().equals(HttpMethod.HEAD)) {
|
||||
error(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED); return;
|
||||
}
|
||||
QueryStringDecoder uri = new QueryStringDecoder(request.uri());
|
||||
String path = uri.path();
|
||||
if (!path.matches("/astrapacks/[a-f0-9]{40}\\.zip")) { error(ctx, HttpResponseStatus.NOT_FOUND); return; }
|
||||
String hash = path.substring(12, 52);
|
||||
Path file = published.get(hash);
|
||||
if (file == null || !Files.isRegularFile(file)) { error(ctx, HttpResponseStatus.NOT_FOUND); return; }
|
||||
if (config.blockNonGameRequests) {
|
||||
String token = uri.parameters().getOrDefault("token", List.of("")).getFirst();
|
||||
Grant grant = grants.get(token);
|
||||
if (grant == null || grant.expires() < System.currentTimeMillis() || !grant.hash().equals(hash)) {
|
||||
error(ctx, HttpResponseStatus.FORBIDDEN); return;
|
||||
}
|
||||
}
|
||||
String ip = ((InetSocketAddress)ctx.channel().remoteAddress()).getAddress().getHostAddress();
|
||||
if (!acquire(ip)) { error(ctx, HttpResponseStatus.TOO_MANY_REQUESTS); return; }
|
||||
AtomicBoolean released = new AtomicBoolean();
|
||||
Runnable cleanup = () -> { if (released.compareAndSet(false, true)) release(ip); };
|
||||
ctx.channel().closeFuture().addListener(f -> cleanup.run());
|
||||
ChunkedNioFile stream = null;
|
||||
try {
|
||||
long size = Files.size(file);
|
||||
if (request.method().equals(HttpMethod.GET)) stream = new ChunkedNioFile(file.toFile(), 65536);
|
||||
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
|
||||
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/zip");
|
||||
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, size);
|
||||
response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
|
||||
response.headers().set(HttpHeaderNames.CACHE_CONTROL, "private, max-age=31536000, immutable");
|
||||
response.headers().set(HttpHeaderNames.ETAG, '"' + hash + '"');
|
||||
ctx.write(response);
|
||||
if (stream != null) ctx.write(new HttpChunkedInput(stream));
|
||||
else ctx.write(LastHttpContent.EMPTY_LAST_CONTENT);
|
||||
ctx.writeAndFlush(io.netty.buffer.Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
|
||||
} catch (Throwable e) {
|
||||
if (stream != null) try { stream.close(); } catch (Exception ignored) { }
|
||||
cleanup.run(); ctx.close();
|
||||
}
|
||||
}
|
||||
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { ctx.close(); }
|
||||
}
|
||||
private static void error(ChannelHandlerContext ctx, HttpResponseStatus status) {
|
||||
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
|
||||
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);
|
||||
response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
|
||||
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
|
||||
}
|
||||
@Override public void close() {
|
||||
if (listening != null) listening.close().awaitUninterruptibly();
|
||||
if (group != null) group.shutdownGracefully(0, 2, TimeUnit.SECONDS).awaitUninterruptibly();
|
||||
grants.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
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.network.Connection;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.protocol.common.ServerboundResourcePackPacket;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
|
||||
import online.astradev.packs.mixin.CommonAccessor;
|
||||
|
||||
public final class PackRuntime implements AutoCloseable {
|
||||
public static volatile PackRuntime INSTANCE;
|
||||
private final MinecraftServer server;
|
||||
private final Path root;
|
||||
private final Path configPath;
|
||||
private volatile PackConfig config;
|
||||
private volatile PackBuilder.Pack current;
|
||||
private final PackHost host;
|
||||
private final Map<ServerCommonPacketListenerImpl, PackSession> sessions = 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 AtomicBoolean busy = new AtomicBoolean();
|
||||
private volatile boolean closed;
|
||||
public PackRuntime(MinecraftServer server, Path root, Path configPath, PackConfig config) {
|
||||
this.server = server; this.root = root; this.configPath = configPath; this.config = config;
|
||||
this.host = new PackHost(config.hosting);
|
||||
}
|
||||
public void start() throws Exception {
|
||||
if (!config.enabled) return;
|
||||
if (server.getServerResourcePack().isPresent())
|
||||
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.
|
||||
Files.createDirectories(root.resolve("astrapacks/contents"));
|
||||
PackBuilder.Pack candidate;
|
||||
try { 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);
|
||||
try { 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) {
|
||||
try { 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();
|
||||
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 PackHost host() { return host; }
|
||||
public PackSession session(ServerCommonPacketListenerImpl listener) {
|
||||
PackSession session = new PackSession(this, listener);
|
||||
PackSession old = sessions.put(listener, session);
|
||||
if (old != null) old.replace();
|
||||
return session;
|
||||
}
|
||||
public boolean intercept(ServerCommonPacketListenerImpl listener, ServerboundResourcePackPacket packet) {
|
||||
if (!config.enabled) return false;
|
||||
// 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.
|
||||
server.execute(() -> {
|
||||
PackSession session = sessions.get(listener);
|
||||
if (session != null) session.response(packet);
|
||||
});
|
||||
return true;
|
||||
}
|
||||
public void tick() {
|
||||
sessions.entrySet().removeIf(entry -> {
|
||||
if (!((CommonAccessor)entry.getKey()).astrapacks$connection().isConnected()) {
|
||||
welcome.remove(entry.getKey().getOwner().id());
|
||||
return true;
|
||||
}
|
||||
entry.getValue().tick(); return false;
|
||||
});
|
||||
}
|
||||
public void loaded(ServerCommonPacketListenerImpl listener, String message) {
|
||||
if (listener instanceof net.minecraft.server.network.ServerGamePacketListenerImpl game) {
|
||||
if (!message.isBlank()) game.player.sendSystemMessage(PackText.of(message, listener.getOwner().name()));
|
||||
} else welcome.put(listener.getOwner().id(), message);
|
||||
}
|
||||
public void welcome(net.minecraft.server.level.ServerPlayer player) {
|
||||
String text = welcome.remove(player.getUUID());
|
||||
if (text != null && !text.isBlank()) player.sendSystemMessage(PackText.of(text, player.getGameProfile().name()));
|
||||
}
|
||||
public String url(ServerCommonPacketListenerImpl listener, PackBuilder.Pack pack) {
|
||||
if (config.hosting.mode.equals("no_host")) return config.hosting.externalUrl;
|
||||
Connection connection = ((CommonAccessor)listener).astrapacks$connection();
|
||||
String base = config.hosting.publicAddress;
|
||||
if (base.equals("auto")) {
|
||||
String address = ((ConnectionData)connection).astrapacks$host();
|
||||
if (address == null || address.isBlank()) throw new IllegalArgumentException("Cannot determine server address; set hosting.publicAddress");
|
||||
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);
|
||||
}
|
||||
public void rebuild(CommandSourceStack source, boolean reload, boolean publishOnly) {
|
||||
if (!busy.compareAndSet(false, true)) { source.sendFailure(Component.literal("Сборка AstraPacks уже выполняется.")); return; }
|
||||
source.sendSuccess(() -> Component.literal("AstraPacks: проверка и подготовка ресурспака…"), false);
|
||||
worker.submit(() -> {
|
||||
try {
|
||||
PackConfig next = reload ? PackConfig.load(configPath) : config;
|
||||
if (next.enabled != config.enabled || !PackConfig.JSON.toJson(next.hosting).equals(PackConfig.JSON.toJson(config.hosting)))
|
||||
throw new IOException("Изменение enabled или hosting требует перезапуска сервера.");
|
||||
PackBuilder.Pack pack = publishOnly ? PackBuilder.previous(root, next) : new PackBuilder(next).build(root, "[88,0]");
|
||||
PackBuilder.verifyExternal(next, pack);
|
||||
server.execute(() -> {
|
||||
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) {
|
||||
AstraPacks.LOG.error("Pack build/publication failed; active pack retained", e);
|
||||
server.execute(() -> source.sendFailure(Component.literal("AstraPacks: " + e.getMessage() + " Рабочий пак сохранён.")));
|
||||
} finally { busy.set(false); }
|
||||
});
|
||||
}
|
||||
public void resendAll() {
|
||||
for (var player : server.getPlayerList().getPlayers()) session(player.connection).start(player.connection::send);
|
||||
}
|
||||
public String status() {
|
||||
return "AstraPacks " + config.hosting.mode + ", required=" + config.delivery.required
|
||||
+ ", build=" + busy.get() + ", pack=" + (current == null ? "UNAVAILABLE" : current.path() + " (" + current.files() + " files)");
|
||||
}
|
||||
@Override public void close() { closed = true; worker.shutdownNow(); host.close(); sessions.clear(); welcome.clear(); }
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package online.astradev.packs;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.Consumer;
|
||||
import net.minecraft.network.protocol.Packet;
|
||||
import net.minecraft.network.protocol.common.*;
|
||||
import net.minecraft.server.network.*;
|
||||
|
||||
/** Configuration only completes on SUCCESSFULLY_LOADED, never merely ACCEPTED or DOWNLOADED. */
|
||||
public final class PackSession implements ConfigurationTask {
|
||||
public static final Type TYPE = new Type("astrapacks:resource_pack");
|
||||
private final PackRuntime runtime;
|
||||
final ServerCommonPacketListenerImpl listener;
|
||||
private final PackConfig config;
|
||||
private final PackBuilder.Pack pack;
|
||||
private UUID id;
|
||||
private long deadline;
|
||||
private int retries;
|
||||
private boolean done;
|
||||
private boolean failed;
|
||||
private boolean started;
|
||||
public PackSession(PackRuntime runtime, ServerCommonPacketListenerImpl listener) {
|
||||
this.runtime = runtime; this.listener = listener;
|
||||
this.config = runtime.config(); this.pack = runtime.current();
|
||||
}
|
||||
@Override public Type type() { return TYPE; }
|
||||
@Override public void start(Consumer<Packet<?>> sender) {
|
||||
started = true;
|
||||
if (pack == null) {
|
||||
if (config.delivery.required) disconnect(config.messages.unavailable); else done = true;
|
||||
return;
|
||||
}
|
||||
send();
|
||||
}
|
||||
private void send() {
|
||||
if (id != null) listener.send(new ClientboundResourcePackPopPacket(Optional.of(id)));
|
||||
id = UUID.randomUUID();
|
||||
deadline = System.nanoTime() + config.delivery.timeoutSeconds * 1_000_000_000L;
|
||||
try {
|
||||
listener.send(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) {
|
||||
AstraPacks.LOG.error("Cannot send resource pack to {}", player(), e);
|
||||
if (config.delivery.required || config.delivery.kickOnFailure) disconnect(config.messages.unavailable); else done = true;
|
||||
}
|
||||
}
|
||||
public void response(ServerboundResourcePackPacket packet) {
|
||||
if (!started || failed || !packet.id().equals(id)) return;
|
||||
if (config.delivery.logStatus) AstraPacks.LOG.info("Resource pack {}: {} ({})", player(), packet.action(), pack.sha1());
|
||||
if (done) return;
|
||||
switch (packet.action()) {
|
||||
case SUCCESSFULLY_LOADED -> { done = true; runtime.loaded(listener, config.messages.loaded); }
|
||||
case DECLINED -> { if (config.delivery.required) disconnect(config.messages.declined); else done = true; }
|
||||
case FAILED_DOWNLOAD, FAILED_RELOAD, INVALID_URL, DISCARDED -> {
|
||||
if (retries++ < config.delivery.retries) send();
|
||||
else if (config.delivery.required || config.delivery.kickOnFailure) disconnect(config.messages.failed);
|
||||
else done = true;
|
||||
}
|
||||
default -> { /* Accept/download progress does not extend the bounded deadline. */ }
|
||||
}
|
||||
}
|
||||
@Override public boolean tick() {
|
||||
if (started && !done && !failed && System.nanoTime() >= deadline) {
|
||||
if (config.delivery.required || config.delivery.kickOnFailure) disconnect(config.messages.timeout); else done = true;
|
||||
}
|
||||
return done;
|
||||
}
|
||||
public void replace() {
|
||||
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())); }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package online.astradev.packs;
|
||||
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.network.chat.*;
|
||||
|
||||
public final class PackText {
|
||||
private PackText() {}
|
||||
public static Component of(String text, String player) {
|
||||
text = text.replace("{player}", player).replace("\\n", "\n");
|
||||
MutableComponent result = Component.empty();
|
||||
Style style = Style.EMPTY;
|
||||
StringBuilder part = new StringBuilder();
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
char ch = text.charAt(i);
|
||||
if ((ch == '&' || ch == '§') && i + 1 < text.length()) {
|
||||
ChatFormatting code = ChatFormatting.getByCode(text.charAt(i + 1));
|
||||
if (code != null) {
|
||||
result.append(Component.literal(part.toString()).setStyle(style)); part.setLength(0);
|
||||
style = code == ChatFormatting.RESET ? Style.EMPTY : "0123456789abcdef".indexOf(Character.toLowerCase(text.charAt(i + 1))) >= 0 ? Style.EMPTY.applyFormat(code) : style.applyFormat(code);
|
||||
i++; continue;
|
||||
}
|
||||
}
|
||||
part.append(ch);
|
||||
}
|
||||
return result.append(Component.literal(part.toString()).setStyle(style));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package online.astradev.packs.mixin;
|
||||
|
||||
import net.minecraft.network.Connection;
|
||||
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.gen.Accessor;
|
||||
|
||||
@Mixin(ServerCommonPacketListenerImpl.class)
|
||||
public interface CommonAccessor {
|
||||
@Accessor("connection") Connection astrapacks$connection();
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package online.astradev.packs.mixin;
|
||||
|
||||
import net.minecraft.network.protocol.common.ServerboundResourcePackPacket;
|
||||
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
|
||||
import online.astradev.packs.PackRuntime;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
@Mixin(ServerCommonPacketListenerImpl.class)
|
||||
public abstract class CommonResponseMixin {
|
||||
@Inject(method = "handleResourcePackResponse", at = @At("HEAD"), cancellable = true)
|
||||
private void astrapacks$response(ServerboundResourcePackPacket packet, CallbackInfo ci) {
|
||||
PackRuntime runtime = PackRuntime.INSTANCE;
|
||||
if (runtime != null && runtime.intercept((ServerCommonPacketListenerImpl)(Object)this, packet)) ci.cancel();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package online.astradev.packs.mixin;
|
||||
|
||||
import net.minecraft.network.protocol.common.ServerboundResourcePackPacket;
|
||||
import net.minecraft.server.network.*;
|
||||
import online.astradev.packs.PackRuntime;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
@Mixin(ServerConfigurationPacketListenerImpl.class)
|
||||
public abstract class ConfigurationResponseMixin {
|
||||
@Inject(method = "handleResourcePackResponse", at = @At("HEAD"), cancellable = true)
|
||||
private void astrapacks$response(ServerboundResourcePackPacket packet, CallbackInfo ci) {
|
||||
PackRuntime runtime = PackRuntime.INSTANCE;
|
||||
if (runtime != null && runtime.intercept((ServerCommonPacketListenerImpl)(Object)this, packet)) ci.cancel();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package online.astradev.packs.mixin;
|
||||
|
||||
import io.netty.channel.ChannelPipeline;
|
||||
import net.minecraft.network.BandwidthDebugMonitor;
|
||||
import net.minecraft.network.Connection;
|
||||
import net.minecraft.network.protocol.PacketFlow;
|
||||
import online.astradev.packs.PackRuntime;
|
||||
import online.astradev.packs.ConnectionData;
|
||||
import org.spongepowered.asm.mixin.*;
|
||||
import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
@Mixin(Connection.class)
|
||||
public abstract class ConnectionMixin implements ConnectionData {
|
||||
@Unique private String astrapacks$serverHost;
|
||||
public String astrapacks$host() { return astrapacks$serverHost; }
|
||||
public void astrapacks$host(String host) { astrapacks$serverHost = host; }
|
||||
@Inject(method = "configureSerialization", at = @At("RETURN"))
|
||||
private static void astrapacks$detectHttp(ChannelPipeline pipeline, PacketFlow flow, boolean local, BandwidthDebugMonitor monitor, CallbackInfo ci) {
|
||||
PackRuntime runtime = PackRuntime.INSTANCE;
|
||||
if (runtime != null && runtime.config().enabled && !local && flow == PacketFlow.SERVERBOUND
|
||||
&& runtime.config().hosting.mode.equals("simple_self_host")) runtime.host().installSniffer(pipeline);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package online.astradev.packs.mixin;
|
||||
|
||||
import net.minecraft.network.Connection;
|
||||
import online.astradev.packs.ConnectionData;
|
||||
import net.minecraft.network.protocol.handshake.ClientIntentionPacket;
|
||||
import net.minecraft.server.network.ServerHandshakePacketListenerImpl;
|
||||
import org.spongepowered.asm.mixin.*;
|
||||
import org.spongepowered.asm.mixin.injection.*;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
@Mixin(ServerHandshakePacketListenerImpl.class)
|
||||
public abstract class HandshakeMixin {
|
||||
@Shadow @Final private Connection connection;
|
||||
@Inject(method = "handleIntention", at = @At("HEAD"))
|
||||
private void astrapacks$rememberHost(ClientIntentionPacket packet, CallbackInfo ci) {
|
||||
String host = packet.hostName().split("\u0000", 2)[0];
|
||||
if (host.matches("[a-zA-Z0-9._:\\[\\]-]+")) ((ConnectionData)connection).astrapacks$host(host);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
modLoader="javafml"
|
||||
loaderVersion="[11,)"
|
||||
license="All Rights Reserved"
|
||||
[[mods]]
|
||||
modId="astrapacks"
|
||||
version="${version}"
|
||||
displayName="AstraPacks"
|
||||
description='''Server resource pack core for AstraDev.'''
|
||||
[[mixins]]
|
||||
config="astrapacks.mixins.json"
|
||||
[[dependencies.astrapacks]]
|
||||
modId="neoforge"
|
||||
type="required"
|
||||
versionRange="[26.2.0.79,26.3)"
|
||||
side="SERVER"
|
||||
[[dependencies.astrapacks]]
|
||||
modId="minecraft"
|
||||
type="required"
|
||||
versionRange="[26.2,26.3)"
|
||||
side="SERVER"
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"required": true,
|
||||
"package": "online.astradev.packs.mixin",
|
||||
"compatibilityLevel": "JAVA_25",
|
||||
"mixins": ["ConnectionMixin", "HandshakeMixin", "CommonAccessor", "CommonResponseMixin", "ConfigurationResponseMixin"],
|
||||
"injectors": { "defaultRequire": 1 }
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
name: AstraPacks
|
||||
version: '${version}'
|
||||
main: online.astradev.packs.AstraPacksPlugin
|
||||
api-version: '26.2'
|
||||
load: STARTUP
|
||||
loadbefore: [ItemsAdder, AstraArmorStatues, AstraBanners, AstraMonitor, AstraFertilizers]
|
||||
author: AstraDev
|
||||
description: Automatically installs bundled ItemsAdder content and builds the shared server resource pack.
|
||||
@@ -1,164 +0,0 @@
|
||||
package online.astradev.packs;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.zip.*;
|
||||
|
||||
class ContentSyncTest {
|
||||
@TempDir Path root;
|
||||
|
||||
Path contents() {
|
||||
return root.resolve("ItemsAdder/contents");
|
||||
}
|
||||
|
||||
Path state() {
|
||||
return root.resolve("AstraPacks");
|
||||
}
|
||||
|
||||
ContentSync sync() {
|
||||
return new ContentSync(contents(), state());
|
||||
}
|
||||
|
||||
void bundle(String filename, String owner, String folder, Map<String, String> files)
|
||||
throws Exception {
|
||||
try (var zip = new ZipOutputStream(Files.newOutputStream(root.resolve(filename)))) {
|
||||
entry(
|
||||
zip,
|
||||
"astra-pack.properties",
|
||||
"schema=1\nplugin=" + owner + "\nfolder=" + folder + "\n");
|
||||
for (var file : files.entrySet())
|
||||
entry(zip, ContentSync.PREFIX + folder + "/" + file.getKey(), file.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
void pack(String fingerprint) throws Exception {
|
||||
Path path = root.resolve("ItemsAdder/output/generated.zip");
|
||||
Files.createDirectories(path.getParent());
|
||||
try (var zip = new ZipOutputStream(Files.newOutputStream(path))) {
|
||||
entry(zip, "pack.mcmeta", "{}");
|
||||
entry(zip, ContentSync.MARKER, "{\"astrapacks.build\":\"" + fingerprint + "\"}");
|
||||
}
|
||||
}
|
||||
|
||||
static void entry(ZipOutputStream zip, String name, String text) throws Exception {
|
||||
zip.putNextEntry(new ZipEntry(name));
|
||||
zip.write(text.getBytes(StandardCharsets.UTF_8));
|
||||
zip.closeEntry();
|
||||
}
|
||||
|
||||
@Test
|
||||
void installRestartUpdateAndRemovalPreserveUnmanagedContent() throws Exception {
|
||||
bundle(
|
||||
"First.jar",
|
||||
"First",
|
||||
"first",
|
||||
Map.of("resourcepack/assets/first/items/a.json", "v1", "configs/old.yml", "old"));
|
||||
bundle("Second.jar", "Second", "second", Map.of("configs/items.yml", "items"));
|
||||
var first = sync().sync(root);
|
||||
assertEquals(2, first.modules());
|
||||
assertTrue(first.buildRequired());
|
||||
pack(first.fingerprint());
|
||||
sync().confirmed(first.fingerprint());
|
||||
var unchanged = sync().sync(root);
|
||||
assertEquals(0, unchanged.written());
|
||||
assertFalse(unchanged.buildRequired());
|
||||
Files.writeString(
|
||||
contents().resolve("first/resourcepack/assets/first/items/a.json"),
|
||||
"optimized by ItemsAdder");
|
||||
assertFalse(
|
||||
sync().sync(root).buildRequired(),
|
||||
"Do not undo ItemsAdder source optimization on every restart");
|
||||
Path custom = contents().resolve("first/configs/local.yml");
|
||||
Files.writeString(custom, "mine");
|
||||
Files.writeString(contents().resolve("first/configs/old.yml"), "edited by owner");
|
||||
bundle(
|
||||
"First.jar",
|
||||
"First",
|
||||
"first",
|
||||
Map.of("resourcepack/assets/first/items/a.json", "v2"));
|
||||
Files.delete(root.resolve("Second.jar"));
|
||||
var updated = sync().sync(root);
|
||||
assertTrue(updated.buildRequired());
|
||||
assertEquals(2, updated.removed());
|
||||
assertEquals(
|
||||
"v2",
|
||||
Files.readString(
|
||||
contents().resolve("first/resourcepack/assets/first/items/a.json")));
|
||||
assertEquals("mine", Files.readString(custom));
|
||||
try (var paths = Files.walk(state().resolve("backups"))) {
|
||||
assertTrue(
|
||||
paths.filter(Files::isRegularFile)
|
||||
.anyMatch(
|
||||
p -> {
|
||||
try {
|
||||
return Files.readString(p).equals("edited by owner");
|
||||
} catch (IOException e) {
|
||||
return false;
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void interruptedBuildRetriesAndMissingOutputIsRebuilt() throws Exception {
|
||||
bundle("One.jar", "One", "one", Map.of("configs/items.yml", "content"));
|
||||
var result = sync().sync(root);
|
||||
assertTrue(sync().sync(root).buildRequired());
|
||||
pack(result.fingerprint());
|
||||
assertTrue(
|
||||
sync().sync(root).buildRequired(), "ZIP alone must not clear an unconfirmed build");
|
||||
sync().confirmed(result.fingerprint());
|
||||
assertFalse(sync().sync(root).buildRequired());
|
||||
Files.delete(root.resolve("ItemsAdder/output/generated.zip"));
|
||||
assertTrue(sync().sync(root).buildRequired());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsTraversalAndDuplicateAssetsBeforeWriting() throws Exception {
|
||||
bundle("Unsafe.jar", "Unsafe", "unsafe", Map.of("../escape", "bad"));
|
||||
assertThrows(IOException.class, () -> sync().sync(root));
|
||||
assertFalse(Files.exists(contents()));
|
||||
Files.delete(root.resolve("Unsafe.jar"));
|
||||
bundle("One.jar", "One", "one", Map.of("resourcepack/assets/shared/items/a.json", "one"));
|
||||
bundle("Two.jar", "Two", "two", Map.of("resourcepack/assets/shared/items/a.json", "two"));
|
||||
assertThrows(IOException.class, () -> sync().sync(root));
|
||||
assertFalse(Files.exists(contents()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicatePluginVersionsFailBeforeReplacingFiles() throws Exception {
|
||||
bundle("One-1.jar", "One", "one", Map.of("configs/items.yml", "1"));
|
||||
bundle("One-2.jar", "One", "one", Map.of("configs/items.yml", "2"));
|
||||
assertThrows(IOException.class, () -> sync().sync(root));
|
||||
assertFalse(Files.exists(contents()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void itemsAdderUpgradeRebuildsUnchangedBundles() throws Exception {
|
||||
bundle("One.jar", "One", "one", Map.of("configs/items.yml", "content"));
|
||||
Path jar = root.resolve("ItemsAdder.jar");
|
||||
try (var zip = new ZipOutputStream(Files.newOutputStream(jar))) {
|
||||
entry(zip, "plugin.yml", "name: ItemsAdder\nversion: 1\n");
|
||||
}
|
||||
var installed = sync().sync(root);
|
||||
pack(installed.fingerprint());
|
||||
sync().confirmed(installed.fingerprint());
|
||||
assertFalse(sync().sync(root).buildRequired());
|
||||
|
||||
try (var zip = new ZipOutputStream(Files.newOutputStream(jar))) {
|
||||
entry(zip, "plugin.yml", "name: ItemsAdder\nversion: 2\n");
|
||||
}
|
||||
var upgraded = sync().sync(root);
|
||||
assertNotEquals(installed.fingerprint(), upgraded.fingerprint());
|
||||
assertTrue(upgraded.buildRequired());
|
||||
assertEquals("content", Files.readString(contents().resolve("one/configs/items.yml")));
|
||||
assertTrue(Files.exists(state().resolve("pending")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package online.astradev.packs;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.net.http.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.zip.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PackCoreTest {
|
||||
@TempDir Path root;
|
||||
private PackConfig config() throws IOException {
|
||||
PackConfig c = new PackConfig();
|
||||
Files.createDirectories(root.resolve("astrapacks/contents"));
|
||||
return c;
|
||||
}
|
||||
private void asset(String name, String text) throws IOException {
|
||||
Path p = root.resolve("astrapacks/contents/" + name);
|
||||
Files.createDirectories(p.getParent()); Files.writeString(p, text);
|
||||
}
|
||||
private static void zip(Path path, Map<String, String> files) throws IOException {
|
||||
Files.createDirectories(path.getParent());
|
||||
try (var z = new ZipOutputStream(Files.newOutputStream(path))) {
|
||||
for (var e : files.entrySet()) { z.putNextEntry(new ZipEntry(e.getKey())); z.write(e.getValue().getBytes(java.nio.charset.StandardCharsets.UTF_8)); z.closeEntry(); }
|
||||
}
|
||||
}
|
||||
@Test void deterministicAndDeletedResourcesDisappear() throws Exception {
|
||||
PackConfig c = config(); asset("assets/demo/lang/en_us.json", "{\"hello\":\"world\"}");
|
||||
var a = new PackBuilder(c).build(root, "[88,0]");
|
||||
var b = new PackBuilder(c).build(root, "[88,0]");
|
||||
assertEquals(a.sha1(), b.sha1());
|
||||
Files.delete(root.resolve("astrapacks/contents/assets/demo/lang/en_us.json"));
|
||||
var changed = new PackBuilder(c).build(root, "[88,0]");
|
||||
assertNotEquals(a.sha1(), changed.sha1());
|
||||
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")); }
|
||||
}
|
||||
@Test void conflictingSourcesPreservePreviousBuild() throws Exception {
|
||||
PackConfig c = config(); asset("one/assets/demo/test.txt", "a");
|
||||
var good = new PackBuilder(c).build(root, "[88,0]");
|
||||
asset("two/assets/demo/test.txt", "b");
|
||||
assertThrows(IOException.class, () -> new PackBuilder(c).build(root, "[88,0]"));
|
||||
assertEquals(good.sha1(), PackBuilder.previous(root, c).sha1());
|
||||
c.build.conflictPolicy = "last_wins";
|
||||
var newer = new PackBuilder(c).build(root, "[88,0]");
|
||||
try (var z = new ZipFile(newer.path().toFile())) { assertEquals("b", new String(z.getInputStream(z.getEntry("assets/demo/test.txt")).readAllBytes())); }
|
||||
}
|
||||
@Test void matchingDuplicatesAreAllowed() throws Exception {
|
||||
PackConfig c = config(); asset("one/assets/demo/test.txt", "a"); asset("two/assets/demo/test.txt", "a");
|
||||
assertEquals(2, new PackBuilder(c).build(root, "[88,0]").files());
|
||||
}
|
||||
@Test void unsafeZipEntryRejected() throws Exception {
|
||||
PackConfig c = config();
|
||||
zip(root.resolve("astrapacks/contents/bad.zip"), Map.of("assets/../../escape.txt", "bad"));
|
||||
assertThrows(IOException.class, () -> new PackBuilder(c).build(root, "[88,0]"));
|
||||
assertFalse(Files.exists(root.resolve("escape.txt")));
|
||||
}
|
||||
@Test void fileAndTotalLimits() throws Exception {
|
||||
PackConfig c = config(); c.build.maxFileMiB = 1;
|
||||
asset("assets/demo/large.txt", "x".repeat(1024 * 1024 + 1));
|
||||
assertThrows(IOException.class, () -> new PackBuilder(c).build(root, "[88,0]"));
|
||||
c.build.maxFileMiB = 2; c.build.maxTotalMiB = 1;
|
||||
assertThrows(IOException.class, () -> new PackBuilder(c).build(root, "[88,0]"));
|
||||
}
|
||||
@Test void modJarBundleOnlyExposesPackAssets() throws Exception {
|
||||
PackConfig c = config();
|
||||
zip(root.resolve("mods/example.jar"), Map.of("astra-pack.properties", "schema=2\n", "astra-resourcepack/assets/demo/test.txt", "hello", "secret.txt", "secret"));
|
||||
var pack = new PackBuilder(c).build(root, "[88,0]");
|
||||
try (var z = new ZipFile(pack.path().toFile())) { assertNotNull(z.getEntry("assets/demo/test.txt")); assertNull(z.getEntry("secret.txt")); }
|
||||
}
|
||||
@Test void invalidConfigIsNotSilentlyReplaced() throws Exception {
|
||||
Path path = root.resolve("config/astrapacks.json");
|
||||
PackConfig c = PackConfig.load(path); assertTrue(c.delivery.required);
|
||||
c.delivery.sendOnJoin = false; Files.writeString(path, PackConfig.JSON.toJson(c));
|
||||
assertThrows(IOException.class, () -> PackConfig.load(path));
|
||||
assertFalse(Files.readString(path).isEmpty());
|
||||
}
|
||||
@Test void noHostRequiresValidUrlWhenSending() throws Exception {
|
||||
PackConfig c = config(); c.hosting.mode = "no_host";
|
||||
assertThrows(IllegalArgumentException.class, c::validate);
|
||||
c.hosting.externalUrl = "https://example.com/pack.zip"; assertDoesNotThrow(c::validate);
|
||||
c.hosting.externalUrl = "file:///secret"; assertThrows(IllegalArgumentException.class, c::validate);
|
||||
}
|
||||
@Test void corruptedPreviousZipRejected() throws Exception {
|
||||
PackConfig c = config(); var pack = new PackBuilder(c).build(root, "[88,0]");
|
||||
Files.writeString(pack.path(), "corrupted");
|
||||
assertThrows(IOException.class, () -> PackBuilder.previous(root, c));
|
||||
}
|
||||
@Test void hostRequiresGrantAndServesExactZip() throws Exception {
|
||||
PackConfig c = config(); var pack = new PackBuilder(c).build(root, "[88,0]");
|
||||
c.hosting.mode = "self_host"; c.hosting.bindAddress = "127.0.0.1";
|
||||
try (var reservation = new ServerSocket(0)) { c.hosting.port = reservation.getLocalPort(); }
|
||||
try (PackHost host = new PackHost(c.hosting); HttpClient client = HttpClient.newHttpClient()) {
|
||||
host.publish(pack); host.start(); String base = "http://127.0.0.1:" + c.hosting.port;
|
||||
String path = host.issuePath(pack);
|
||||
var response = client.send(HttpRequest.newBuilder(URI.create(base + path)).build(), HttpResponse.BodyHandlers.ofByteArray());
|
||||
assertEquals(200, response.statusCode()); assertArrayEquals(Files.readAllBytes(pack.path()), response.body());
|
||||
var denied = client.send(HttpRequest.newBuilder(URI.create(base + path.split("\\?")[0])).build(), HttpResponse.BodyHandlers.discarding());
|
||||
assertEquals(403, denied.statusCode());
|
||||
var head = client.send(HttpRequest.newBuilder(URI.create(base + path)).method("HEAD", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.discarding());
|
||||
assertEquals(200, head.statusCode()); assertEquals(pack.bytes(), head.headers().firstValueAsLong("Content-Length").orElseThrow());
|
||||
var secret = client.send(HttpRequest.newBuilder(URI.create(base + "/server.properties")).build(), HttpResponse.BodyHandlers.discarding());
|
||||
assertEquals(404, secret.statusCode());
|
||||
}
|
||||
}
|
||||
@Test void externalPublicationChecksActualZip() throws Exception {
|
||||
PackConfig c = config(); var pack = new PackBuilder(c).build(root, "[88,0]");
|
||||
c.hosting.mode = "self_host"; c.hosting.bindAddress = "127.0.0.1"; c.hosting.blockNonGameRequests = false;
|
||||
try (var reservation = new ServerSocket(0)) { c.hosting.port = reservation.getLocalPort(); }
|
||||
try (PackHost host = new PackHost(c.hosting)) {
|
||||
host.publish(pack); host.start();
|
||||
PackConfig external = config(); external.hosting.mode = "no_host";
|
||||
external.hosting.externalUrl = "http://127.0.0.1:" + c.hosting.port + host.issuePath(pack);
|
||||
assertDoesNotThrow(() -> PackBuilder.verifyExternal(external, pack));
|
||||
asset("assets/demo/new.txt", "new");
|
||||
var newer = new PackBuilder(c).build(root, "[88,0]");
|
||||
assertThrows(IOException.class, () -> PackBuilder.verifyExternal(external, newer));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.zip.*;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import com.google.gson.*;
|
||||
import org.lwjgl.stb.STBImage;
|
||||
import org.lwjgl.system.MemoryStack;
|
||||
import org.lwjgl.system.MemoryUtil;
|
||||
|
||||
/** Checks merged resources, including ItemsAdder's texture aliases and lossless PNG optimization. */
|
||||
class VerifySharedPack {
|
||||
public static void main(String[] args) throws Exception {
|
||||
int checked = 0;
|
||||
try (var pack = new ZipFile(args[0])) {
|
||||
Map<String, String> aliases = new HashMap<>();
|
||||
for (var entries = pack.entries(); entries.hasMoreElements();) {
|
||||
var entry = entries.nextElement();
|
||||
if (!entry.getName().contains("/atlases/") || !entry.getName().endsWith(".json")) continue;
|
||||
try (var in = pack.getInputStream(entry)) {
|
||||
var json = JsonParser.parseString(new String(in.readAllBytes(), StandardCharsets.UTF_8)).getAsJsonObject();
|
||||
for (var source : json.getAsJsonArray("sources")) {
|
||||
var object = source.getAsJsonObject();
|
||||
if (object.has("sprite") && object.has("resource"))
|
||||
aliases.put(object.get("sprite").getAsString(), object.get("resource").getAsString());
|
||||
}
|
||||
}
|
||||
}
|
||||
for (int i = 1; i < args.length; i++) {
|
||||
try (var jar = new ZipFile(args[i])) {
|
||||
int count = 0;
|
||||
for (var entries = jar.entries(); entries.hasMoreElements();) {
|
||||
var entry = entries.nextElement();
|
||||
if (!entry.getName().startsWith("astra-itemsadder/")) continue;
|
||||
int offset = entry.getName().indexOf("/resourcepack/assets/");
|
||||
if (offset < 0 || entry.isDirectory()) continue;
|
||||
String name = entry.getName().substring(offset + "/resourcepack/".length());
|
||||
var actual = pack.getEntry(name);
|
||||
if (actual == null) throw new AssertionError("Missing asset: " + name);
|
||||
try (var expectedBytes = jar.getInputStream(entry); var actualBytes = pack.getInputStream(actual)) {
|
||||
byte[] expected = expectedBytes.readAllBytes(), received = actualBytes.readAllBytes();
|
||||
if (!Arrays.equals(expected, received)) {
|
||||
if (name.endsWith(".json")) {
|
||||
var a = JsonParser.parseString(new String(expected, StandardCharsets.UTF_8));
|
||||
var b = normalize(JsonParser.parseString(new String(received, StandardCharsets.UTF_8)), aliases);
|
||||
// ItemsAdder's configured fix_dark_in_inventory adds front lighting
|
||||
// to parentless models; it does not change their geometry or tints.
|
||||
if (name.contains("/models/") && a.isJsonObject() && b.isJsonObject()
|
||||
&& !a.getAsJsonObject().has("gui_light")
|
||||
&& new JsonPrimitive("front").equals(b.getAsJsonObject().get("gui_light")))
|
||||
b.getAsJsonObject().remove("gui_light");
|
||||
if (!a.equals(b)) throw new AssertionError("Changed JSON semantics: " + name + " " + diff(a, b, ""));
|
||||
} else if (name.endsWith(".png")) {
|
||||
var a = pixels(expected); var b = pixels(received);
|
||||
if (a.width != b.width || a.height != b.height || !Arrays.equals(a.rgba, b.rgba))
|
||||
throw new AssertionError("Changed texture pixels: " + name);
|
||||
} else throw new AssertionError("Changed asset: " + name);
|
||||
}
|
||||
}
|
||||
count++;
|
||||
}
|
||||
System.out.println("PASS " + Path.of(args[i]).getFileName() + ": " + count + " equivalent client assets");
|
||||
checked += count;
|
||||
}
|
||||
}
|
||||
if (checked == 0) throw new AssertionError("No assets checked");
|
||||
if (pack.getEntry("pack.mcmeta") == null || pack.getEntry("assets/astrapacks/lang/en_us.json") == null)
|
||||
throw new AssertionError("Missing shared pack metadata");
|
||||
}
|
||||
System.out.println("PASS shared pack: " + checked + " assets; geometry, tints, fonts and texture pixels preserved");
|
||||
}
|
||||
static JsonElement normalize(JsonElement value, Map<String, String> aliases) {
|
||||
if (value.isJsonObject()) {
|
||||
var result = new JsonObject();
|
||||
value.getAsJsonObject().entrySet().forEach(e -> result.add(e.getKey(), normalize(e.getValue(), aliases)));
|
||||
return result;
|
||||
}
|
||||
if (value.isJsonArray()) {
|
||||
var result = new JsonArray(); value.getAsJsonArray().forEach(e -> result.add(normalize(e, aliases))); return result;
|
||||
}
|
||||
if (value.isJsonPrimitive() && value.getAsJsonPrimitive().isString() && aliases.containsKey(value.getAsString()))
|
||||
return new JsonPrimitive(aliases.get(value.getAsString()));
|
||||
return value;
|
||||
}
|
||||
static String diff(JsonElement a, JsonElement b, String path) {
|
||||
if (a.isJsonObject() && b.isJsonObject()) {
|
||||
var keys = new TreeSet<>(a.getAsJsonObject().keySet()); keys.addAll(b.getAsJsonObject().keySet());
|
||||
for (String key : keys) {
|
||||
var x = a.getAsJsonObject().get(key); var y = b.getAsJsonObject().get(key);
|
||||
if (x == null || y == null) return path + "/" + key + " key added/removed";
|
||||
if (!x.equals(y)) return diff(x, y, path + "/" + key);
|
||||
}
|
||||
}
|
||||
String text = path + ": " + a + " -> " + b;
|
||||
return text.substring(0, Math.min(200, text.length()));
|
||||
}
|
||||
record Pixels(int width, int height, byte[] rgba) {}
|
||||
static Pixels pixels(byte[] bytes) {
|
||||
// Minecraft uses stb_image, which supports the PNG checksum protection used by ItemsAdder.
|
||||
var input = MemoryUtil.memAlloc(bytes.length); input.put(bytes).flip();
|
||||
try (var stack = MemoryStack.stackPush()) {
|
||||
var width = stack.mallocInt(1); var height = stack.mallocInt(1); var channels = stack.mallocInt(1);
|
||||
var image = STBImage.stbi_load_from_memory(input, width, height, channels, 4);
|
||||
if (image == null) throw new AssertionError("Minecraft PNG decoder: " + STBImage.stbi_failure_reason());
|
||||
try {
|
||||
byte[] rgba = new byte[width.get(0) * height.get(0) * 4]; image.get(rgba);
|
||||
return new Pixels(width.get(0), height.get(0), rgba);
|
||||
} finally { image.rewind(); STBImage.stbi_image_free(image); }
|
||||
} finally { MemoryUtil.memFree(input); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
"""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