Files
romm/backend/utils/filesystem.py
Georges-Antoine Assi e232a52656 fix(docker): boot when the container runs as a non-default UID (#5189)
* fix(docker): boot when the container runs as a non-default UID

Unraid runs the container as 99:100, which can't write to the image's
/romm (owned by 1000, mode 755), only to the mounted subfolders. The
PSP pending dir at /romm/cache/retroarch_sync was created at import
time, so every gunicorn worker failed to boot.

- Buffer pending PSP save files under the user's assets folder
  (assets/users/<user>/retroarch/psp_pending/), beside the other
  RetroArch Cloud Sync files and outside the client-reachable blob
  categories.
- Move the zip and rom-converto download caches to /tmp/romm/cache,
  and point nginx's internal /cache/ alias there.
- Put gunicorn's control socket in /tmp/gunicorn instead of
  $HOME/.gunicorn, since HOME is / for that UID.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(docker): honor ROMM_TMP_PATH for caches, explain an unwritable sync folder

- The download caches live under $ROMM_TMP_PATH/cache when it's set,
  so installs with a small Docker disk (Unraid's docker.img) can point
  them at a share. The entrypoint exports the same path for nginx's
  /cache/ alias.
- With ENABLE_SYNC_FOLDER_WATCHER on and /romm/sync not writable, /init
  warns and skips the watcher instead of dying on mkdir under errexit.
- The compose example lists the /romm/sync mount the sync features need.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(sync): cover reading back and clearing buffered PSP files

Addresses Greptile's review on #5189.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): apply code-review findings to PSP pending buffer

Remove the emptied psp_pending folder after a merge, define the sync
folder path once in init, update the architecture doc's PSP and blob
locations, and drop a stale .gitignore entry.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(sync): apply simplify findings to PSP pending cleanup

Clear the buffered folder with remove_directory, let the startup check
own creating the sync folder, and reword the test fixture docstring.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): cap buffered PSP files and drop them on delete

Buffered files for an unresolved save folder now count against the
bundle limits, so a folder can't fill the assets share and then fail
every merge once it resolves. A DELETE also removes the buffered copy,
so a deleted file isn't merged back when the folder resolves.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(docker): check the sync folder for push-pull sync too

ENABLE_SYNC_PUSH_PULL keeps SSH keys and device saves under /romm/sync
as well, so an unwritable folder now disables it with the watcher and
warns at boot instead of failing when the task runs.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(docker): strip whitespace from env vars like the backend does

The backend strips every variable it reads, while the init script and
nginx templates used raw values, so a padded ROMM_TMP_PATH sent nginx's
/cache/ alias somewhere the backend never writes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* chore(config): drop the CACHE_BASE_PATH comment

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* docs(docker): say which backend config strips env whitespace

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* revert(docker): drop the entrypoint env whitespace trimming

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): apply pr-ready code-review findings

Gate push-pull on its SSH keys path rather than a writable sync folder,
accept the same truthy values as the backend, and clear only the merged
PSP pending files so another worker's buffered file survives.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor: apply pr-ready simplify findings

Share one truthy pattern across init's flag checks (the watcher gates
now accept the same values as the backend), disable gunicorn's unused
control socket instead of placing it, derive the converts redirect from
its own cache path, and factor the unknown PSP folder in tests.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* docs(docker): apply pr-ready humanizer pass to the sync mount note

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(fs): create handler base folders on first write, skip leftover temp files

FSHandler no longer mkdirs its base path when constructed, so a module-level
handler rooted at an unmounted or unwritable folder can't take down boot;
every write path already creates its parent folders. Blob listings skip
.romm_tmp_ files a crashed write left behind, so they are never merged into
a PSP bundle or advertised in the sync manifest. The prefix now lives in one
TEMP_FILE_PREFIX constant.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 16:48:50 -04:00

207 lines
7.2 KiB
Python

import errno
import os
import re
import shutil
from collections.abc import Iterator
from pathlib import Path
from logger.logger import log
# Container file extensions treated as compressed archives across modules
# (roms_handler for hashing decisions, rahasher for skipping disc-platform
# buffer-hash attempts, feeds for PKGi passthrough).
COMPRESSED_FILE_EXTENSIONS: frozenset[str] = frozenset(
(".7z", ".bz2", ".gz", ".rar", ".tar", ".zip", ".xz", ".tgz", ".tbz2", ".txz")
)
# str.endswith takes a tuple, never a set, so it is built once here.
COMPRESSED_FILE_SUFFIXES: tuple[str, ...] = tuple(COMPRESSED_FILE_EXTENSIONS)
# tempfile.mkstemp creates files 0600, too narrow for the nginx user to read.
SERVED_FILE_MODE = 0o644
# Prefix of in-progress writes and staged conversions, renamed into place once
# complete. Scans skip dot-prefixed names, so these stay unseen.
TEMP_FILE_PREFIX = ".romm_tmp_"
def iter_files(path: str, recursive: bool = False) -> Iterator[tuple[Path, str]]:
"""List files in a directory.
Yields tuples where the first element is the path to the directory where the file is located,
and the second element is the name of the file.
"""
for root, _, files in os.walk(path, topdown=True):
for file in files:
yield Path(root), file
if not recursive:
break
def iter_directories(path: str, recursive: bool = False) -> Iterator[tuple[Path, str]]:
"""List directories in a directory.
Yields tuples where the first element is the path to the directory where the directory is located,
and the second element is the name of the directory.
"""
for root, dirs, _ in os.walk(path, topdown=True):
for directory in dirs:
yield Path(root), directory
if not recursive:
break
# errno values that mean "hardlink not possible here, fall back to copy".
# EXDEV: cross-device link. EPERM: filesystem doesn't permit/support hardlinks
# (e.g. FAT32, exFAT, some network mounts). EOPNOTSUPP/ENOTSUP: same, on BSD/macOS.
# EMLINK: source already has the maximum number of hardlinks for the filesystem.
LINK_FALLBACK_ERRNOS: frozenset[int] = frozenset(
e
for e in (
getattr(errno, "EXDEV", None),
getattr(errno, "EPERM", None),
getattr(errno, "EOPNOTSUPP", None),
getattr(errno, "ENOTSUP", None),
getattr(errno, "EMLINK", None),
getattr(errno, "EACCES", None),
)
if e is not None
)
def rel_platform_folder(fs_path: str, platform_fs_path: str) -> str:
"""The part of a rom's folder that sits below its platform folder.
Args:
fs_path: The rom's folder.
platform_fs_path: The platform folder holding the metadata export files.
Returns:
`Disks/Set A` for a rom nested by a custom library structure, empty for one
sitting directly in the platform folder.
"""
rel = fs_path.removeprefix(f"{platform_fs_path}/")
return "" if rel in (fs_path, platform_fs_path) else rel
def join_rel_path(*parts: str) -> str:
"""Join the non-empty parts of a path written into an export file."""
return "/".join(part for part in parts if part)
def link_or_copy_file(source: Path, dest: Path) -> None:
"""Place ``source`` at ``dest`` via hardlink (preferred) or copy (fallback),
atomically replacing ``dest`` if it already exists. Caller is responsible
for creating ``dest.parent``.
Hardlinking is preferred because it's instantaneous and uses no extra disk
space, but only works within a single filesystem. If linking isn't possible,
we transparently fall back to ``shutil.copy2`` (preserving metadata).
Overwriting is atomic: we link/copy to a tempfile in dest's directory, then
rename it onto dest, which mirrors shutil.copy2's overwrite-on-exists
behavior.
"""
tmp_path = dest.parent / f".romm_link_tmp_{os.urandom(8).hex()}"
try:
try:
os.link(source, tmp_path)
except OSError as exc:
if exc.errno not in LINK_FALLBACK_ERRNOS:
raise
shutil.copy2(source, tmp_path)
os.replace(tmp_path, dest)
except BaseException:
try:
os.unlink(tmp_path)
except OSError:
pass
raise
def place_export_asset(source: Path, dest: Path) -> bool:
"""Link or copy an exported asset to ``dest``, keeping one already there.
Returns: whether ``dest`` holds the asset afterwards.
"""
if dest.exists():
return True
# Metadata scanned before unfetched media paths were cleared can still
# point at files that were never downloaded.
if not source.is_file():
log.debug(f"Skipping asset {source}: source file is missing")
return False
dest.parent.mkdir(parents=True, exist_ok=True)
try:
link_or_copy_file(source, dest)
return True
except OSError as e:
log.warning(f"Failed to copy {source} -> {dest}: {e}")
return False
INVALID_CHARS_HYPHENS = re.compile(r"[\\/:|]")
INVALID_CHARS_EMPTY = re.compile(r'[*?"<>]')
# C0 controls plus DEL. Illegal on most filesystems, and a line feed in a name
# that reaches a line-oriented protocol (the nginx mod_zip manifest) would split
# the record it sits in.
CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f]")
# NAME_MAX on ext4, XFS, Btrfs and ZFS. The limit is in bytes, so a CJK name
# reaches it at about 85 characters.
FILE_NAME_MAX_BYTES = 255
def check_filename_length(filename: str) -> None:
"""Raise ValueError if `filename` is too long for the filesystem to create."""
if len(filename.encode()) > FILE_NAME_MAX_BYTES:
raise ValueError(
f"Filename exceeds the filesystem limit of {FILE_NAME_MAX_BYTES} bytes"
)
def fit_filename(name: str, tail: str) -> str:
"""`name` cut so `name + tail` fits in FILE_NAME_MAX_BYTES, never splitting
a character."""
room = max(FILE_NAME_MAX_BYTES - len(tail.encode()), 0)
return name.encode()[:room].decode(errors="ignore") + tail
def sanitize_filename(filename: str) -> str:
"""
Replace invalid characters in the filename to make it valid across common filesystems
and prevent path-traversal attacks.
Args:
- filename (str): The filename to sanitize.
Returns:
- str: The sanitized filename (always a bare name, never a path).
Raises:
- ValueError: If the filename is empty or a reserved traversal name.
"""
# Strip directory components first to neutralise path-traversal payloads
sanitized_filename = os.path.basename(filename)
# Replace some invalid characters with hyphen
sanitized_filename = INVALID_CHARS_HYPHENS.sub("-", sanitized_filename)
# Remove other invalid characters
sanitized_filename = INVALID_CHARS_EMPTY.sub("", sanitized_filename)
# Drop control characters, null bytes included (ZFS allows every other character)
sanitized_filename = CONTROL_CHARS.sub("", sanitized_filename)
# Remove leading/trailing whitespace
sanitized_filename = sanitized_filename.strip()
# Reject empty, current-directory, or parent-directory names
if not sanitized_filename or sanitized_filename in (".", ".."):
raise ValueError("Filename cannot be empty after sanitization")
return sanitized_filename