diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
new file mode 100644
index 0000000..d9fc3fd
--- /dev/null
+++ b/.github/workflows/test.yml
@@ -0,0 +1,62 @@
+name: test
+
+# Checks that need no GPU: file parsers, config handling, queue bookkeeping (tests/run_tests.gd) and the shell scripts.
+on:
+ push:
+ branches: [main]
+ paths:
+ - "project.godot"
+ - "scripts/**"
+ - "tests/**"
+ - "docker/**"
+ - ".github/workflows/test.yml"
+ pull_request:
+ paths:
+ - "project.godot"
+ - "scripts/**"
+ - "tests/**"
+ - "docker/**"
+ - ".github/workflows/test.yml"
+
+permissions:
+ contents: read
+
+concurrency:
+ group: test-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ test:
+ runs-on: ubuntu-latest
+ env:
+ GODOT_VERSION: 4.7.2-stable
+ # from SHA512-SUMS.txt of the release
+ GODOT_SHA512: 9aa00f7a605200940bce3027a567b782f49bd8e940dd06ae9e987bd65aee1b1467edd56ed84fcdcbdd44354bf613bdbb4e5d2913e925850368e150c59ed54c65
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+
+ - name: Install Godot
+ run: |
+ f="Godot_v${GODOT_VERSION}_linux.x86_64.zip"
+ curl -fsSL -o "$RUNNER_TEMP/$f" "https://github.com/godotengine/godot-builds/releases/download/${GODOT_VERSION}/$f"
+ echo "$GODOT_SHA512 $RUNNER_TEMP/$f" | sha512sum -c -
+ unzip -q "$RUNNER_TEMP/$f" -d "$RUNNER_TEMP"
+ mv "$RUNNER_TEMP/Godot_v${GODOT_VERSION}_linux.x86_64" "$RUNNER_TEMP/godot"
+
+ - name: Import the project
+ run: timeout 300 "$RUNNER_TEMP/godot" --headless --path . --import
+
+ - name: Run the checks
+ run: timeout 300 "$RUNNER_TEMP/godot" --headless --path . -s tests/run_tests.gd
+
+ - name: Check the shell scripts
+ run: shellcheck -S warning docker/*.sh
+
+ - name: Check the compose example
+ working-directory: docker
+ run: |
+ # the files the example expects next to it are created by the operator
+ touch db_password
+ docker compose -f compose.watch.yaml config -q
diff --git a/docker/compose.watch.yaml b/docker/compose.watch.yaml
index 99e3c30..b099cbc 100644
--- a/docker/compose.watch.yaml
+++ b/docker/compose.watch.yaml
@@ -1,7 +1,8 @@
# Resident map updater: ONE container for every map listed in ./maps.json (shape: docker/maps.example.json).
# Separate compose project, it does not touch the game stack:
# cd
&& docker compose pull && docker compose up -d
-# Needs next to this file: data/ (output of `build-data`), maps.json, state/ (writable: keeps what was seen and queued).
+# Needs next to this file: data/ (output of `build-data`), maps.json, state/ (writable: keeps what was seen and queued),
+# db_password (the database user's password, readable by the uid below and nobody else).
#
# Unprivileged: read-only root, no capabilities, 1 CPU at the lowest share, only the iGPU render node, world directories
# read-only. Renders only below --max-load, at most --max-megas mega tiles per batch, closest to a player first.
@@ -9,7 +10,7 @@ services:
watch:
image: ghcr.io/toro-server/toro-renderer:latest
command: ["watch", "--config", "/config/maps.json", "--state-dir", "/state"]
- network_mode: host # the database is published on 127.0.0.1:4000
+ networks: [database]
restart: unless-stopped
user: "1002:1002" # any uid that may use the render node
group_add: ["993", "1001"] # gid of `render` (iGPU), gid that may read the world files
@@ -20,13 +21,26 @@ services:
security_opt: ["no-new-privileges:true"]
cpus: 1.0
cpu_shares: 32
- mem_limit: 1536m
+ # The kernel charges the iGPU's buffers to this cgroup as shmem: about 1.2 GB while drawing, on top of about 400 MB of
+ # anonymous memory. A limit below that total gets the container OOM-killed over and over (every 70 s or so at 1536m).
+ mem_limit: 3g
pids_limit: 256
environment:
HOME: /tmp
- # DYNMAP_DB_PASSWORD: ... # only when the database user has a password
+ secrets: [db_password]
volumes:
- ./data:/data:ro
- ./maps.json:/config/maps.json:ro
- ./state:/state
- /srv/minecraft/worlds:/worlds:ro # the directory holding the region folders named in maps.json
+
+networks:
+ # An existing Docker network where the database answers as "tidb" (see "db" in maps.json).
+ # Named by the game stack's compose file; set DB_NETWORK if yours differs.
+ database:
+ external: true
+ name: ${DB_NETWORK:-minecraft-network}
+
+secrets:
+ db_password:
+ file: ./db_password
diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh
index 756e562..b9e0eb3 100644
--- a/docker/entrypoint.sh
+++ b/docker/entrypoint.sh
@@ -6,7 +6,8 @@ set -eu
export HOME=/tmp
export XDG_RUNTIME_DIR=/tmp/xdg
-mkdir -p -m 700 "$XDG_RUNTIME_DIR"
+mkdir -p "$XDG_RUNTIME_DIR"
+chmod 700 "$XDG_RUNTIME_DIR"
export WLR_BACKENDS=headless
export WLR_LIBINPUT_NO_DEVICES=1
diff --git a/docker/maps.example.json b/docker/maps.example.json
index bcad78d..008f0e6 100644
--- a/docker/maps.example.json
+++ b/docker/maps.example.json
@@ -1,5 +1,5 @@
{
- "db": { "host": "127.0.0.1", "port": 4000, "user": "root", "database": "dynmap" },
+ "db": { "host": "tidb", "port": 4000, "user": "renderer", "password_file": "/run/secrets/db_password", "database": "dynmap" },
"live": "wss://map.example.net/up/ws",
"maps": [
{ "id": 1, "region": "/worlds/overworld/region", "persp": "iso_SE_30_hires", "zoom_max": 12 },
diff --git a/docker/run.sh b/docker/run.sh
index cccb678..ee41883 100644
--- a/docker/run.sh
+++ b/docker/run.sh
@@ -10,7 +10,9 @@
# CONFIG maps.json mounted read-only at /config/maps.json
# ONLINE_FILE proxy presence file mounted at /online.txt (use with run --online-file /online.txt)
# EXTRA_GROUPS space separated gids that may read the world files
-# NETWORK docker network (default: host for run/zoom, none otherwise)
+# NETWORK docker network (default: $DB_NETWORK or minecraft-network for run/zoom/watch, none otherwise)
+# DB_PASSWORD_FILE file with the database password, mounted read-only at /run/secrets/db_password
+# DYNMAP_DB_PASSWORD the password itself: passed by name, so its value stays off the docker command line
# IMAGE, CPUS, MEMORY
set -euo pipefail
@@ -22,7 +24,7 @@ RENDER_GID=$(getent group render | cut -d: -f3)
mkdir -p "$OUT_DIR" "$STATE_DIR"
case "${1:-}" in
- run|zoom|watch) NETWORK=${NETWORK:-host} ;;
+ run|zoom|watch) NETWORK=${NETWORK:-${DB_NETWORK:-minecraft-network}} ;;
*) NETWORK=${NETWORK:-none} ;;
esac
@@ -31,14 +33,21 @@ MOUNTS=(-v "$DATA_DIR:/data:ro" -v "$OUT_DIR:/out" -v "$STATE_DIR:/state")
[ -n "${CONFIG:-}" ] && MOUNTS+=(-v "$CONFIG:/config/maps.json:ro")
[ -n "${ONLINE_FILE:-}" ] && MOUNTS+=(-v "$ONLINE_FILE:/online.txt:ro")
+DB_ARGS=()
+if [ -n "${DB_PASSWORD_FILE:-}" ]; then
+ MOUNTS+=(-v "$DB_PASSWORD_FILE:/run/secrets/db_password:ro")
+ DB_ARGS+=(-e DYNMAP_DB_PASSWORD_FILE=/run/secrets/db_password)
+fi
+[ -n "${DYNMAP_DB_PASSWORD:-}" ] && DB_ARGS+=(-e DYNMAP_DB_PASSWORD)
+
GROUPS_ARGS=(--group-add "$RENDER_GID")
for g in ${EXTRA_GROUPS:-}; do GROUPS_ARGS+=(--group-add "$g"); done
exec docker run --rm --name toro-renderer --network "$NETWORK" \
--user "$(id -u):$(id -g)" "${GROUPS_ARGS[@]}" \
--device /dev/dri/renderD128 \
- --cpus "${CPUS:-1}" --cpu-shares 32 --memory "${MEMORY:-1g}" --pids-limit 256 \
+ --cpus "${CPUS:-1}" --cpu-shares 32 --memory "${MEMORY:-3g}" --pids-limit 256 \
--read-only --tmpfs /tmp:size=256m,exec \
--cap-drop ALL --security-opt no-new-privileges \
- -e GODOT_RENDERING_METHOD="${GODOT_RENDERING_METHOD:-mobile}" -e DYNMAP_DB_PASSWORD="${DYNMAP_DB_PASSWORD:-}" \
+ -e GODOT_RENDERING_METHOD="${GODOT_RENDERING_METHOD:-mobile}" "${DB_ARGS[@]}" \
"${MOUNTS[@]}" "$IMAGE" "$@"
diff --git a/docs/commands.md b/docs/commands.md
index d21fd05..5c2c21c 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -13,6 +13,7 @@ godot --path . -s scripts/main.gd -- <コマンド> [--オプション 値] [--
| --- | --- | --- |
| `--config FILE` | `/config/maps.json`(あれば) | マップ設定 |
| `--db-host`, `--db-port` | 設定の `db`、無ければ `127.0.0.1:4000` | データベース |
+| `--db-user` | 設定の `db.user`(既定なし) | データベースのユーザー。パスワードは環境変数かファイルから読む([運用](operations.md)) |
| `--rate N` | 8000000 | 書き込みと blob 読み出しで共有するバイト/秒の上限。0 で無制限 |
| `--dry-run` | | データベースへ書かない |
| `--live URL` | 設定の `live` | プレイヤー位置の WebSocket。`off` で無効 |
diff --git a/docs/operations.md b/docs/operations.md
index 2ddda03..c92f077 100644
--- a/docs/operations.md
+++ b/docs/operations.md
@@ -23,7 +23,8 @@
```
`docker/run.sh` が使う環境変数: `WORLD_DIR`(`/world` に読み取り専用)、`DATA_DIR`(`/data`)、`OUT_DIR`(`/out`)、
`STATE_DIR`(`/state`)、`CONFIG`(`/config/maps.json`)、`ONLINE_FILE`(`/online.txt`)、`EXTRA_GROUPS`、`NETWORK`、
- `IMAGE`、`CPUS`、`MEMORY`。`run` と `zoom` では既定でホストのネットワークを使う(DB が `127.0.0.1` で公開されているため)。
+ `DB_PASSWORD_FILE`(`/run/secrets/db_password`)、`IMAGE`、`CPUS`、`MEMORY`。`run`、`zoom`、`watch` では既定で
+ `DB_NETWORK`(無ければ `minecraft-network`)の Docker ネットワークに入る。それ以外は通信なし。
## マップ設定
@@ -31,7 +32,7 @@
```json
{
- "db": { "host": "127.0.0.1", "port": 4000, "user": "root", "database": "dynmap" },
+ "db": { "host": "tidb", "port": 4000, "user": "renderer", "password_file": "/run/secrets/db_password", "database": "dynmap" },
"live": "wss://map.example.net/up/ws",
"maps": [
{ "id": 30002, "region": "/worlds/flat/region", "persp": "iso_SE_30_hires", "zoom_max": 7 }
@@ -41,10 +42,25 @@
- `id` は Dynmap の MapID。マップの Dynmap ワールド名(`main` など)は `dynmap_Maps` から引く。
- `persp` は 4 つの視点名のいずれか。`zoom_max` は作る zoom の段数。`mega`(既定 8)、`min_y`(-64)、`max_y`(320)も指定できる。
-- `live` を省くとプレイヤー位置を使わない。
-- DB にパスワードがある場合は環境変数 `DYNMAP_DB_PASSWORD` に入れる(設定ファイルに書かない)。
+- `live` を省くとプレイヤー位置を使わない。`wss://` だけを受け付ける(`ws://` はこのマシンの中の接続先だけ)。それ以外の URL では
+ 接続せず、`run` は「プレイヤーの有無が分からない」ものとして待つ。
- 設定ファイルは `/config/maps.json` にあれば自動で読む。それ以外は `--config FILE`。
+### データベースの接続先とパスワード
+
+- `db.user` は必須(既定はない)。`--db-host`、`--db-port`、`--db-user` で上書きできる。
+- パスワードは環境変数かファイルから読む。コマンドラインでは受け取らず、設定ファイルの `password` も無視する。優先順は
+ `DYNMAP_DB_PASSWORD`、`DYNMAP_DB_PASSWORD_FILE` が指すファイル、`db.password_file` が指すファイル。読めないファイルを指定した
+ 場合は、パスワードなしで試さずに接続を断念する。
+- 接続は TLS を使わない。同じ Docker ネットワークの中だけで使う。
+- レンダラーに要る権限はタイルの表だけなので、専用のユーザーを作る。
+
+ ```sql
+ CREATE USER 'renderer'@'%' IDENTIFIED BY '<生成した値>';
+ GRANT SELECT, INSERT, UPDATE, DELETE ON dynmap.dynmap_Tiles TO 'renderer'@'%';
+ GRANT SELECT ON dynmap.dynmap_Maps TO 'renderer'@'%';
+ ```
+
## マップ全体のジョブ(`run`)
```
@@ -85,6 +101,10 @@ docker compose -f docker/compose.watch.yaml up -d
レンダラーは起動したまま使い回す。歩き回っただけで保存済みの地形が変わらなければ、何も再描画しない。
+描き始める前に試行回数を状態ファイルへ記録し、終わったら消す。回数が残っているメガタイルは、プロセスがその途中で止まったもの
+なので、1 つずつ描き直し、3 回失敗したら待ち行列から外す(チャンクがまた変わると入り直す)。同じ場所で落ち続けて再起動を
+繰り返すことを防ぐ。データベースのエラーは数えず、制限なしに再試行する。
+
初回の起動時は、その時点以降の変更だけを見る(`since` は起動時刻から)。停止中に起きた変更も、領域ファイルの時刻から
拾える。
@@ -107,12 +127,25 @@ docker compose -f docker/compose.watch.yaml up -d
## 本番運用の安全策
-- コンテナ: CPU 1 個を最低の共有度で、`nice 19`、`ionice idle`、メモリ 1〜1.5 GB、ルートとワールドは読み取り専用、
- ケーパビリティなし、一時ファイルは tmpfs(SSD へ書かない)
+- コンテナ: CPU 1 個を最低の共有度で、`nice 19`、`ionice idle`、ルートとワールドは読み取り専用、ケーパビリティなし、一時ファイルは
+ tmpfs(SSD へ書かない)。ホストのネットワークは使わず、データベースのある Docker ネットワークにだけ入る
+- メモリ: `watch` は 3 GB。内蔵 GPU のバッファが shmem としてコンテナの cgroup に計上される(描画中で約 1.2 GB、ほかに無名メモリが
+ 約 400 MB)ので、1.5 GB では OOM で落ち続ける
+- 入力の検査: 領域ファイル、NBT、jar は外から来るデータとして扱う。チャンクごとの展開は 64 MiB まで、NBT の深さは 128 段まで、値は
+ 200 万個まで、パレットとデータの長さも確かめる。合わないチャンクは無いものとして描き、既存のタイルは消さない
- 負荷が上限を超える間は描画しない。`run` ではさらに、誰かがオンラインの間も待つ
- TiDB: `(MapID,x,y,zoom) IN (...)` の点参照のみ。書き込みは `--rate`(既定 8 MB/s)で制限し、ハッシュが同じタイルは書かず、
空のタイルは行を削除する。全レベル走査をするのは `--zoom-all` だけ
-- メモリ: 1 バッチ分の画像(メガタイル × 8 個 ≒ 数十 MB)と、チャンクキャッシュ(バッチ後に解放)だけを持つ
+- メモリ(プロセスの中): 1 バッチ分の画像(メガタイル × 8 個 ≒ 数十 MB)と、チャンクキャッシュ(バッチ後に解放)だけを持つ
+
+## 試験
+
+GPU の要らない部分(ファイルの解析、設定、待ち行列)は `tests/run_tests.gd` で確かめる。GitHub Actions の `test` でも動く。
+
+```
+godot --headless --path . --import
+godot --headless --path . -s tests/run_tests.gd
+```
## なぜコンテナに Wayland コンポジタがあるのか
diff --git a/scripts/cmd/context.gd b/scripts/cmd/context.gd
index 6d01058..91076d9 100644
--- a/scripts/cmd/context.gd
+++ b/scripts/cmd/context.gd
@@ -2,7 +2,7 @@ class_name Context
extends RefCounted
## What the database-backed commands (run, watch, zoom) share: config file, tile store, quiet-gate and live player feed.
##
-## Common options: --config FILE (default /config/maps.json when present), --db-host/--db-port, --rate BYTES/S,
+## Common options: --config FILE (default /config/maps.json when present), --db-host/--db-port/--db-user, --rate BYTES/S,
## --dry-run, --live URL (WebSocket of the map site, default from the config; --live off disables), --max-load N,
## --max-players N (< 0 ignores players), --online-file FILE, --stale-after S.
@@ -19,8 +19,8 @@ static func create(args_: Args, default_max_load: float, default_max_players: in
var cfg_path := args_.text("config", "/config/maps.json" if FileAccess.file_exists("/config/maps.json") else "")
c.cfg = MapDef.load_config(cfg_path)
var db := MapDef.db_config(args_, c.cfg)
- if OS.get_environment("DYNMAP_DB_PASSWORD") != "":
- db["password"] = OS.get_environment("DYNMAP_DB_PASSWORD")
+ if db.get("password", "") == "" and not db.has("error"):
+ Term.say("warning: no database password configured (DYNMAP_DB_PASSWORD or password_file)")
c.store.configure(db)
c.store.rate = args_.number("rate", 8_000_000.0)
c.store.dry_run = args_.flag("dry-run")
diff --git a/scripts/cmd/jar_reader.gd b/scripts/cmd/jar_reader.gd
index 1a66712..c71a6e2 100644
--- a/scripts/cmd/jar_reader.gd
+++ b/scripts/cmd/jar_reader.gd
@@ -3,13 +3,23 @@ extends RefCounted
## Reads a .jar/.zip from memory with a name index built once. (ZIPReader.read_file walks the central directory for every
## call, ~0.2 s each on a jar with 40k entries.) Deflated entries are inflated by wrapping the raw stream into a gzip
## container - the zip directory already holds the CRC32 and the size gzip wants in its trailer.
+##
+## The archive is input from outside: entry names that could leave the output directory are not indexed, offsets are checked
+## against the file, and declared sizes are limited (they decide how much memory is allocated).
+
+const MAX_JAR_BYTES := 1024 * 1024 * 1024
+## client jars hold JSON and small textures
+const MAX_ENTRY_BYTES := 16 * 1024 * 1024
var _data := PackedByteArray()
var _index := {} # name -> [header offset, compressed size, size, crc32, method]
func open(path: String) -> bool:
- _data = FileAccess.get_file_as_bytes(path)
+ var f := FileAccess.open(path, FileAccess.READ)
+ if f == null or f.get_length() > MAX_JAR_BYTES:
+ return false
+ _data = f.get_buffer(f.get_length())
if _data.size() < 22:
return false
var eocd := -1
@@ -22,14 +32,30 @@ func open(path: String) -> bool:
var entries := _data.decode_u16(eocd + 10)
var pos := _data.decode_u32(eocd + 16)
for _i in entries:
- if _data.decode_u32(pos) != 0x02014B50:
+ if pos + 46 > _data.size() or _data.decode_u32(pos) != 0x02014B50:
return false
var name_len := _data.decode_u16(pos + 28)
var extra_len := _data.decode_u16(pos + 30)
var comment_len := _data.decode_u16(pos + 32)
+ var next := pos + 46 + name_len + extra_len + comment_len
+ if next > _data.size():
+ return false
var name := _data.slice(pos + 46, pos + 46 + name_len).get_string_from_utf8()
- _index[name] = [_data.decode_u32(pos + 42), _data.decode_u32(pos + 20), _data.decode_u32(pos + 24), _data.decode_u32(pos + 16), _data.decode_u16(pos + 10)]
- pos += 46 + name_len + extra_len + comment_len
+ if safe_name(name):
+ _index[name] = [_data.decode_u32(pos + 42), _data.decode_u32(pos + 20), _data.decode_u32(pos + 24), _data.decode_u32(pos + 16), _data.decode_u16(pos + 10)]
+ else:
+ push_warning("jar entry skipped, its name is not a relative path inside the archive: %s" % name)
+ pos = next
+ return true
+
+
+## A relative path without "..", safe to join to an output directory on Linux and Windows.
+static func safe_name(name: String) -> bool:
+ if name == "" or name.begins_with("/") or name.contains("\\") or name.contains(":"):
+ return false
+ for part in name.split("/"):
+ if part == "..":
+ return false
return true
@@ -46,7 +72,13 @@ func read(name: String) -> PackedByteArray:
return PackedByteArray()
var e: Array = _index[name]
var header: int = e[0]
+ if e[1] > MAX_ENTRY_BYTES or e[2] > MAX_ENTRY_BYTES or header + 30 > _data.size():
+ push_warning("jar entry skipped, sizes out of bounds: %s" % name)
+ return PackedByteArray()
var start := header + 30 + _data.decode_u16(header + 26) + _data.decode_u16(header + 28)
+ if start + e[1] > _data.size():
+ push_warning("jar entry skipped, sizes out of bounds: %s" % name)
+ return PackedByteArray()
var body := _data.slice(start, start + e[1])
if e[4] == 0:
return body
diff --git a/scripts/cmd/render.gd b/scripts/cmd/render.gd
index ea60698..3a859d0 100644
--- a/scripts/cmd/render.gd
+++ b/scripts/cmd/render.gd
@@ -54,6 +54,9 @@ static func run(args: Args) -> int:
iso.next_generation()
tiles = iso.render(rect[0], rect[1], rect[2], rect[3])
print("render rect %s: %.0f ms (%d tiles)" % [rect, (Time.get_ticks_usec() - t0) / 1000.0, tiles.size()])
+ if tiles.is_empty():
+ push_error("rect %s was not drawn" % [rect])
+ continue
var dir := out_dir
if out_dir != "" and rects.size() > 1:
dir = out_dir.path_join("r%d_%d" % [rect[0], rect[1]])
diff --git a/scripts/job/live_feed.gd b/scripts/job/live_feed.gd
index 28c9253..db36163 100644
--- a/scripts/job/live_feed.gd
+++ b/scripts/job/live_feed.gd
@@ -3,9 +3,13 @@ extends RefCounted
## Real-time player positions over the map site's WebSocket (/up/ws). A client that sends {"subscribe": ""} gets
## {"type":"players","players":[{account, world, x, y, z, health, armor}, ...]} whenever the positions of the players
## Dynmap shows in that world change, so one connection per watched world. Reconnects on its own.
+##
+## Only wss:// (certificates are verified), or ws:// to this machine. With any other URL the feed never connects, which
+## the gate treats as "not connected" rather than as "nobody online".
const RETRY_MIN_MS := 5_000
const RETRY_MAX_MS := 60_000
+const MAX_PLAYERS := 1000
var url := ""
var _worlds := {} # world -> {"peer", "open", "players", "retry_at", "backoff"}
@@ -13,11 +17,17 @@ var _worlds := {} # world -> {"peer", "open", "players", "retry_at", "backoff"}
func _init(url_: String) -> void:
url = url_
+ if not allowed_url(url):
+ push_warning("live feed disabled: %s is not a wss:// URL" % url)
+
+
+static func allowed_url(u: String) -> bool:
+ return u.begins_with("wss://") or u.begins_with("ws://127.0.0.1:") or u.begins_with("ws://localhost:")
## Starts following a world; polling happens every frame of the main loop (use Term.sleep to wait).
func watch(world: String) -> void:
- if world == "" or _worlds.has(world):
+ if world == "" or _worlds.has(world) or not allowed_url(url):
return
_worlds[world] = {"peer": null, "open": false, "players": [], "retry_at": 0, "backoff": RETRY_MIN_MS}
if _worlds.size() == 1:
@@ -60,8 +70,23 @@ func _lost(w: Dictionary, now: int) -> void:
func _message(w: Dictionary, text: String) -> void:
var msg = JSON.parse_string(text)
- if msg is Dictionary and msg.get("type") == "players" and msg.get("players") is Array:
- w["players"] = msg["players"]
+ if msg is Dictionary and msg.get("type") is String and msg["type"] == "players" and msg.get("players") is Array:
+ w["players"] = valid_players(msg["players"])
+
+
+## The entries with usable coordinates (the feed comes from another service).
+static func valid_players(list: Array) -> Array:
+ var out := []
+ for p in list:
+ if p is Dictionary and _coord(p.get("x")) and _coord(p.get("y")) and _coord(p.get("z")):
+ out.append(p)
+ if out.size() >= MAX_PLAYERS:
+ break
+ return out
+
+
+static func _coord(v: Variant) -> bool:
+ return v is int or (v is float and is_finite(v))
## Players of a world: Array of Dictionary with x, y, z (block coordinates).
diff --git a/scripts/job/renderer_pool.gd b/scripts/job/renderer_pool.gd
index 1447eac..8f7af0e 100644
--- a/scripts/job/renderer_pool.gd
+++ b/scripts/job/renderer_pool.gd
@@ -43,6 +43,7 @@ func renderer(persp_name: String, region_dir: String) -> IsoRenderer:
## Renders each mega tile (mega x mega tiles) -> Vector2i -> null (blank) or {"img": Image, "hash": int}.
+## A mega tile that could not be drawn adds nothing, so its existing rows stay as they are.
func render_megas(iso: IsoRenderer, megas: Array[Vector2i], mega: int, min_y: int, max_y: int) -> Dictionary:
var tiles := {}
iso.min_y = min_y
@@ -50,6 +51,8 @@ func render_megas(iso: IsoRenderer, megas: Array[Vector2i], mega: int, min_y: in
for m in megas:
iso.next_generation()
var images := iso.render(m.x * mega, m.y * mega, mega, mega)
+ if images.is_empty():
+ continue
var i := 0
for ty in mega:
for tx in mega:
diff --git a/scripts/job/watch_job.gd b/scripts/job/watch_job.gd
index b05b377..4014f2e 100644
--- a/scripts/job/watch_job.gd
+++ b/scripts/job/watch_job.gd
@@ -7,6 +7,12 @@ extends RefCounted
##
## Order of work: mega tiles close to a player first (positions arrive over the WebSocket live feed), the rest in the order
## they were queued; anything waiting longer than --stale-after seconds goes ahead of everything else.
+##
+## A mega tile is counted as attempted (on disk) before drawing and the count is cleared afterwards, so a count that survives
+## a restart means the process died on it. Those are retried one at a time and dropped after MAX_ATTEMPTS, so one bad chunk
+## cannot keep the container in a crash loop. The tile is queued again the next time its chunks change.
+
+const MAX_ATTEMPTS := 3
class MapState:
var def: MapDef
@@ -15,6 +21,8 @@ class MapState:
var since := 0.0
## Vector2i -> unix time it was queued
var pending := {}
+ ## Vector2i -> times the process started drawing it without finishing
+ var attempts := {}
var path := ""
var maps: Array[MapState] = []
@@ -46,7 +54,10 @@ func add(def: MapDef, state_dir: String) -> bool:
if st is Dictionary:
ms.since = float(st.get("since", ms.since))
for e in st.get("pending", []):
- ms.pending[Vector2i(int(e[0]), int(e[1]))] = float(e[2]) if e.size() > 2 else Time.get_unix_time_from_system()
+ var m := Vector2i(int(e[0]), int(e[1]))
+ ms.pending[m] = float(e[2]) if e.size() > 2 else Time.get_unix_time_from_system()
+ if e.size() > 3 and int(e[3]) > 0:
+ ms.attempts[m] = int(e[3])
maps.append(ms)
return true
@@ -55,11 +66,34 @@ func _save(ms: MapState) -> void:
DirAccess.make_dir_recursive_absolute(ms.path.get_base_dir())
var pend := []
for m: Vector2i in ms.pending:
- pend.append([m.x, m.y, ms.pending[m]])
+ pend.append([m.x, m.y, ms.pending[m], ms.attempts.get(m, 0)])
var f := FileAccess.open(ms.path, FileAccess.WRITE)
+ if f == null:
+ push_warning("cannot write %s" % ms.path)
+ return
f.store_string(JSON.stringify({"since": ms.since, "pending": pend}))
+## Forgets the mega tiles that already took the process down MAX_ATTEMPTS times.
+func _drop_failing(ms: MapState) -> void:
+ for m: Vector2i in ms.attempts.keys():
+ if ms.attempts[m] >= MAX_ATTEMPTS:
+ Term.say("map %d: giving up on mega tile %s after %d attempts" % [ms.def.id, m, ms.attempts[m]])
+ ms.pending.erase(m)
+ ms.attempts.erase(m)
+
+
+## The next batch from the queue in priority order. A tile the process died on goes alone, to tell which one is the cause.
+func _next_group(ms: MapState, order: Array) -> Array[Vector2i]:
+ var group: Array[Vector2i] = []
+ group.assign(order.slice(0, max_megas))
+ for m in group:
+ if ms.attempts.has(m):
+ group.assign([m])
+ break
+ return group
+
+
func _scan(ms: MapState, now: float) -> void:
var chunks := ms.changes.changed_since(ms.def.region_dir, ms.since)
if not chunks.is_empty():
@@ -121,6 +155,7 @@ func _work_one_group() -> bool:
var best_ms: MapState = null
var best_rank := INF
for ms in maps:
+ _drop_failing(ms)
for m: Vector2i in ms.pending:
var r := _rank(ms, m, ms.pending[m], now)
if r < best_rank:
@@ -131,8 +166,7 @@ func _work_one_group() -> bool:
var ms := best_ms
var order: Array = ms.pending.keys()
order.sort_custom(func(a: Vector2i, b: Vector2i) -> bool: return _rank(ms, a, ms.pending[a], now) < _rank(ms, b, ms.pending[b], now))
- var group: Array[Vector2i] = []
- group.assign(order.slice(0, max_megas))
+ var group := _next_group(ms, order)
if not store.ensure_connected():
Term.say("database unreachable: " + store.error)
return false
@@ -140,6 +174,9 @@ func _work_one_group() -> bool:
var iso := pool.renderer(ms.def.persp_name, ms.def.region_dir)
if iso == null:
return false
+ for m in group:
+ ms.attempts[m] = ms.attempts.get(m, 0) + 1
+ _save(ms)
var t0 := Time.get_ticks_msec()
var tiles := pool.render_megas(iso, group, ms.def.mega, ms.def.min_y, ms.def.max_y)
var t1 := Time.get_ticks_msec()
@@ -150,9 +187,13 @@ func _work_one_group() -> bool:
if _zoom == null:
_zoom = ZoomBuilder.new(store, pool.rd)
_zoom.rebuild(keys, res["changed"], ms.def.zoom_max, false, int(Time.get_unix_time_from_system() * 1000.0))
+ # the process survived the batch, so the count does not apply any more (database errors are retried without a limit)
+ for m in group:
+ ms.attempts.erase(m)
if store.error != "":
Term.say("map %d: upload failed (%s), will retry" % [ms.def.id, store.error])
store.error = ""
+ _save(ms)
return false
for m in group:
ms.pending.erase(m)
diff --git a/scripts/map/anvil_changes.gd b/scripts/map/anvil_changes.gd
index cf21b2c..c1af2c1 100644
--- a/scripts/map/anvil_changes.gd
+++ b/scripts/map/anvil_changes.gd
@@ -16,8 +16,8 @@ func changed_since(region_dir: String, since: float) -> Array[Vector2i]:
var out: Array[Vector2i] = []
var now := Time.get_unix_time_from_system()
for f in DirAccess.get_files_at(region_dir):
- var p := f.split(".")
- if p.size() != 4 or p[0] != "r" or p[3] != "mca" or not p[1].is_valid_int() or not p[2].is_valid_int():
+ var rc := WorldReader.region_coords(f)
+ if rc.is_empty():
continue
var path := region_dir.path_join(f)
var mt := FileAccess.get_modified_time(path)
@@ -34,8 +34,8 @@ func changed_since(region_dir: String, since: float) -> Array[Vector2i]:
fh.close()
if head.size() < 8192:
continue
- var rx := int(p[1])
- var rz := int(p[2])
+ var rx: int = rc[0]
+ var rz: int = rc[1]
for i in 1024:
var o := 4096 + i * 4
var ts := (head[o] << 24) | (head[o + 1] << 16) | (head[o + 2] << 8) | head[o + 3]
diff --git a/scripts/map/map_def.gd b/scripts/map/map_def.gd
index baec9fb..978937a 100644
--- a/scripts/map/map_def.gd
+++ b/scripts/map/map_def.gd
@@ -18,7 +18,7 @@ func persp() -> Persp:
## Config file (JSON), shape in docker/maps.example.json:
-## {"db": {host, port, user, password, database}, "live": "wss://.../up/ws", "maps": [{id, region, persp, zoom_max}]}
+## {"db": {host, port, user, password_file, database}, "live": "wss://.../up/ws", "maps": [{id, region, persp, zoom_max}]}
static func load_config(path: String) -> Dictionary:
if path == "":
return {}
@@ -56,11 +56,32 @@ static func from_args(args: Args, cfg: Dictionary) -> MapDef:
return m
-## database settings: config "db" section, overridden by --db-host / --db-port
+## Database settings: config "db" section, overridden by --db-host / --db-port / --db-user.
+## The password comes from the environment or a file, never from the command line or the text of the config: the variable
+## DYNMAP_DB_PASSWORD, else the file named by DYNMAP_DB_PASSWORD_FILE or by "password_file" in the config.
+## A password file that cannot be read sets "error": the store then refuses to connect instead of trying without one.
static func db_config(args: Args, cfg: Dictionary) -> Dictionary:
- var db: Dictionary = cfg.get("db", {}).duplicate()
+ var section = cfg.get("db", {})
+ var db: Dictionary = section.duplicate() if section is Dictionary else {}
+ if db.has("password"):
+ push_warning('"password" in the config is ignored: use DYNMAP_DB_PASSWORD or "password_file"')
+ db.erase("password")
if args.has("db-host"):
db["host"] = args.text("db-host")
if args.has("db-port"):
db["port"] = args.integer("db-port")
+ if args.has("db-user"):
+ db["user"] = args.text("db-user")
+ var path: String = OS.get_environment("DYNMAP_DB_PASSWORD_FILE")
+ if path == "":
+ path = str(db.get("password_file", ""))
+ db.erase("password_file")
+ if OS.get_environment("DYNMAP_DB_PASSWORD") != "":
+ db["password"] = OS.get_environment("DYNMAP_DB_PASSWORD")
+ elif path != "":
+ var f := FileAccess.open(path, FileAccess.READ)
+ if f == null:
+ db["error"] = "cannot read the database password file %s" % path
+ else:
+ db["password"] = f.get_as_text().rstrip("\r\n")
return db
diff --git a/scripts/map/scan_cache.gd b/scripts/map/scan_cache.gd
index ce7a504..a81d139 100644
--- a/scripts/map/scan_cache.gd
+++ b/scripts/map/scan_cache.gd
@@ -49,9 +49,9 @@ func max_y() -> int:
static func build(region_dir: String) -> ScanCache:
var c := ScanCache.new()
for f in DirAccess.get_files_at(region_dir):
- var p := f.split(".")
- if p.size() == 4 and p[0] == "r" and p[3] == "mca" and p[1].is_valid_int() and p[2].is_valid_int():
- c._files.append([int(p[1]), int(p[2]), region_dir.path_join(f)])
+ var rc := WorldReader.region_coords(f)
+ if not rc.is_empty():
+ c._files.append([rc[0], rc[1], region_dir.path_join(f)])
c._files.sort()
c._results.resize(c._files.size())
var gid := WorkerThreadPool.add_group_task(c._scan_region, c._files.size(), -1, true, "scan regions")
@@ -63,7 +63,7 @@ static func build(region_dir: String) -> ScanCache:
func _scan_region(i: int) -> void:
var info: Array = _files[i]
- var rg := FileAccess.get_file_as_bytes(info[2])
+ var rg := WorldReader.read_region(info[2])
var out := PackedInt32Array()
if rg.size() >= 8192:
for lz in 32:
@@ -79,9 +79,16 @@ func _scan_region(i: int) -> void:
continue
var lo := 1 << 30
var hi := -(1 << 30)
- for s in root.get("sections", []):
- var pal: Array = s.get("block_states", {}).get("palette", [])
- if pal.is_empty() or (pal.size() == 1 and _is_air(pal[0])):
+ var secs = root.get("sections", [])
+ if not secs is Array:
+ continue
+ for s in secs:
+ # these values size the tile ranges of the plan: anything ChunkData.decode would refuse does not count
+ if not s is Dictionary or not ChunkData.valid_section_y(s.get("Y")):
+ continue
+ var bs = s.get("block_states", {})
+ var pal = bs.get("palette", []) if bs is Dictionary else []
+ if not pal is Array or pal.is_empty() or (pal.size() == 1 and _is_air(pal[0])):
continue
var y: int = s["Y"]
lo = mini(lo, y * 16)
diff --git a/scripts/render/chunk_data.gd b/scripts/render/chunk_data.gd
index 98b7f3f..5ea5b3c 100644
--- a/scripts/render/chunk_data.gd
+++ b/scripts/render/chunk_data.gd
@@ -1,6 +1,15 @@
class_name ChunkData
extends RefCounted
## One decoded chunk (1.18+ palette layout, 26.x quirks). Section block data is unpacked lazily.
+##
+## decode() checks what the GPU mesher later reads without bounds checks: section range, palette sizes, data array lengths.
+## A chunk that breaks these rules counts as absent.
+
+## sections of a dimension stay within this (the game allows -2032..2031 blocks)
+const MAX_SECTION_Y := 128
+## 16x16x16 blocks, 4x4x4 biome cells: a section cannot use more distinct values
+const MAX_BLOCK_PALETTE := 4096
+const MAX_BIOME_PALETTE := 64
static var unpack_ms := 0.0
static var unpack_count := 0
@@ -52,7 +61,8 @@ class Section:
blocks = Nbt.unpack(Nbt.longs(raw_data), bits, 4096)
ChunkData.unpack_ms += (Time.get_ticks_usec() - t0) / 1000.0
ChunkData.unpack_count += 1
- return pal[blocks[(ly << 8) | (lz << 4) | lx]]
+ var i := blocks[(ly << 8) | (lz << 4) | lx]
+ return pal[i] if i < pal.size() else 0 # like the GPU mesher: an index past the palette is air
static func _palette_entry(v: Variant) -> Dictionary:
@@ -79,6 +89,21 @@ static func _bits_for(n: int, minimum: int) -> int:
return maxi(b, minimum)
+## Bytes of a bit-packed array of `count` entries (no entry spans two longs).
+static func _packed_bytes(count: int, bits: int) -> int:
+ var per := 64 / bits
+ return (count + per - 1) / per * 8
+
+
+static func valid_section_y(y: Variant) -> bool:
+ return y is int and y >= -MAX_SECTION_Y and y <= MAX_SECTION_Y
+
+
+static func _reject(cx_: int, cz_: int, why: String) -> ChunkData:
+ push_warning("chunk %d,%d rejected: %s" % [cx_, cz_, why])
+ return null
+
+
## Same as decode(), but palette entries become StateRegistry state ids (full block states for the mesh renderer).
static func decode(raw: PackedByteArray, cx_: int, cz_: int, tbl: BlockTable, reg: StateRegistry = null) -> ChunkData:
var root := Nbt.parse(raw)
@@ -87,8 +112,8 @@ static func decode(raw: PackedByteArray, cx_: int, cz_: int, tbl: BlockTable, re
var status = root.get("Status", "minecraft:full")
if status is String and status != "minecraft:full" and status != "full":
return null
- var secs: Array = root.get("sections", [])
- if secs.is_empty():
+ var secs = root.get("sections", [])
+ if not secs is Array or secs.is_empty():
return null
var c := ChunkData.new()
c.cx = cx_
@@ -97,6 +122,8 @@ static func decode(raw: PackedByteArray, cx_: int, cz_: int, tbl: BlockTable, re
var lo := 1000
var hi := -1000
for s in secs:
+ if not s is Dictionary or not valid_section_y(s.get("Y")):
+ return _reject(cx_, cz_, "section without a valid Y")
var y: int = s["Y"]
lo = mini(lo, y)
hi = maxi(hi, y)
@@ -107,8 +134,14 @@ static func decode(raw: PackedByteArray, cx_: int, cz_: int, tbl: BlockTable, re
for s in secs:
var sec := Section.new()
var y: int = s["Y"]
- var bs: Dictionary = s.get("block_states", {})
- var palette: Array = bs.get("palette", [])
+ var bs = s.get("block_states", {})
+ var bio = s.get("biomes", {})
+ if not bs is Dictionary or not bio is Dictionary:
+ return _reject(cx_, cz_, "section with malformed states")
+ var palette = bs.get("palette", [])
+ var bpal = bio.get("palette", [])
+ if not palette is Array or palette.size() > MAX_BLOCK_PALETTE or not bpal is Array or bpal.size() > MAX_BIOME_PALETTE:
+ return _reject(cx_, cz_, "section with a malformed palette")
sec.pal.resize(palette.size())
for i in palette.size():
var e := _palette_entry(palette[i])
@@ -124,21 +157,27 @@ static func decode(raw: PackedByteArray, cx_: int, cz_: int, tbl: BlockTable, re
if palette.size() <= 1 or not bs.has("data"):
sec.uniform = sec.pal[0] if sec.pal.size() > 0 else 0
else:
- sec.raw_data = bs["data"]
sec.bits = _bits_for(palette.size(), 4)
- var bio: Dictionary = s.get("biomes", {})
- var bpal: Array = bio.get("palette", [])
+ if not bs["data"] is PackedByteArray or bs["data"].size() != _packed_bytes(4096, sec.bits):
+ return _reject(cx_, cz_, "block data of the wrong size")
+ sec.raw_data = bs["data"]
sec.biome_pal.resize(bpal.size())
for i in bpal.size():
sec.biome_pal[i] = tbl.biome_id(_palette_entry(bpal[i])["name"])
if bpal.size() > 1 and bio.has("data"):
- sec.biome_data = Nbt.unpack(Nbt.longs(bio["data"]), _bits_for(bpal.size(), 1), 64)
+ var bbits := _bits_for(bpal.size(), 1)
+ if not bio["data"] is PackedByteArray or bio["data"].size() != _packed_bytes(64, bbits):
+ return _reject(cx_, cz_, "biome data of the wrong size")
+ sec.biome_data = Nbt.unpack(Nbt.longs(bio["data"]), bbits, 64)
+ for v in sec.biome_data:
+ if v >= bpal.size():
+ return _reject(cx_, cz_, "biome index past the palette")
else:
sec.biome_uniform = sec.biome_pal[0] if sec.biome_pal.size() > 0 else 0
- if s.has("SkyLight") and (s["SkyLight"] as PackedByteArray).size() == 2048:
+ if s.get("SkyLight") is PackedByteArray and s["SkyLight"].size() == 2048:
sec.sky = s["SkyLight"]
top_sky = maxi(top_sky, y + 1)
- if s.has("BlockLight") and (s["BlockLight"] as PackedByteArray).size() == 2048:
+ if s.get("BlockLight") is PackedByteArray and s["BlockLight"].size() == 2048:
sec.blk = s["BlockLight"]
c.sections[y - lo] = sec
c.sky_fill = top_sky
diff --git a/scripts/render/gpu_mesher.gd b/scripts/render/gpu_mesher.gd
index 83fe595..f9d4d71 100644
--- a/scripts/render/gpu_mesher.gd
+++ b/scripts/render/gpu_mesher.gd
@@ -3,6 +3,9 @@ extends RefCounted
## Host side of shaders/mesh_chunks.glsl: packs the chunks around a list of target chunks, runs the two mesher passes
## (count, emit) and hands the quad buffers to the raster pass without leaving the GPU.
+## 180 bytes of buffers per quad; an 8x8 mega tile of dense terrain has about 1.1 million quads
+const MAX_QUADS := 8_000_000
+
var rd: RenderingDevice
var reg: StateRegistry
var table: BlockTable
@@ -68,7 +71,8 @@ func _ensure_tables() -> void:
## targets: chunks to mesh; offs: vec4 per target (map offset x, y, z-relative, 0).
-## Returns {"nquads", "vf", "vi", "qchunk" (RIDs, caller frees), "trans" (bytes: 16 uints per translucent quad, see mesh_chunks.glsl)}.
+## Returns {"nquads", "vf", "vi", "qchunk" (RIDs, caller frees), "trans" (bytes: 16 uints per translucent quad, see mesh_chunks.glsl)},
+## and "too_large": true (nothing drawn) when the chunks need more than MAX_QUADS quads.
func mesh(world: WorldReader, targets: Array[Vector2i], offs: PackedFloat32Array, row2: PackedFloat64Array, water_tex: int, lava_tex: int) -> Dictionary:
var out := {"nquads": 0, "vf": RID(), "vi": RID(), "qchunk": RID(), "trans": PackedByteArray()}
if targets.is_empty():
@@ -118,6 +122,12 @@ func mesh(world: WorldReader, targets: Array[Vector2i], offs: PackedFloat32Array
for r in temp + [b_targets, b_offs, b_counters, dummy]:
rd.free_rid(r)
return out
+ if nq > MAX_QUADS:
+ push_warning("GPU mesher: %d quads is over the limit of %d, not drawing these chunks" % [nq, MAX_QUADS])
+ for r in temp + [b_targets, b_offs, b_counters, dummy]:
+ rd.free_rid(r)
+ out["too_large"] = true
+ return out
# pass 1: emit
rd.buffer_update(b_counters, 0, 16, PackedInt32Array([0, 0, 0, 0]).to_byte_array())
diff --git a/scripts/render/gpu_world.gd b/scripts/render/gpu_world.gd
index 2fabd5f..45e344d 100644
--- a/scripts/render/gpu_world.gd
+++ b/scripts/render/gpu_world.gd
@@ -57,6 +57,11 @@ static func _pack_grid(world: WorldReader, gx0: int, gz0: int, gx1: int, gz1: in
continue
var pal_off := pal.size()
pal.append_array(s.pal)
+ # the shader adds an index of `bits` bits to pal_off without a check: keep every such index inside this
+ # section's palette (padding reads as state 0, air), however the block data was written
+ if s.bits > 0:
+ for _i in (1 << s.bits) - s.pal.size():
+ pal.append(0)
var data_off := -1
if not s.raw_data.is_empty():
data_off = data.size() / 4
diff --git a/scripts/render/iso_renderer.gd b/scripts/render/iso_renderer.gd
index 5ea57e8..cce7ee3 100644
--- a/scripts/render/iso_renderer.gd
+++ b/scripts/render/iso_renderer.gd
@@ -309,6 +309,7 @@ static func _f32_key(v: float, seq: int) -> int:
## Renders tiles [tx0, tx0+ntx) x [ty0, ty0+nty); one RGBA8 Image per tile, row-major (ty then tx).
+## Empty when the area could not be drawn: not the same as blank tiles, which delete their rows.
func render(tx0: int, ty0: int, ntx: int, nty: int) -> Array[Image]:
var w := ntx * TILE
var h := nty * TILE
@@ -350,6 +351,8 @@ func render(tx0: int, ty0: int, ntx: int, nty: int) -> Array[Image]:
var order := PackedInt32Array()
if gpu_mesh:
var g := gmesher.mesh(world, chunks, offs, PackedFloat64Array([m[6], m[7], m[8]]), reg.water_tex, reg.lava_tex)
+ if g.get("too_large", false):
+ return []
nquads = g["nquads"]
b_vf = g["vf"]
b_vi = g["vi"]
diff --git a/scripts/render/nbt.gd b/scripts/render/nbt.gd
index 5ed111c..f8c4e8d 100644
--- a/scripts/render/nbt.gd
+++ b/scripts/render/nbt.gd
@@ -3,6 +3,9 @@ extends RefCounted
## Minimal big-endian NBT reader.
## Compound -> Dictionary, List -> Array, Byte/Int array -> Packed*Array,
## LongArray -> PackedByteArray (raw big-endian, decode with long_at()).
+##
+## Region files are input from outside: every length is checked against the bytes left, and depth and value count are
+## limited, so a damaged file costs little. parse() returns {} for anything that does not fit (the chunk counts as absent).
const T_END := 0
const T_BYTE := 1
@@ -18,6 +21,13 @@ const T_COMPOUND := 10
const T_INT_ARRAY := 11
const T_LONG_ARRAY := 12
+## smallest encoding of a value of each tag, to check a list's length against the bytes left
+const MIN_BYTES := [0, 1, 2, 4, 8, 4, 8, 4, 2, 5, 1, 4, 4]
+## levels of nesting: chunks use about 10 (a few dozen with containers inside containers)
+const MAX_DEPTH := 128
+## list elements and compound entries of one chunk: a full-height chunk with every palette full stays below this
+const MAX_VALUES := 2_000_000
+
static func parse(bytes: PackedByteArray) -> Dictionary:
var sp := StreamPeerBuffer.new()
@@ -26,64 +36,118 @@ static func parse(bytes: PackedByteArray) -> Dictionary:
var tag := sp.get_u8()
if tag != T_COMPOUND:
return {}
- _read_string(sp)
- return _read_payload(sp, tag)
+ var r := Reader.new(sp, bytes.size())
+ r.read_string()
+ var root = r.read_payload(tag, 0)
+ if r.failed:
+ push_warning("NBT rejected: a length or nesting limit was exceeded")
+ return {}
+ return root
+
+
+class Reader:
+ extends RefCounted
+ var sp: StreamPeerBuffer
+ var size := 0
+ var values := 0
+ var failed := false
+ func _init(sp_: StreamPeerBuffer, size_: int) -> void:
+ sp = sp_
+ size = size_
-static func _read_string(sp: StreamPeerBuffer) -> String:
- var n := sp.get_u16()
- if n == 0:
- return ""
- return sp.get_utf8_string(n)
+ func read_string() -> String:
+ var n := sp.get_u16()
+ if n == 0:
+ return ""
+ if n > size - sp.get_position():
+ failed = true
+ return ""
+ return sp.get_utf8_string(n)
+ ## Reserves `n` values taking `unit` bytes each; false (and failed) when they cannot be there.
+ func reserve(n: int, unit: int) -> bool:
+ values += n
+ if n < 0 or n * unit > size - sp.get_position() or values > Nbt.MAX_VALUES:
+ failed = true
+ return false
+ return true
-static func _read_payload(sp: StreamPeerBuffer, tag: int) -> Variant:
- match tag:
- T_BYTE:
- return sp.get_8()
- T_SHORT:
- return sp.get_16()
- T_INT:
- return sp.get_32()
- T_LONG:
- return sp.get_64()
- T_FLOAT:
- return sp.get_float()
- T_DOUBLE:
- return sp.get_double()
- T_BYTE_ARRAY:
- var n := sp.get_32()
- return sp.get_data(n)[1] as PackedByteArray
- T_STRING:
- return _read_string(sp)
- T_LIST:
- var et := sp.get_u8()
- var n := sp.get_32()
- var arr := []
- arr.resize(n)
- for i in n:
- arr[i] = _read_payload(sp, et)
- return arr
- T_COMPOUND:
- var d := {}
- while true:
- var t := sp.get_u8()
- if t == T_END:
- break
- var key := _read_string(sp)
- d[key] = _read_payload(sp, t)
- return d
- T_INT_ARRAY:
- var n := sp.get_32()
- var a := PackedInt32Array()
- a.resize(n)
- for i in n:
- a[i] = sp.get_32()
- return a
- T_LONG_ARRAY:
- var n := sp.get_32()
- return sp.get_data(n * 8)[1] as PackedByteArray
- return null
+ func read_payload(tag: int, depth: int) -> Variant:
+ match tag:
+ Nbt.T_BYTE:
+ return sp.get_8()
+ Nbt.T_SHORT:
+ return sp.get_16()
+ Nbt.T_INT:
+ return sp.get_32()
+ Nbt.T_LONG:
+ return sp.get_64()
+ Nbt.T_FLOAT:
+ return sp.get_float()
+ Nbt.T_DOUBLE:
+ return sp.get_double()
+ Nbt.T_BYTE_ARRAY:
+ var n := sp.get_32()
+ if n < 0 or n > size - sp.get_position():
+ failed = true
+ return null
+ return sp.get_data(n)[1] as PackedByteArray
+ Nbt.T_STRING:
+ return read_string()
+ Nbt.T_LIST:
+ var et := sp.get_u8()
+ var n := sp.get_32()
+ if n <= 0: # a length of 0 or less is an empty list, with any element type
+ return []
+ if depth >= Nbt.MAX_DEPTH or et == Nbt.T_END or et > Nbt.T_LONG_ARRAY or not reserve(n, Nbt.MIN_BYTES[et]):
+ failed = true
+ return null
+ var arr := []
+ arr.resize(n)
+ for i in n:
+ arr[i] = read_payload(et, depth + 1)
+ if failed:
+ return null
+ return arr
+ Nbt.T_COMPOUND:
+ if depth >= Nbt.MAX_DEPTH:
+ failed = true
+ return null
+ var d := {}
+ while true:
+ if sp.get_position() >= size: # ran out before the end tag
+ failed = true
+ return null
+ var t := sp.get_u8()
+ if t == Nbt.T_END:
+ break
+ values += 1
+ if values > Nbt.MAX_VALUES:
+ failed = true
+ return null
+ var key := read_string()
+ d[key] = read_payload(t, depth + 1)
+ if failed:
+ return null
+ return d
+ Nbt.T_INT_ARRAY:
+ var n := sp.get_32()
+ if not reserve(n, 4):
+ return null
+ var a := PackedInt32Array()
+ a.resize(n)
+ for i in n:
+ a[i] = sp.get_32()
+ return a
+ Nbt.T_LONG_ARRAY:
+ var n := sp.get_32()
+ if n < 0 or n * 8 > size - sp.get_position():
+ failed = true
+ return null
+ return sp.get_data(n * 8)[1] as PackedByteArray
+ failed = true # not a tag
+ return null
## Converts a raw big-endian long array into signed 64-bit ints.
diff --git a/scripts/render/state_registry.gd b/scripts/render/state_registry.gd
index dcf8786..48c292f 100644
--- a/scripts/render/state_registry.gd
+++ b/scripts/render/state_registry.gd
@@ -25,6 +25,15 @@ const TINT_FIXED := 0x1000000
const DIR_VEC := [Vector3(0, -1, 0), Vector3(0, 1, 0), Vector3(0, 0, -1), Vector3(0, 0, 1), Vector3(-1, 0, 0), Vector3(1, 0, 0)]
const DIR_NAMES := {"down": 0, "up": 1, "north": 2, "south": 3, "west": 4, "east": 5}
+# Palette entries come from region files. The game has about 30000 states; these limits only stop runaway growth.
+const MAX_STATES := 200_000
+const MAX_NAME_LENGTH := 128
+const MAX_PROPERTIES := 32
+const MAX_PROPERTY_LENGTH := 64
+
+## a block name, as used in the paths of data/assets: [namespace:]name
+static var _name_re := RegEx.create_from_string("^([a-z0-9_.-]+:)?[a-z0-9_/.-]+$")
+
var data_dir := ""
var tex_names := PackedStringArray()
var tex_index := {}
@@ -55,6 +64,9 @@ var _defaults := {}
var _model_cache := {}
var _blockstates := {}
var unknown := {}
+## palette entries turned into air because they broke the limits above
+var rejected := 0
+var max_states := MAX_STATES
func load_dir(dir: String) -> bool:
@@ -142,8 +154,16 @@ func _add_state(full_name: String, is_air: bool) -> int:
return s_name.size() - 1
-## props: Dictionary of String -> String/bool/number (palette Properties). Returns the state id.
+static func valid_name(block_name: String) -> bool:
+ return block_name.length() <= MAX_NAME_LENGTH and not block_name.contains("..") and _name_re.search(block_name) != null
+
+
+## props: Dictionary of String -> String/bool/number (palette Properties). Returns the state id; air (0) for an entry
+## that is not a plausible block state.
func intern(block_name: String, given: Dictionary) -> int:
+ if given.size() > MAX_PROPERTIES or block_name.length() > MAX_NAME_LENGTH:
+ rejected += 1
+ return 0
var props := {}
var d = _defaults.get(block_name)
if d != null:
@@ -151,7 +171,11 @@ func intern(block_name: String, given: Dictionary) -> int:
props[k] = d[k]
for k in given:
var v = given[k]
- props[k] = v if v is String else (("true" if v else "false") if v is bool else str(v))
+ var text: String = v if v is String else (("true" if v else "false") if v is bool else str(v))
+ if String(k).length() > MAX_PROPERTY_LENGTH or text.length() > MAX_PROPERTY_LENGTH:
+ rejected += 1
+ return 0
+ props[k] = text
var keys := props.keys()
keys.sort()
var key := block_name
@@ -162,6 +186,9 @@ func intern(block_name: String, given: Dictionary) -> int:
var id = _lookup.get(key)
if id != null:
return id
+ if not valid_name(block_name) or s_name.size() >= max_states:
+ rejected += 1
+ return 0
var sid := _build(block_name, props)
_lookup[key] = sid
return sid
diff --git a/scripts/render/world_reader.gd b/scripts/render/world_reader.gd
index cd483ce..ad17881 100644
--- a/scripts/render/world_reader.gd
+++ b/scripts/render/world_reader.gd
@@ -2,6 +2,12 @@ class_name WorldReader
extends RefCounted
## Reads Anvil region files: raw chunk NBT, decoded chunks (cached) and per-block lookups.
+## a region file: the 8 KiB header and 1024 chunks of at most 255 sectors of 4 KiB
+const MAX_REGION_BYTES := 8192 + 1024 * 255 * 4096
+## one decompressed chunk: far above real chunks (the game moves anything over 1 MiB compressed to a separate file)
+const MAX_CHUNK_BYTES := 64 * 1024 * 1024
+## the game's world border (30 million blocks) in regions
+const MAX_REGION_COORD := 60000
var region_dir := ""
var table: BlockTable
@@ -27,12 +33,36 @@ func _region(rx: int, rz: int) -> PackedByteArray:
var path := region_dir.path_join("r.%d.%d.mca" % [rx, rz])
var data := PackedByteArray()
if FileAccess.file_exists(path):
- data = FileAccess.get_file_as_bytes(path)
+ data = read_region(path)
_regions[key] = data
return data
-## Decompressed NBT of chunk (lx, lz) of a region file image (empty when the chunk is absent).
+## The whole file, empty when it cannot be read or is larger than a region file can be.
+static func read_region(path: String) -> PackedByteArray:
+ var f := FileAccess.open(path, FileAccess.READ)
+ if f == null:
+ return PackedByteArray()
+ var n := f.get_length()
+ if n > MAX_REGION_BYTES:
+ push_warning("%s: %d bytes is too large for a region file" % [path, n])
+ return PackedByteArray()
+ return f.get_buffer(n)
+
+
+## [rx, rz] of a file named r...mca inside the world border; [] for any other name.
+static func region_coords(file_name: String) -> Array:
+ var p := file_name.split(".")
+ if p.size() != 4 or p[0] != "r" or p[3] != "mca" or not p[1].is_valid_int() or not p[2].is_valid_int():
+ return []
+ var rx := int(p[1])
+ var rz := int(p[2])
+ if rx < -MAX_REGION_COORD or rx > MAX_REGION_COORD or rz < -MAX_REGION_COORD or rz > MAX_REGION_COORD:
+ return []
+ return [rx, rz]
+
+
+## Decompressed NBT of chunk (lx, lz) of a region file image (empty when the chunk is absent or out of bounds).
static func raw_chunk(rg: PackedByteArray, lx: int, lz: int) -> PackedByteArray:
var raw := PackedByteArray()
if rg.size() < 8192:
@@ -40,19 +70,19 @@ static func raw_chunk(rg: PackedByteArray, lx: int, lz: int) -> PackedByteArray:
var idx := lx + lz * 32
var off := ((rg[idx * 4] << 16) | (rg[idx * 4 + 1] << 8) | rg[idx * 4 + 2]) * 4096
var sectors := rg[idx * 4 + 3]
- if off == 0 or sectors == 0 or off + 5 > rg.size():
+ if off < 8192 or sectors == 0 or off + 5 > rg.size():
return raw
var ln := (rg[off] << 24) | (rg[off + 1] << 16) | (rg[off + 2] << 8) | rg[off + 3]
var comp := rg[off + 4] & 0x7f
- if ln < 1 or off + 4 + ln > rg.size():
+ if ln < 2 or off + 4 + ln > rg.size(): # 1 = only the compression byte: the chunk lives in a separate file
return raw
var body := rg.slice(off + 5, off + 4 + ln)
if comp == 2:
- raw = body.decompress_dynamic(-1, FileAccess.COMPRESSION_DEFLATE)
+ raw = body.decompress_dynamic(MAX_CHUNK_BYTES, FileAccess.COMPRESSION_DEFLATE)
elif comp == 1:
- raw = body.decompress_dynamic(-1, FileAccess.COMPRESSION_GZIP)
+ raw = body.decompress_dynamic(MAX_CHUNK_BYTES, FileAccess.COMPRESSION_GZIP)
elif comp == 3:
- raw = body
+ raw = body if body.size() <= MAX_CHUNK_BYTES else PackedByteArray()
else:
push_warning("unsupported chunk compression %d at chunk %d,%d" % [comp, lx, lz])
return raw
diff --git a/scripts/store/tile_store.gd b/scripts/store/tile_store.gd
index 7b9a807..a92693f 100644
--- a/scripts/store/tile_store.gd
+++ b/scripts/store/tile_store.gd
@@ -17,9 +17,11 @@ var error := ""
var _db := Mysql.new()
var _host := "127.0.0.1"
var _port := 4000
-var _user := "root"
+## no default: the renderer only needs the tile tables, so a user has to be chosen for it (see docs/operations.md)
+var _user := ""
var _password := ""
var _schema := "dynmap"
+var _config_error := ""
var _sent := 0
var _t0 := 0
@@ -30,10 +32,15 @@ func configure(cfg: Dictionary) -> void:
_user = cfg.get("user", _user)
_password = cfg.get("password", _password)
_schema = cfg.get("database", _schema)
+ _config_error = cfg.get("error", "")
func connect_db() -> bool:
- error = ""
+ error = _config_error
+ if error == "" and _user == "":
+ error = 'no database user configured ("user" in the config or --db-user)'
+ if error != "":
+ return false
if not _db.open(_host, _port, _user, _password, _schema):
error = _db.error
return false
diff --git a/tests/run_tests.gd b/tests/run_tests.gd
new file mode 100644
index 0000000..bb71f6d
--- /dev/null
+++ b/tests/run_tests.gd
@@ -0,0 +1,630 @@
+extends SceneTree
+## Checks of everything that needs no GPU: file parsers, config handling, queue bookkeeping. From the repository root:
+## godot --headless --path . --import
+## godot --headless --path . -s tests/run_tests.gd
+## Feeding bad input is the point, so warnings and errors about rejected data in the output are expected.
+
+const TMP := "user://tests"
+
+var _checks := 0
+var _fails := 0
+
+
+class Longs:
+ var raw: PackedByteArray
+
+ func _init(raw_: PackedByteArray) -> void:
+ raw = raw_
+
+
+func _initialize() -> void:
+ DirAccess.make_dir_recursive_absolute(TMP)
+ _test_nbt()
+ _test_region()
+ _test_chunk()
+ _test_gpu_pack()
+ _test_scan()
+ _test_jar()
+ _test_registry()
+ _test_config()
+ _test_live_feed()
+ _test_watch_queue()
+ print("%d checks, %d failed" % [_checks, _fails])
+ quit(1 if _fails > 0 else 0)
+
+
+func _eq(name: String, got: Variant, want: Variant) -> void:
+ _checks += 1
+ if typeof(got) != typeof(want) or got != want:
+ _fails += 1
+ print("FAIL %s: got %s, wanted %s" % [name, got, want])
+
+
+func _ok(name: String, condition: bool) -> void:
+ _eq(name, condition, true)
+
+
+func _write(path: String, bytes: PackedByteArray) -> void:
+ var f := FileAccess.open(path, FileAccess.WRITE)
+ f.store_buffer(bytes)
+ f.close()
+
+
+func _write_text(path: String, text: String) -> void:
+ _write(path, text.to_utf8_buffer())
+
+
+# --- writers ---------------------------------------------------------------------------------------------------------
+
+
+func _be() -> StreamPeerBuffer:
+ var sp := StreamPeerBuffer.new()
+ sp.big_endian = true
+ return sp
+
+
+func _tag_of(v: Variant) -> int:
+ if v is Dictionary:
+ return Nbt.T_COMPOUND
+ if v is Array:
+ return Nbt.T_LIST
+ if v is String:
+ return Nbt.T_STRING
+ if v is int:
+ return Nbt.T_INT
+ if v is PackedByteArray:
+ return Nbt.T_BYTE_ARRAY
+ if v is Longs:
+ return Nbt.T_LONG_ARRAY
+ return Nbt.T_END
+
+
+func _put_string(sp: StreamPeerBuffer, s: String) -> void:
+ var b := s.to_utf8_buffer()
+ sp.put_u16(b.size())
+ sp.put_data(b)
+
+
+func _put_value(sp: StreamPeerBuffer, v: Variant) -> void:
+ if v is Dictionary:
+ for k: String in v:
+ sp.put_u8(_tag_of(v[k]))
+ _put_string(sp, k)
+ _put_value(sp, v[k])
+ sp.put_u8(Nbt.T_END)
+ elif v is Array:
+ sp.put_u8(_tag_of(v[0]) if not v.is_empty() else Nbt.T_END)
+ sp.put_32(v.size())
+ for e in v:
+ _put_value(sp, e)
+ elif v is String:
+ _put_string(sp, v)
+ elif v is int:
+ sp.put_32(v)
+ elif v is PackedByteArray:
+ sp.put_32(v.size())
+ sp.put_data(v)
+ elif v is Longs:
+ sp.put_32(v.raw.size() / 8)
+ sp.put_data(v.raw)
+
+
+func _nbt(root: Dictionary) -> PackedByteArray:
+ var sp := _be()
+ sp.put_u8(Nbt.T_COMPOUND)
+ sp.put_u16(0)
+ _put_value(sp, root)
+ return sp.data_array
+
+
+## A root compound whose only entry `v` has the given tag and raw payload (for payloads _put_value would not write).
+func _nbt_raw(tag: int, payload: PackedByteArray) -> PackedByteArray:
+ var sp := _be()
+ sp.put_u8(Nbt.T_COMPOUND)
+ sp.put_u16(0)
+ sp.put_u8(tag)
+ _put_string(sp, "v")
+ sp.put_data(payload)
+ sp.put_u8(Nbt.T_END)
+ return sp.data_array
+
+
+func _i32(v: int) -> PackedByteArray:
+ var sp := _be()
+ sp.put_32(v)
+ return sp.data_array
+
+
+## Section with `bits`-bit block data whose first entry is `first` (the array has the length the format requires).
+func _section(y: int, names: Array, first := 0) -> Dictionary:
+ var palette := []
+ for n in names:
+ palette.append({"Name": n})
+ var states := {"palette": palette}
+ if names.size() > 1:
+ var bits := ChunkData._bits_for(names.size(), 4)
+ var raw := PackedByteArray()
+ raw.resize(ChunkData._packed_bytes(4096, bits))
+ raw.fill(0)
+ raw[7] = first # lowest bits of the first long, big endian
+ states["data"] = Longs.new(raw)
+ return {"Y": y, "block_states": states, "biomes": {"palette": ["minecraft:plains"]}}
+
+
+func _chunk_nbt(sections: Variant) -> PackedByteArray:
+ return _nbt({"Status": "minecraft:full", "sections": sections})
+
+
+# --- NBT -------------------------------------------------------------------------------------------------------------
+
+
+func _test_nbt() -> void:
+ var longs := PackedByteArray()
+ longs.resize(16)
+ var v := Nbt.parse(_nbt({"a": 5, "s": "text", "l": [1, 2], "e": [], "c": {"x": PackedByteArray([1, 2])}, "n": Longs.new(longs)}))
+ _eq("nbt int", v.get("a"), 5)
+ _eq("nbt string", v.get("s"), "text")
+ _eq("nbt list", v.get("l"), [1, 2])
+ _eq("nbt empty list", v.get("e"), [])
+ _eq("nbt nested byte array", v.get("c", {}).get("x"), PackedByteArray([1, 2]))
+ _eq("nbt long array keeps raw bytes", v.get("n"), longs)
+
+ var huge := 0x7FFFFFFF
+ _eq("byte array longer than the data", Nbt.parse(_nbt_raw(Nbt.T_BYTE_ARRAY, _i32(huge))), {})
+ _eq("byte array of negative length", Nbt.parse(_nbt_raw(Nbt.T_BYTE_ARRAY, _i32(-1))), {})
+ _eq("int array longer than the data", Nbt.parse(_nbt_raw(Nbt.T_INT_ARRAY, _i32(huge))), {})
+ _eq("long array longer than the data", Nbt.parse(_nbt_raw(Nbt.T_LONG_ARRAY, _i32(huge))), {})
+ var list_of_ints := PackedByteArray([Nbt.T_INT])
+ list_of_ints.append_array(_i32(huge))
+ _eq("list longer than the data", Nbt.parse(_nbt_raw(Nbt.T_LIST, list_of_ints)), {})
+ var list_of_end := PackedByteArray([Nbt.T_END])
+ list_of_end.append_array(_i32(3))
+ _eq("non-empty list of the end tag", Nbt.parse(_nbt_raw(Nbt.T_LIST, list_of_end)), {})
+ var list_bad_type := PackedByteArray([200])
+ list_bad_type.append_array(_i32(1))
+ _eq("list of an unknown tag", Nbt.parse(_nbt_raw(Nbt.T_LIST, list_bad_type)), {})
+ var negative_list := PackedByteArray([Nbt.T_INT])
+ negative_list.append_array(_i32(-1))
+ _eq("negative list length means empty", Nbt.parse(_nbt_raw(Nbt.T_LIST, negative_list)).get("v"), [])
+ _eq("string longer than the data", Nbt.parse(_nbt_raw(Nbt.T_STRING, PackedByteArray([0xFF, 0xFF]))), {})
+ _eq("unknown tag", Nbt.parse(_nbt_raw(99, PackedByteArray())), {})
+
+ var truncated := _nbt({"a": 5})
+ truncated.resize(truncated.size() - 1)
+ _eq("compound without an end tag", Nbt.parse(truncated), {})
+ _eq("not a compound", Nbt.parse(PackedByteArray([Nbt.T_INT, 0, 0, 0, 0, 0, 0])), {})
+ _eq("empty input", Nbt.parse(PackedByteArray()), {})
+
+ _ok("nesting within the limit", not Nbt.parse(_deep(Nbt.MAX_DEPTH - 2)).is_empty())
+ _eq("nesting past the limit", Nbt.parse(_deep(Nbt.MAX_DEPTH + 5)), {})
+
+ var many := PackedByteArray([Nbt.T_BYTE])
+ many.append_array(_i32(Nbt.MAX_VALUES + 1))
+ var body := PackedByteArray()
+ body.resize(Nbt.MAX_VALUES + 1)
+ many.append_array(body)
+ _eq("too many values", Nbt.parse(_nbt_raw(Nbt.T_LIST, many)), {})
+
+
+func _deep(levels: int) -> PackedByteArray:
+ var sp := _be()
+ sp.put_u8(Nbt.T_COMPOUND)
+ sp.put_u16(0)
+ for _i in levels:
+ sp.put_u8(Nbt.T_COMPOUND)
+ _put_string(sp, "a")
+ for _i in levels + 1:
+ sp.put_u8(Nbt.T_END)
+ return sp.data_array
+
+
+# --- region files ----------------------------------------------------------------------------------------------------
+
+
+func _region_with(sector: int, length: int, comp: int, body: PackedByteArray) -> PackedByteArray:
+ var rg := PackedByteArray()
+ rg.resize(8192)
+ rg.fill(0)
+ rg[0] = (sector >> 16) & 0xFF
+ rg[1] = (sector >> 8) & 0xFF
+ rg[2] = sector & 0xFF
+ rg[3] = 1
+ var sp := _be()
+ sp.put_32(length)
+ sp.put_u8(comp)
+ sp.put_data(body)
+ rg.append_array(sp.data_array)
+ return rg
+
+
+func _test_region() -> void:
+ var nbt := _nbt({"a": 1})
+ var deflated := nbt.compress(FileAccess.COMPRESSION_DEFLATE)
+ var gz := nbt.compress(FileAccess.COMPRESSION_GZIP)
+ _eq("deflate chunk", WorldReader.raw_chunk(_region_with(2, deflated.size() + 1, 2, deflated), 0, 0), nbt)
+ _eq("gzip chunk", WorldReader.raw_chunk(_region_with(2, gz.size() + 1, 1, gz), 0, 0), nbt)
+ _eq("uncompressed chunk", WorldReader.raw_chunk(_region_with(2, nbt.size() + 1, 3, nbt), 0, 0), nbt)
+ _eq("absent chunk", WorldReader.raw_chunk(_region_with(2, nbt.size() + 1, 3, nbt), 1, 0), PackedByteArray())
+ _eq("too short for a header", WorldReader.raw_chunk(PackedByteArray([1, 2, 3]), 0, 0), PackedByteArray())
+ _eq("offset inside the header", WorldReader.raw_chunk(_region_with(1, nbt.size() + 1, 3, nbt), 0, 0), PackedByteArray())
+ _eq("offset past the file", WorldReader.raw_chunk(_region_with(9999, nbt.size() + 1, 3, nbt), 0, 0), PackedByteArray())
+ _eq("length past the file", WorldReader.raw_chunk(_region_with(2, 0x7FFFFFF0, 3, nbt), 0, 0), PackedByteArray())
+ _eq("only a compression byte (external file)", WorldReader.raw_chunk(_region_with(2, 1, 0x82, PackedByteArray()), 0, 0), PackedByteArray())
+ _eq("unknown compression", WorldReader.raw_chunk(_region_with(2, nbt.size() + 1, 77, nbt), 0, 0), PackedByteArray())
+
+ var big := PackedByteArray()
+ big.resize(WorldReader.MAX_CHUNK_BYTES + 4096)
+ big.fill(0)
+ var bomb := big.compress(FileAccess.COMPRESSION_DEFLATE)
+ big = PackedByteArray()
+ _eq("output larger than the limit", WorldReader.raw_chunk(_region_with(2, bomb.size() + 1, 2, bomb), 0, 0), PackedByteArray())
+
+ _eq("region name", WorldReader.region_coords("r.-1.2.mca"), [-1, 2])
+ for bad in ["r.1.mca", "x.1.2.mca", "r.a.2.mca", "r.1.2.mcc", "r.999999.0.mca", "r.0.-99999999999999999999.mca"]:
+ _eq("region name " + bad, WorldReader.region_coords(bad), [])
+ var p := TMP.path_join("r.0.0.mca")
+ _write(p, PackedByteArray([1, 2, 3]))
+ _eq("read region file", WorldReader.read_region(p), PackedByteArray([1, 2, 3]))
+ _eq("missing region file", WorldReader.read_region(TMP.path_join("none.mca")), PackedByteArray())
+
+
+# --- chunks ----------------------------------------------------------------------------------------------------------
+
+
+func _data_dir() -> String:
+ var d := TMP.path_join("data")
+ DirAccess.make_dir_recursive_absolute(d.path_join("assets/blockstates"))
+ DirAccess.make_dir_recursive_absolute(d.path_join("assets/models/block"))
+ _write_text(d.path_join("textures.json"), '["missingno","block/water_still","block/lava_still"]')
+ var tex := PackedByteArray()
+ tex.resize(3 * 1024)
+ tex.fill(255)
+ _write(d.path_join("textures.bin"), tex)
+ _write_text(d.path_join("block_defaults.json"), "{}")
+ for n in ["stone", "dirt"]:
+ _write_text(d.path_join("assets/blockstates/%s.json" % n), '{"variants":{"":{"model":"minecraft:block/%s"}}}' % n)
+ _write_text(d.path_join("assets/models/block/%s.json" % n), "{}")
+ # outside assets/: a palette entry must not be able to reach this
+ _write_text(d.path_join("outside.json"), '{"variants":{"":{"model":"minecraft:block/stone"}}}')
+ return d
+
+
+func _registry() -> StateRegistry:
+ var reg := StateRegistry.new()
+ reg.load_dir(_data_dir())
+ return reg
+
+
+func _decode(sections: Variant, reg: StateRegistry) -> ChunkData:
+ return ChunkData.decode(_chunk_nbt(sections), 0, 0, BlockTable.new(), reg)
+
+
+func _test_chunk() -> void:
+ var reg := _registry()
+ var c := _decode([_section(0, ["minecraft:air", "minecraft:stone"], 1), _section(1, ["minecraft:dirt"])], reg)
+ _ok("valid chunk decodes", c != null)
+ if c != null:
+ var stone := reg.intern("minecraft:stone", {})
+ var dirt := reg.intern("minecraft:dirt", {})
+ _eq("first block from the palette", c.block(0, 0, 0), stone)
+ _eq("other blocks", c.block(1, 0, 0), 0)
+ _eq("uniform section", c.block(5, 20, 5), dirt)
+ _eq("above the sections", c.block(0, 100, 0), 0)
+
+ var past := _decode([_section(0, ["minecraft:air", "minecraft:stone"], 15)], reg)
+ _ok("index past the palette still decodes", past != null)
+ if past != null:
+ _eq("index past the palette reads as air", past.block(0, 0, 0), 0)
+
+ _eq("Y out of range", _decode([_section(ChunkData.MAX_SECTION_Y + 1, ["minecraft:stone"])], reg), null)
+ _eq("Y far out of range", _decode([_section(1 << 30, ["minecraft:stone"])], reg), null)
+ _eq("the most negative Y", ChunkData.valid_section_y(-9223372036854775807 - 1), false)
+ _eq("Y at the limit", ChunkData.valid_section_y(-ChunkData.MAX_SECTION_Y), true)
+ _eq("sections not a list", _decode({"Y": 0}, reg), null)
+ _eq("section not a compound", _decode([1, 2], reg), null)
+ _eq("section without Y", _decode([{"block_states": {}}], reg), null)
+ _eq("Y not a number", _decode([{"Y": "zero"}], reg), null)
+ _eq("palette not a list", _decode([{"Y": 0, "block_states": {"palette": 1}}], reg), null)
+ _eq("states not a compound", _decode([{"Y": 0, "block_states": 1}], reg), null)
+
+ var short_data := _section(0, ["minecraft:air", "minecraft:stone"])
+ var raw: PackedByteArray = short_data["block_states"]["data"].raw
+ raw.resize(raw.size() - 8)
+ short_data["block_states"]["data"] = Longs.new(raw)
+ _eq("block data too short", _decode([short_data], reg), null)
+ var data_as_bytes := _section(0, ["minecraft:air", "minecraft:stone"])
+ data_as_bytes["block_states"]["data"] = 7
+ _eq("block data not an array", _decode([data_as_bytes], reg), null)
+
+ var wide := []
+ for i in ChunkData.MAX_BLOCK_PALETTE + 1:
+ wide.append({"Name": "minecraft:stone"})
+ _eq("block palette too large", _decode([{"Y": 0, "block_states": {"palette": wide}}], reg), null)
+
+ var sec := _section(0, ["minecraft:stone"])
+ var biome_raw := PackedByteArray()
+ biome_raw.resize(8)
+ biome_raw.fill(0)
+ sec["biomes"] = {"palette": ["minecraft:plains", "minecraft:desert"], "data": Longs.new(biome_raw)}
+ _ok("biome data decodes", _decode([sec], reg) != null)
+ var bad_biome := _section(0, ["minecraft:stone"])
+ var three := PackedByteArray()
+ three.resize(8)
+ three.fill(0)
+ three[7] = 3 # 2 bits for a palette of 3: index 3 is past it
+ bad_biome["biomes"] = {"palette": ["minecraft:plains", "minecraft:desert", "minecraft:forest"], "data": Longs.new(three)}
+ _eq("biome index past the palette", _decode([bad_biome], reg), null)
+ var long_biome := _section(0, ["minecraft:stone"])
+ long_biome["biomes"] = {"palette": ["minecraft:plains", "minecraft:desert"], "data": Longs.new(PackedByteArray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]))}
+ _eq("biome data of the wrong size", _decode([long_biome], reg), null)
+
+
+func _test_gpu_pack() -> void:
+ var reg := _registry()
+ var c := _decode([_section(0, ["minecraft:air", "minecraft:stone", "minecraft:dirt"])], reg)
+ var world := WorldReader.new("", BlockTable.new())
+ world._chunks[Vector2i(0, 0)] = c
+ var chunks: Array[Vector2i] = [Vector2i(0, 0)]
+ var packed := GpuWorld.pack_set(world, chunks)
+ var pal: PackedInt32Array = packed["pal"].to_int32_array()
+ _eq("palette padded to every index the data can hold", pal.size(), 16)
+ _eq("palette entries kept", pal[1], reg.intern("minecraft:stone", {}))
+ _eq("padding reads as air", pal[15], 0)
+ _eq("block data as long as the shader indexes", packed["data"].size(), 2048)
+
+
+func _test_scan() -> void:
+ var dir := TMP.path_join("scan")
+ DirAccess.make_dir_recursive_absolute(dir)
+ var nbt := _chunk_nbt([_section(0, ["minecraft:stone"]), _section(1 << 30, ["minecraft:stone"]), _section(2, ["minecraft:air"])])
+ var deflated := nbt.compress(FileAccess.COMPRESSION_DEFLATE)
+ _write(dir.path_join("r.0.0.mca"), _region_with(2, deflated.size() + 1, 2, deflated))
+ _write(dir.path_join("r.999999.0.mca"), _region_with(2, deflated.size() + 1, 2, deflated))
+ var scan := ScanCache.build(ProjectSettings.globalize_path(dir))
+ _eq("scan keeps only region files inside the world border", scan.count(), 1)
+ _eq("scan ignores a section outside the Y range", [scan.min_y(), scan.max_y()], [0, 16])
+
+
+# --- build-data's jar reader -----------------------------------------------------------------------------------------
+
+
+## entries: [name, stored bytes, optional declared size, optional method]
+func _zip(entries: Array, cd_offset_delta := 0) -> PackedByteArray:
+ var body := StreamPeerBuffer.new()
+ var cd := StreamPeerBuffer.new()
+ for e in entries:
+ var name: PackedByteArray = (e[0] as String).to_utf8_buffer()
+ var data: PackedByteArray = e[1]
+ var declared: int = e[2] if e.size() > 2 else data.size()
+ var method: int = e[3] if e.size() > 3 else 0
+ var at := body.get_position()
+ body.put_u32(0x04034B50)
+ for v in [20, 0, method, 0, 0]:
+ body.put_u16(v)
+ body.put_u32(0) # crc
+ body.put_u32(data.size())
+ body.put_u32(declared)
+ body.put_u16(name.size())
+ body.put_u16(0)
+ body.put_data(name)
+ body.put_data(data)
+ cd.put_u32(0x02014B50)
+ for v in [20, 20, 0, method, 0, 0]:
+ cd.put_u16(v)
+ cd.put_u32(0)
+ cd.put_u32(data.size())
+ cd.put_u32(declared)
+ cd.put_u16(name.size())
+ for v in [0, 0, 0, 0]:
+ cd.put_u16(v)
+ cd.put_u32(0)
+ cd.put_u32(at)
+ cd.put_data(name)
+ var out := StreamPeerBuffer.new()
+ out.put_data(body.data_array)
+ out.put_data(cd.data_array)
+ out.put_u32(0x06054B50)
+ out.put_u16(0)
+ out.put_u16(0)
+ out.put_u16(entries.size())
+ out.put_u16(entries.size())
+ out.put_u32(cd.get_size())
+ out.put_u32(body.get_size() + cd_offset_delta)
+ out.put_u16(0)
+ return out.data_array
+
+
+func _open_jar(bytes: PackedByteArray) -> JarReader:
+ var p := TMP.path_join("t.jar")
+ _write(p, bytes)
+ var j := JarReader.new()
+ return j if j.open(p) else null
+
+
+func _test_jar() -> void:
+ var text := "{}".to_utf8_buffer()
+ var j := _open_jar(_zip([
+ ["assets/minecraft/blockstates/a.json", text],
+ ["assets/minecraft/blockstates/../../../../evil.json", text],
+ ["../evil.json", text],
+ ["/abs.json", text],
+ ["c:/abs.json", text],
+ ["a\\..\\evil.json", text],
+ ["big.json", text, JarReader.MAX_ENTRY_BYTES + 1, 8],
+ ]))
+ _ok("jar opens", j != null)
+ if j != null:
+ _eq("only safe names are indexed", Array(j.names()).filter(func(n: String) -> bool: return n != "big.json"), ["assets/minecraft/blockstates/a.json"])
+ _eq("stored entry", j.read("assets/minecraft/blockstates/a.json"), text)
+ _eq("declared size over the limit", j.read("big.json"), PackedByteArray())
+ _eq("unknown entry", j.read("nope"), PackedByteArray())
+ _eq("central directory past the file", _open_jar(_zip([["a", text]], 1 << 20)), null)
+ _eq("not an archive", _open_jar("not a zip file, long enough to search for a directory".to_utf8_buffer()), null)
+ # the central record of one entry: 46 bytes and its name, in front of the 22 bytes of the end record
+ var cut := _zip([["a.json", text]])
+ var record := cut.size() - 22 - 46 - "a.json".length()
+ cut[record + 28] = 0xFF # name length: reaches past the file
+ cut[record + 29] = 0xFF
+ _eq("entry name past the file", _open_jar(cut), null)
+ var oob := _zip([["a.json", text]])
+ oob[record + 42] = 0xFF # local header offset: past the file
+ oob[record + 43] = 0xFF
+ var jo := _open_jar(oob)
+ _ok("jar with a bad local offset opens", jo != null)
+ if jo != null:
+ _eq("local header past the file", jo.read("a.json"), PackedByteArray())
+
+ var zp := TMP.path_join("real.jar")
+ var packer := ZIPPacker.new()
+ packer.open(zp)
+ packer.start_file("assets/minecraft/blockstates/b.json")
+ packer.write_file('{"variants":{}}'.to_utf8_buffer())
+ packer.close_file()
+ packer.close()
+ var real := JarReader.new()
+ _ok("zip from another writer opens", real.open(zp))
+ _eq("deflated entry", real.read("assets/minecraft/blockstates/b.json"), '{"variants":{}}'.to_utf8_buffer())
+
+
+# --- block states ----------------------------------------------------------------------------------------------------
+
+
+func _test_registry() -> void:
+ var reg := _registry()
+ _ok("known block", reg.intern("minecraft:stone", {}) > 0)
+ _eq("same state, same id", reg.intern("minecraft:stone", {}), reg.intern("minecraft:stone", {}))
+ var before := reg.state_count()
+ _eq("name leaving the data directory", reg.intern("minecraft:../../outside", {}), 0)
+ _eq("name with a separator trick", reg.intern("minecraft:a/../../outside", {}), 0)
+ _eq("name with odd characters", reg.intern("minecraft:Stone Block", {}), 0)
+ _eq("name too long", reg.intern("minecraft:" + "a".repeat(200), {}), 0)
+ var props := {}
+ for i in StateRegistry.MAX_PROPERTIES + 1:
+ props["p%d" % i] = "1"
+ _eq("too many properties", reg.intern("minecraft:stone", props), 0)
+ _eq("property value too long", reg.intern("minecraft:stone", {"p": "a".repeat(100)}), 0)
+ _eq("rejected entries add no states", reg.state_count(), before)
+ _ok("rejected entries are counted", reg.rejected > 0)
+ var unknown := reg.intern("minecraft:not_in_the_data", {})
+ _ok("unknown block is its own state", unknown > 0)
+ _eq("unknown block draws nothing", reg.s_air[unknown], 1)
+ reg.max_states = reg.state_count()
+ _eq("limit on the number of states", reg.intern("minecraft:another_block", {}), 0)
+ _eq("existing states still resolve", reg.intern("minecraft:not_in_the_data", {}), unknown)
+
+
+# --- database settings -----------------------------------------------------------------------------------------------
+
+
+func _args(words: Array) -> Args:
+ return Args.parse(PackedStringArray(words))
+
+
+func _test_config() -> void:
+ OS.unset_environment("DYNMAP_DB_PASSWORD")
+ OS.unset_environment("DYNMAP_DB_PASSWORD_FILE")
+ var cfg := {"db": {"host": "tidb", "port": 4000, "user": "renderer", "database": "dynmap"}}
+ var db := MapDef.db_config(_args(["run"]), cfg)
+ _eq("host from the config", db.get("host"), "tidb")
+ _eq("user from the config", db.get("user"), "renderer")
+ _ok("no password configured", not db.has("password"))
+ _eq("the config is not modified", cfg["db"].has("password"), false)
+
+ var over := MapDef.db_config(_args(["run", "--db-host", "h", "--db-port", "5", "--db-user", "u"]), cfg)
+ _eq("options override the config", [over.get("host"), over.get("port"), over.get("user")], ["h", 5, "u"])
+ _ok("no password option", not MapDef.db_config(_args(["run", "--db-password", "x"]), cfg).has("password"))
+ _ok("password text in the config is ignored", not MapDef.db_config(_args(["run"]), {"db": {"password": "x"}}).has("password"))
+
+ var pf := TMP.path_join("db_password")
+ _write_text(pf, "from-file\n")
+ var with_file := {"db": {"user": "renderer", "password_file": pf}}
+ _eq("password from the config's file", MapDef.db_config(_args(["run"]), with_file).get("password"), "from-file")
+ OS.set_environment("DYNMAP_DB_PASSWORD_FILE", pf)
+ _eq("password from the file in the environment", MapDef.db_config(_args(["run"]), cfg).get("password"), "from-file")
+ OS.set_environment("DYNMAP_DB_PASSWORD", "from-env")
+ _eq("the variable wins", MapDef.db_config(_args(["run"]), with_file).get("password"), "from-env")
+ OS.unset_environment("DYNMAP_DB_PASSWORD")
+ OS.unset_environment("DYNMAP_DB_PASSWORD_FILE")
+
+ var missing := MapDef.db_config(_args(["run"]), {"db": {"user": "renderer", "password_file": TMP.path_join("none")}})
+ _ok("unreadable password file is an error", missing.has("error"))
+ var store := TileStore.new()
+ store.configure(missing)
+ _eq("no connection without the password", store.connect_db(), false)
+ _ok("the store reports why", store.error.contains("password file"))
+ var nobody := TileStore.new()
+ nobody.configure({"host": "tidb"})
+ _eq("no connection without a user", nobody.connect_db(), false)
+ _ok("the store asks for a user", nobody.error.contains("user"))
+
+
+# --- live feed -------------------------------------------------------------------------------------------------------
+
+
+func _test_live_feed() -> void:
+ _ok("wss", LiveFeed.allowed_url("wss://map.example.net/up/ws"))
+ _ok("ws to this machine", LiveFeed.allowed_url("ws://127.0.0.1:3000/up/ws"))
+ _eq("ws to another host", LiveFeed.allowed_url("ws://map.example.net/up/ws"), false)
+ _eq("ws with a look-alike host", LiveFeed.allowed_url("ws://127.0.0.1.example.net/up/ws"), false)
+ _eq("other scheme", LiveFeed.allowed_url("http://map.example.net/up/ws"), false)
+ var feed := LiveFeed.new("ws://map.example.net/up/ws")
+ feed.watch("main")
+ _eq("insecure feed follows nothing", feed.healthy(), false)
+
+ var good := {"x": 1.5, "y": 64, "z": -2.0}
+ _eq("players with coordinates", LiveFeed.valid_players([good, {"x": 1}, {"x": "1", "y": 2, "z": 3}, "text", 5, null, {"x": INF, "y": 0, "z": 0}]), [good])
+ var crowd := []
+ for i in LiveFeed.MAX_PLAYERS + 10:
+ crowd.append(good)
+ _eq("limit on players", LiveFeed.valid_players(crowd).size(), LiveFeed.MAX_PLAYERS)
+
+ var ok_feed := LiveFeed.new("wss://map.example.net/up/ws")
+ var w := {"players": []}
+ ok_feed._message(w, '{"type":"players","players":[{"x":1,"y":2,"z":3},{"x":"a"}]}')
+ _eq("message keeps valid players", w["players"].size(), 1)
+ ok_feed._message(w, '{"type":5,"players":[]}')
+ _eq("message of another type", w["players"].size(), 1)
+ ok_feed._message(w, "not json")
+ _eq("message that is not JSON", w["players"].size(), 1)
+
+
+# --- resident updater's queue ----------------------------------------------------------------------------------------
+
+
+func _test_watch_queue() -> void:
+ var state := TMP.path_join("state")
+ DirAccess.make_dir_recursive_absolute(state)
+ DirAccess.remove_absolute(state.path_join("watch-7.json")) # from an earlier run of these checks
+ var def := MapDef.new()
+ def.id = 7
+ var job := WatchJob.new()
+ _ok("map added", job.add(def, state))
+ var ms: WatchJob.MapState = job.maps[0]
+ var a := Vector2i(1, 1)
+ var b := Vector2i(2, 2)
+ var c := Vector2i(3, 3)
+ var order := [a, b, c]
+ for m in order:
+ ms.pending[m] = 100.0
+ var first := job._next_group(ms, order)
+ _eq("a batch without failures", first.size(), order.size())
+ ms.attempts[b] = 1
+ var alone := job._next_group(ms, order)
+ _eq("a tile the process died on goes alone", alone.size(), 1)
+ _eq("which one", alone[0], b)
+
+ job._save(ms)
+ var again := WatchJob.new()
+ _ok("map added from the saved state", again.add(def, state))
+ var ms2: WatchJob.MapState = again.maps[0]
+ _eq("pending survives a restart", ms2.pending.size(), 3)
+ _eq("the count survives a restart", ms2.attempts.get(b, 0), 1)
+
+ ms2.attempts[b] = WatchJob.MAX_ATTEMPTS - 1
+ again._drop_failing(ms2)
+ _ok("below the limit it stays", ms2.pending.has(b))
+ ms2.attempts[b] = WatchJob.MAX_ATTEMPTS
+ again._drop_failing(ms2)
+ _eq("at the limit it is dropped", ms2.pending.has(b), false)
+ _eq("the others stay", ms2.pending.size(), 2)
+ _eq("no count left", ms2.attempts.is_empty(), true)
diff --git a/tests/run_tests.gd.uid b/tests/run_tests.gd.uid
new file mode 100644
index 0000000..2f11059
--- /dev/null
+++ b/tests/run_tests.gd.uid
@@ -0,0 +1 @@
+uid://65y3pho660vk