Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Restore symlink members when extracting the sd.cpp prebuilt (#9270)

Francesco Bruno292199071ab3
diff --git a/studio/backend/tests/test_sd_cpp_install.py b/studio/backend/tests/test_sd_cpp_install.py
index a0e20afc545..f7aa03263cf 100644
--- a/studio/backend/tests/test_sd_cpp_install.py
+++ b/studio/backend/tests/test_sd_cpp_install.py
@@ -17,6 +17,7 @@ _STUDIO = Path(__file__).resolve().parents[2]
if str(_STUDIO) not in sys.path:
sys.path.insert(0, str(_STUDIO))
+import os # noqa: E402
import hashlib # noqa: E402
import builtins # noqa: E402
import types # noqa: E402
@@ -376,6 +377,687 @@ def test_safe_extractall_rejects_path_traversal(tmp_path):
assert not (tmp_path / "escape.txt").exists()
+def test_safe_extractall_restores_symlink_members(tmp_path):
+ if not _can_create_symlinks(tmp_path):
+ pytest.skip("symlink creation needs privilege on this host (Windows non-dev-mode)")
+ target = tmp_path / "install"
+ target.mkdir()
+ archive = tmp_path / "libs.zip"
+ # A symlink member carries the Unix symlink mode in external_attr and the
+ # link target as its data: the shape CPython's zipfile writes when zipping
+ # a symlink, and what upstream sd.cpp release zips ship for lib*.so.
+ with zipfile.ZipFile(archive, "w") as zf:
+ zf.writestr("libwebpmux.so.3.1.2", b"\x7fELFpayload")
+ info = zipfile.ZipInfo("libwebpmux.so.3")
+ info.create_system = 3
+ info.external_attr = (0o120777 << 16) | 0o777
+ zf.writestr(info, "libwebpmux.so.3.1.2")
+
+ with zipfile.ZipFile(archive) as zf:
+ _safe_extractall(zf, target)
+
+ link = target / "libwebpmux.so.3"
+ real = target / "libwebpmux.so.3.1.2"
+ assert link.is_symlink()
+ assert link.readlink().name == "libwebpmux.so.3.1.2"
+ # Compare bytes, not stat().st_size: stat() follows the link, so a size check cannot
+ # fail. Pre-fix this was a 19-byte text file, which ldd calls "file too short".
+ assert link.resolve(strict = True) == real.resolve()
+ assert link.read_bytes() == b"\x7fELFpayload"
+ assert not real.is_symlink()
+
+
+# The binary the sweep looks for, spelled the way this host spells it.
+_CLI = sdmod._binary_names()[0]
+
+
+def _can_create_symlinks(tmp_path) -> bool:
+ probe = tmp_path / "_link_probe"
+ try:
+ probe.symlink_to("target.txt")
+ except OSError:
+ return False
+ probe.unlink(missing_ok = True)
+ return True
+
+
+def _link_member(
+ zf,
+ name: str,
+ link_target: str,
+ create_system: int = 3,
+) -> None:
+ """The symlink member CPython's zipfile produces: Unix link mode, target as the data."""
+ info = zipfile.ZipInfo(name)
+ info.create_system = create_system
+ info.external_attr = (0o120777 << 16) | 0o777
+ zf.writestr(info, link_target)
+
+
+def test_safe_extractall_rejects_escaping_symlink(tmp_path):
+ # Validation precedes every write, so this holds even where symlinks need privilege.
+ target = tmp_path / "install"
+ target.mkdir()
+ (target / "sd-cli").write_bytes(b"working binary from the previous install")
+ archive = tmp_path / "evil.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ zf.writestr("sd-cli", b"replacement from the rejected archive")
+ _link_member(zf, "libescape.so", "../../outside.so")
+ with zipfile.ZipFile(archive) as zf:
+ with pytest.raises(RuntimeError, match = "unsafe symlink"):
+ _safe_extractall(zf, target)
+ assert not (tmp_path / "outside.so").exists()
+ # A rejected archive must not have replaced the install it was rejected over.
+ assert (target / "sd-cli").read_bytes() == b"working binary from the previous install"
+ assert not (target / "libescape.so").exists()
+
+
+ "link_target",
+ [
+ "/etc/passwd", # absolute, outside
+ "C:outside.dll", # Windows drive-relative: Win32 resolves it off that drive's cwd
+ "", # empty
+ "real\x00.so", # NUL
+ "libself.so", # self-referential, the shape the old resolve() bug produced
+ ],
+)
+def test_safe_extractall_rejects_malformed_symlink_targets(tmp_path, link_target):
+ target = tmp_path / "install"
+ target.mkdir()
+ archive = tmp_path / "evil.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ _link_member(zf, "libself.so", link_target)
+ with zipfile.ZipFile(archive) as zf:
+ with pytest.raises(RuntimeError, match = "unsafe symlink"):
+ _safe_extractall(zf, target)
+ assert not any(target.iterdir())
+
+
+def test_safe_extractall_rejects_a_symlink_redirected_parent(tmp_path):
+ if not _can_create_symlinks(tmp_path):
+ pytest.skip("symlink creation needs privilege on this host (Windows non-dev-mode)")
+ # An earlier member can turn a later member's parent into a link. Preflight refuses the
+ # member under it, so nothing outside is touched and nothing inside is half replaced: the
+ # working binary an install would have overwritten is still the one that was there.
+ target = tmp_path / "install"
+ target.mkdir()
+ (target / "sd-cli").write_bytes(b"working binary from the previous install")
+ outside = tmp_path / "outside_dir"
+ outside.mkdir()
+ victim = outside / "victim"
+ victim.write_bytes(b"outside the install dir")
+ archive = tmp_path / "evil.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ zf.writestr("sd-cli", b"replacement from the rejected archive")
+ _link_member(zf, "a", ".")
+ _link_member(zf, "a/out", "../outside_dir")
+ _link_member(zf, "a/out/victim", "replacement")
+ with zipfile.ZipFile(archive) as zf:
+ with pytest.raises(RuntimeError, match = "under a symlink member"):
+ _safe_extractall(zf, target)
+ assert not victim.is_symlink()
+ assert victim.read_bytes() == b"outside the install dir"
+ assert (target / "sd-cli").read_bytes() == b"working binary from the previous install"
+ assert sorted(p.name for p in target.iterdir()) == ["sd-cli"]
+
+
+def test_the_sweep_keeps_a_binary_supplied_under_a_symlinked_directory(tmp_path):
+ if not _can_create_symlinks(tmp_path):
+ pytest.skip("symlink creation needs privilege on this host (Windows non-dev-mode)")
+ # rglob reports the extracted binary under the real directory, so a lexical member path
+ # would not match and the sweep would delete the executable this bundle just supplied.
+ target = tmp_path / "install"
+ target.mkdir()
+ (target / "real").mkdir()
+ (target / "build").mkdir()
+ (target / "build" / "bin").symlink_to(target / "real")
+ archive = tmp_path / "bundle.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ zf.writestr(f"build/bin/{_CLI}", b"\x7fELF new binary")
+
+ with zipfile.ZipFile(archive) as zf:
+ supplied = sdmod._archive_binary_paths(zf, target)
+ _safe_extractall(zf, target)
+ sdmod._discard_superseded_binaries(target, supplied)
+
+ assert sdmod._locate_sd_cli(target) is not None
+ assert (target / "real" / _CLI).read_bytes() == b"\x7fELF new binary"
+
+
+def test_the_sweep_keeps_a_binary_whose_parent_link_the_archive_replaces(tmp_path):
+ if not _can_create_symlinks(tmp_path):
+ pytest.skip("symlink creation needs privilege on this host (Windows non-dev-mode)")
+ # An explicit directory member replaces the previous bundle's directory symlink, so a key
+ # resolved before extraction points into a layout that no longer exists by sweep time.
+ target = tmp_path / "install"
+ target.mkdir()
+ (target / "real").mkdir()
+ (target / "build").mkdir()
+ (target / "build" / "bin").symlink_to(target / "real")
+ archive = tmp_path / "bundle.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ zf.writestr("build/bin/", b"")
+ zf.writestr(f"build/bin/{_CLI}", b"\x7fELF new binary")
+
+ with zipfile.ZipFile(archive) as zf:
+ supplied = sdmod._archive_binary_paths(zf, target)
+ _safe_extractall(zf, target)
+ sdmod._discard_superseded_binaries(target, supplied)
+
+ assert sdmod._locate_sd_cli(target) is not None
+
+
+def test_safe_extractall_rejects_an_existing_cycle_before_writing_anything(tmp_path):
+ if not _can_create_symlinks(tmp_path):
+ pytest.skip("symlink creation needs privilege on this host (Windows non-dev-mode)")
+ # The cycle is closed by a link the previous bundle left, so it is only visible against the
+ # tree. Deciding it up front is what keeps a refused archive from replacing the binary.
+ target = tmp_path / "install"
+ target.mkdir()
+ (target / "b").symlink_to("a")
+ (target / "sd-cli").write_bytes(b"\x7fELF working binary")
+ archive = tmp_path / "evil.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ zf.writestr("sd-cli", b"replacement from the rejected archive")
+ _link_member(zf, "a", "b")
+ with zipfile.ZipFile(archive) as zf:
+ with pytest.raises(RuntimeError, match = "symlink cycle"):
+ _safe_extractall(zf, target)
+ assert (target / "sd-cli").read_bytes() == b"\x7fELF working binary"
+ assert not (target / "a").exists() and not (target / "a").is_symlink()
+
+
+def test_the_sweep_keeps_a_binary_the_bundle_ships_as_a_symlink(tmp_path):
+ if not _can_create_symlinks(tmp_path):
+ pytest.skip("symlink creation needs privilege on this host (Windows non-dev-mode)")
+ # The other half of _binary_key: resolving the final component would spell the binary as
+ # sd-cli-1.2, a name no member carries, and the sweep would take it.
+ target = tmp_path / "install"
+ target.mkdir()
+ archive = tmp_path / "bundle.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ zf.writestr(f"build/bin/{_CLI}-1.2", b"\x7fELF new binary")
+ _link_member(zf, f"build/bin/{_CLI}", f"{_CLI}-1.2")
+
+ with zipfile.ZipFile(archive) as zf:
+ supplied = sdmod._archive_binary_paths(zf, target)
+ _safe_extractall(zf, target)
+ sdmod._discard_superseded_binaries(target, supplied)
+
+ assert (target / "build" / "bin" / _CLI).is_symlink()
+ assert sdmod._locate_sd_cli(target) is not None
+
+
+def test_safe_extractall_allows_a_parent_symlinked_inside_the_tree(tmp_path):
+ if not _can_create_symlinks(tmp_path):
+ pytest.skip("symlink creation needs privilege on this host (Windows non-dev-mode)")
+ # The creation-time re-check asks whether the parent still resolves INSIDE the install
+ # dir, not whether it is link-free, so a tree that symlinks one of its own subdirectories
+ # still installs. A parent pointing outside is already refused by the member-path check.
+ target = tmp_path / "install"
+ target.mkdir()
+ (target / "real_bin").mkdir()
+ (target / "build").mkdir()
+ (target / "build" / "bin").symlink_to(target / "real_bin")
+ archive = tmp_path / "libs.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ zf.writestr("build/bin/libwebp.so.7.2.0", b"\x7fELFpayload")
+ _link_member(zf, "build/bin/libwebp.so.7", "libwebp.so.7.2.0")
+
+ with zipfile.ZipFile(archive) as zf:
+ _safe_extractall(zf, target)
+
+ link = target / "build" / "bin" / "libwebp.so.7"
+ assert link.is_symlink()
+ assert link.read_bytes() == b"\x7fELFpayload"
+
+
+def test_safe_extractall_drops_a_stale_link_at_a_regular_members_path(tmp_path):
+ if not _can_create_symlinks(tmp_path):
+ pytest.skip("symlink creation needs privilege on this host (Windows non-dev-mode)")
+ # An accelerator switch lands exactly here: upstream ships lib*.so as links, the mirror
+ # ships plain copies. extractall opens its destination "wb", so a leftover link would send
+ # one member's bytes into the file it points at and lose them.
+ target = tmp_path / "install"
+ target.mkdir()
+ (target / "real").write_bytes(b"old real lib")
+ (target / "name").symlink_to("real")
+ archive = tmp_path / "next.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ zf.writestr("name", b"new name bytes")
+ zf.writestr("real", b"new real bytes")
+
+ with zipfile.ZipFile(archive) as zf:
+ _safe_extractall(zf, target)
+
+ assert not (target / "name").is_symlink()
+ assert (target / "name").read_bytes() == b"new name bytes"
+ assert (target / "real").read_bytes() == b"new real bytes"
+
+
+def test_safe_extractall_rejects_a_cycle_closed_by_an_existing_link(tmp_path):
+ if not _can_create_symlinks(tmp_path):
+ pytest.skip("symlink creation needs privilege on this host (Windows non-dev-mode)")
+ # The graph on disk also holds links a previous bundle left, so archive-to-archive edges
+ # alone cannot see a cycle. The half this archive created must not survive the rejection,
+ # or the retry meets the same loop.
+ target = tmp_path / "install"
+ target.mkdir()
+ (target / "b").symlink_to("a")
+ archive = tmp_path / "next.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ _link_member(zf, "a", "b")
+ with zipfile.ZipFile(archive) as zf:
+ with pytest.raises(RuntimeError, match = "symlink cycle"):
+ _safe_extractall(zf, target)
+ assert not (target / "a").is_symlink()
+
+
+def test_safe_extractall_rejects_a_symlink_at_a_reserved_installer_path(tmp_path):
+ # _write_install_record opens the record with "w", which follows a link planted there and
+ # overwrites its target, while the record still reads back, so the install reports success.
+ target = tmp_path / "install"
+ target.mkdir()
+ archive = tmp_path / "evil.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ zf.writestr("sd-cli", b"\x7fELF real binary")
+ _link_member(zf, sdmod.INSTALL_RECORD, "sd-cli")
+ with zipfile.ZipFile(archive) as zf:
+ with pytest.raises(RuntimeError, match = "reserved installer path"):
+ _safe_extractall(zf, target)
+ assert not any(target.iterdir())
+
+
+def test_safe_extractall_rejects_a_symlink_onto_a_reserved_installer_path(tmp_path):
+ # The marker exists before extraction on any root Studio owns, so a link to it resolves
+ # to a file and _locate_sd_cli reports an empty one as the executable.
+ target = tmp_path / "install"
+ target.mkdir()
+ (target / sdmod.OWNERSHIP_MARKER).write_text("")
+ archive = tmp_path / "evil.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ _link_member(zf, _CLI, sdmod.OWNERSHIP_MARKER)
+ with zipfile.ZipFile(archive) as zf:
+ with pytest.raises(RuntimeError, match = "onto a reserved installer path"):
+ _safe_extractall(zf, target)
+ assert sdmod._locate_sd_cli(target) is None
+
+
+def test_safe_extractall_rejects_a_reserved_path_reached_through_a_directory_alias(tmp_path):
+ # A previous bundle's directory link makes alias/<record> land on the record itself, so a
+ # lexical comparison misses it and _write_install_record overwrites sd-cli with JSON.
+ if not _can_create_symlinks(tmp_path):
+ pytest.skip("symlink creation needs privilege on this host (Windows non-dev-mode)")
+ target = tmp_path / "install"
+ target.mkdir()
+ (target / "sd-cli").write_bytes(b"\x7fELF real binary")
+ (target / "alias").symlink_to(".")
+ archive = tmp_path / "evil.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ _link_member(zf, "alias/" + sdmod.INSTALL_RECORD, "sd-cli")
+ with zipfile.ZipFile(archive) as zf:
+ with pytest.raises(RuntimeError, match = "reserved installer path"):
+ _safe_extractall(zf, target)
+ assert not (target / sdmod.INSTALL_RECORD).exists()
+ assert (target / "sd-cli").read_bytes() == b"\x7fELF real binary"
+
+
+def test_safe_extractall_rejects_a_cycle_hidden_behind_a_directory_alias(tmp_path):
+ # alias -> real means alias/a and real/b are one cycle, though the member names differ.
+ if not _can_create_symlinks(tmp_path):
+ pytest.skip("symlink creation needs privilege on this host (Windows non-dev-mode)")
+ target = tmp_path / "install"
+ target.mkdir()
+ (target / "real").mkdir()
+ (target / "alias").symlink_to("real")
+ archive = tmp_path / "cycle.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ _link_member(zf, "alias/a", "b")
+ _link_member(zf, "real/b", "a")
+ with zipfile.ZipFile(archive) as zf:
+ with pytest.raises(RuntimeError, match = "symlink cycle"):
+ _safe_extractall(zf, target)
+ assert not (target / "real" / "a").is_symlink()
+ assert not (target / "real" / "b").is_symlink()
+
+
+def test_safe_extractall_rejects_a_directory_collision_before_writing_anything(tmp_path):
+ # The collision used to be caught after extractall, so the refused archive had already
+ # replaced the working binary.
+ target = tmp_path / "install"
+ (target / "build" / "bin").mkdir(parents = True)
+ (target / "build" / "bin" / "sd-cli").write_bytes(b"\x7fELF working")
+ (target / "libz.so").mkdir()
+ archive = tmp_path / "collide.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ zf.writestr("build/bin/sd-cli", b"\x7fELF replacement")
+ _link_member(zf, "libz.so", "libz.so.1")
+ with zipfile.ZipFile(archive) as zf:
+ with pytest.raises(RuntimeError, match = "collides with a directory"):
+ _safe_extractall(zf, target)
+ assert (target / "build" / "bin" / "sd-cli").read_bytes() == b"\x7fELF working"
+ assert (target / "libz.so").is_dir() and not (target / "libz.so").is_symlink()
+
+
+def _chain_archive(path, hops):
+ with zipfile.ZipFile(path, "w") as zf:
+ zf.writestr("l.so.0", b"ELFpayload")
+ prev = "l.so.0"
+ for i in range(1, hops + 1):
+ _link_member(zf, f"l.so.{i}", prev)
+ prev = f"l.so.{i}"
+
+
+def test_safe_extractall_installs_a_chain_the_loader_can_still_walk(tmp_path):
+ # The kernel allows 40 traversals, so 40 is readable and must not be refused.
+ if not _can_create_symlinks(tmp_path):
+ pytest.skip("symlink creation needs privilege on this host (Windows non-dev-mode)")
+ target = tmp_path / "install"
+ target.mkdir()
+ archive = tmp_path / "chain40.zip"
+ _chain_archive(archive, 40)
+ with zipfile.ZipFile(archive) as zf:
+ _safe_extractall(zf, target)
+ assert (target / "l.so.40").read_bytes() == b"ELFpayload"
+
+
+def test_safe_extractall_rejects_a_chain_deeper_than_the_loader_allows(tmp_path):
+ # At 41 the loader ELOOPs, so installing it leaves a library nothing can read, which is
+ # the same failure a cycle causes. Terminating does not make it usable.
+ target = tmp_path / "install"
+ target.mkdir()
+ archive = tmp_path / "chain41.zip"
+ _chain_archive(archive, 41)
+ with zipfile.ZipFile(archive) as zf:
+ with pytest.raises(RuntimeError, match = "too deep"):
+ _safe_extractall(zf, target)
+
+
+def test_safe_extractall_rejects_symlink_cycles(tmp_path):
+ # Chains are normal, a cycle is not: it installs a library nothing can read, so the
+ # loader failure would send the backend round the reinstall loop on every load.
+ target = tmp_path / "install"
+ target.mkdir()
+ archive = tmp_path / "cycle.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ _link_member(zf, "liba.so", "libb.so")
+ _link_member(zf, "libb.so", "liba.so")
+ with zipfile.ZipFile(archive) as zf:
+ with pytest.raises(RuntimeError, match = "symlink cycle"):
+ _safe_extractall(zf, target)
+ assert not any(target.iterdir())
+
+
+def test_safe_extractall_keeps_valid_symlink_chains(tmp_path):
+ if not _can_create_symlinks(tmp_path):
+ pytest.skip("symlink creation needs privilege on this host (Windows non-dev-mode)")
+ # The cycle check must not reject the chained shape upstream actually ships.
+ target = tmp_path / "install"
+ target.mkdir()
+ archive = tmp_path / "libs.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ zf.writestr("libwebp.so.7.2.0", b"\x7fELFpayload")
+ _link_member(zf, "libwebp.so.7", "libwebp.so.7.2.0")
+ _link_member(zf, "libwebp.so", "libwebp.so.7")
+ with zipfile.ZipFile(archive) as zf:
+ _safe_extractall(zf, target)
+ assert (target / "libwebp.so").read_bytes() == b"\x7fELFpayload"
+
+
+def test_safe_extractall_rejects_oversized_symlink_target(tmp_path):
+ # zf.read holds the payload in memory, and a pathname cannot exceed PATH_MAX.
+ target = tmp_path / "install"
+ target.mkdir()
+ archive = tmp_path / "bomb.zip"
+ with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as zf:
+ _link_member(zf, "libbomb.so", "a" * (1 << 20))
+ with zipfile.ZipFile(archive) as zf:
+ with pytest.raises(RuntimeError, match = "oversized symlink target"):
+ _safe_extractall(zf, target)
+ assert not any(target.iterdir())
+
+
+def test_safe_extractall_ignores_symlink_mode_from_non_unix_hosts(tmp_path):
+ # Those high bits are a Unix mode only when a Unix host wrote the entry.
+ target = tmp_path / "install"
+ target.mkdir()
+ archive = tmp_path / "dos.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ _link_member(zf, "plain.txt", "not a link", create_system = 0)
+ with zipfile.ZipFile(archive) as zf:
+ _safe_extractall(zf, target)
+ extracted = target / "plain.txt"
+ assert not extracted.is_symlink()
+ assert extracted.read_bytes() == b"not a link"
+
+
+def test_safe_extractall_restores_links_from_a_macos_creator(tmp_path):
+ # Apple's ditto and Archive Utility stamp creator 19 (OS X) and lay external_attr out
+ # exactly as a Unix host does. Gating on 3 alone silently flattens such an archive.
+ if not _can_create_symlinks(tmp_path):
+ pytest.skip("symlink creation needs privilege on this host (Windows non-dev-mode)")
+ target = tmp_path / "install"
+ target.mkdir()
+ archive = tmp_path / "ditto.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ zf.writestr("libwebp.so.7.2.0", b"ELFpayload")
+ _link_member(zf, "libwebp.so.7", "libwebp.so.7.2.0", create_system = 19)
+ with zipfile.ZipFile(archive) as zf:
+ _safe_extractall(zf, target)
+ link = target / "libwebp.so.7"
+ assert link.is_symlink()
+ assert link.read_bytes() == b"ELFpayload"
+
+
+def test_safe_extractall_creates_the_install_root_before_probing_for_symlinks(tmp_path):
+ # extractall makes the tree itself, so a first install into a root that does not exist yet
+ # must not fail the symlink probe and report the filesystem as unable to store links.
+ if not _can_create_symlinks(tmp_path):
+ pytest.skip("symlink creation needs privilege on this host (Windows non-dev-mode)")
+ target = tmp_path / "not-created-yet"
+ archive = tmp_path / "fresh.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ zf.writestr("libwebp.so.7.2.0", b"ELFpayload")
+ _link_member(zf, "libwebp.so.7", "libwebp.so.7.2.0")
+ with zipfile.ZipFile(archive) as zf:
+ _safe_extractall(zf, target)
+ assert (target / "libwebp.so.7").is_symlink()
+ assert (target / "libwebp.so.7").read_bytes() == b"ELFpayload"
+
+
+def test_safe_extractall_survives_a_probe_left_by_a_killed_install(tmp_path):
+ # An install killed between symlink_to and unlink leaves its probe in a directory that
+ # outlives the process. A restarted container starts a fresh pid namespace, so the same pid
+ # comes round again, and symlink_to's EEXIST would then read as "no symlink support" and
+ # block every retry.
+ if not _can_create_symlinks(tmp_path):
+ pytest.skip("symlink creation needs privilege on this host (Windows non-dev-mode)")
+ target = tmp_path / "install"
+ target.mkdir()
+ (target / f".unsloth-symlink-probe-{os.getpid()}").symlink_to(".")
+ archive = tmp_path / "libs.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ zf.writestr("libwebp.so.7.2.0", b"ELFpayload")
+ _link_member(zf, "libwebp.so.7", "libwebp.so.7.2.0")
+ with zipfile.ZipFile(archive) as zf:
+ _safe_extractall(zf, target)
+ assert (target / "libwebp.so.7").is_symlink()
+ assert (target / "libwebp.so.7").read_bytes() == b"ELFpayload"
+ # And the install leaves none of its own behind.
+ assert list(target.glob(".unsloth-symlink-probe-*")) == []
+
+
+def test_safe_extractall_is_idempotent_across_reinstalls(tmp_path):
+ if not _can_create_symlinks(tmp_path):
+ pytest.skip("symlink creation needs privilege on this host (Windows non-dev-mode)")
+ target = tmp_path / "install"
+ target.mkdir()
+ archive = tmp_path / "libs.zip"
+ # The chained shape upstream ships: libwebp.so -> libwebp.so.7 -> libwebp.so.7.2.0.
+ with zipfile.ZipFile(archive, "w") as zf:
+ zf.writestr("libwebp.so.7.2.0", b"ELFpayload")
+ _link_member(zf, "libwebp.so.7", "libwebp.so.7.2.0")
+ _link_member(zf, "libwebp.so", "libwebp.so.7")
+
+ # install() MERGES, so a retry or version bump re-extracts over the previous install's
+ # links. Resolving through them destroyed the real library they pointed at.
+ for _ in range(3):
+ with zipfile.ZipFile(archive) as zf:
+ _safe_extractall(zf, target)
+
+ real = target / "libwebp.so.7.2.0"
+ assert not real.is_symlink()
+ assert real.read_bytes() == b"ELFpayload"
+ for name in ("libwebp.so", "libwebp.so.7"):
+ assert (target / name).is_symlink()
+ assert (target / name).read_bytes() == b"ELFpayload"
+
+
+def test_safe_extractall_repairs_a_flattened_install(tmp_path):
+ if not _can_create_symlinks(tmp_path):
+ pytest.skip("symlink creation needs privilege on this host (Windows non-dev-mode)")
+ target = tmp_path / "install"
+ target.mkdir()
+ # What every pre-fix install left behind: the link flattened to its target text.
+ (target / "libwebp.so.7.2.0").write_bytes(b"ELFpayload")
+ (target / "libwebp.so.7").write_bytes(b"libwebp.so.7.2.0")
+ archive = tmp_path / "libs.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ zf.writestr("libwebp.so.7.2.0", b"ELFpayload")
+ _link_member(zf, "libwebp.so.7", "libwebp.so.7.2.0")
+
+ with zipfile.ZipFile(archive) as zf:
+ _safe_extractall(zf, target)
+
+ assert (target / "libwebp.so.7").is_symlink()
+ assert (target / "libwebp.so.7").read_bytes() == b"ELFpayload"
+
+
+def test_safe_extractall_survives_a_hand_repaired_install(tmp_path):
+ if not _can_create_symlinks(tmp_path):
+ pytest.skip("symlink creation needs privilege on this host (Windows non-dev-mode)")
+ target = tmp_path / "install"
+ target.mkdir()
+ # The workaround #9268 tells users to apply by hand, which the next install must not undo.
+ (target / "libwebp.so.7.2.0").write_bytes(b"ELFpayload")
+ (target / "libwebp.so.7").symlink_to("libwebp.so.7.2.0")
+ archive = tmp_path / "libs.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ zf.writestr("libwebp.so.7.2.0", b"ELFpayload")
+ _link_member(zf, "libwebp.so.7", "libwebp.so.7.2.0")
+
+ with zipfile.ZipFile(archive) as zf:
+ _safe_extractall(zf, target)
+
+ real = target / "libwebp.so.7.2.0"
+ assert not real.is_symlink()
+ assert real.read_bytes() == b"ELFpayload"
+ assert (target / "libwebp.so.7").read_bytes() == b"ELFpayload"
+
+
+def test_safe_extractall_falls_back_when_symlinks_are_unavailable(tmp_path, monkeypatch):
+ # Windows outside developer mode cannot create symlinks. The install must still finish
+ # with the flattened member, exactly as it did before symlinks were restored.
+ target = tmp_path / "install"
+ target.mkdir()
+ archive = tmp_path / "libs.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ zf.writestr("libwebp.so.7.2.0", b"ELFpayload")
+ _link_member(zf, "libwebp.so.7", "libwebp.so.7.2.0")
+
+ def _no_symlinks(self, *args, **kwargs):
+ raise OSError(1314, "A required privilege is not held by the client")
+
+ monkeypatch.setattr(Path, "symlink_to", _no_symlinks)
+ monkeypatch.setattr(sdmod.sys, "platform", "win32")
+ with zipfile.ZipFile(archive) as zf:
+ _safe_extractall(zf, target)
+
+ flattened = target / "libwebp.so.7"
+ assert not flattened.is_symlink()
+ assert flattened.read_bytes() == b"libwebp.so.7.2.0"
+ assert (target / "libwebp.so.7.2.0").read_bytes() == b"ELFpayload"
+
+
+def test_safe_extractall_refuses_to_flatten_when_a_unix_host_rejects_symlinks(
+ tmp_path, monkeypatch
+):
+ # Off Windows a refusal means this filesystem cannot hold the layout sd-cli needs. Writing
+ # the link text back as a file would rebuild the "file too short" install #9268 reports,
+ # which the runtime probe then discards and reinstalls on every load. Caught before
+ # extractall, so an upgrade that cannot finish still leaves the previous install runnable.
+ target = tmp_path / "install"
+ target.mkdir()
+ (target / "sd-cli").write_bytes(b"\x7fELF old working")
+ archive = tmp_path / "libs.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ zf.writestr("sd-cli", b"\x7fELF replacement")
+ zf.writestr("libwebp.so.7.2.0", b"ELFpayload")
+ _link_member(zf, "libwebp.so.7", "libwebp.so.7.2.0")
+
+ def _no_symlinks(self, *args, **kwargs):
+ raise OSError(1, "Operation not permitted")
+
+ monkeypatch.setattr(Path, "symlink_to", _no_symlinks)
+ monkeypatch.setattr(sdmod.sys, "platform", "linux")
+ with zipfile.ZipFile(archive) as zf:
+ with pytest.raises(RuntimeError, match = "cannot store symlinks"):
+ _safe_extractall(zf, target)
+ assert not (target / "libwebp.so.7").exists()
+ assert not (target / "libwebp.so.7.2.0").exists()
+ assert (target / "sd-cli").read_bytes() == b"\x7fELF old working"
+
+
+def test_safe_extractall_rejects_a_member_with_a_parent_component(tmp_path):
+ # extractall drops ".." instead of cancelling the component before it, so "a/../victim"
+ # is "a/victim" to it, and an existing link at "a" lands the write outside the tree.
+ if not _can_create_symlinks(tmp_path):
+ pytest.skip("symlink creation needs privilege on this host (Windows non-dev-mode)")
+ target = tmp_path / "install"
+ target.mkdir()
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ (outside / "victim").write_bytes(b"untouched")
+ (target / "a").symlink_to(outside)
+ archive = tmp_path / "slip.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ zf.writestr("a/../victim", b"pwned")
+ with zipfile.ZipFile(archive) as zf:
+ with pytest.raises(RuntimeError, match = "unsafe path"):
+ _safe_extractall(zf, target)
+ assert (outside / "victim").read_bytes() == b"untouched"
+
+
+def test_safe_extractall_rejects_a_cycle_closed_through_link_parents(tmp_path):
+ # a -> b/x and b -> a/y are one cycle only once the b prefix is followed through the
+ # archive, since neither link exists on disk when the graph is built.
+ target = tmp_path / "install"
+ target.mkdir()
+ archive = tmp_path / "cycle.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ _link_member(zf, "a", "b/x")
+ _link_member(zf, "b", "a/y")
+ with zipfile.ZipFile(archive) as zf:
+ with pytest.raises(RuntimeError, match = "symlink cycle"):
+ _safe_extractall(zf, target)
+ assert not any(target.iterdir())
+
+
+def test_safe_extractall_rejects_a_link_that_descends_through_itself(tmp_path):
+ # a -> a/x never reaches a second node, so exact-node repetition misses it, but resolving
+ # a walks a again and every load would fail with ELOOP and reinstall.
+ target = tmp_path / "install"
+ target.mkdir()
+ archive = tmp_path / "loop.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ _link_member(zf, "libz.so", "libz.so/inner")
+ with zipfile.ZipFile(archive) as zf:
+ with pytest.raises(RuntimeError, match = "symlink cycle"):
+ _safe_extractall(zf, target)
+ assert not any(target.iterdir())
+
+
def test_safe_extractall_extracts_normal_members(tmp_path):
target = tmp_path / "install"
target.mkdir()
@@ -2683,3 +3365,77 @@ def test_the_install_record_remembers_whether_the_bundle_shipped_a_server(tmp_pa
sdmod._write_install_record(root, accelerator = "cpu", repo = "r", tag = "t", ships_server = False)
assert sdmod.installed_ships_server(root) is False
assert sdmod.installed_accelerator(root) == "cpu"
+
+
+def _reinstall_twice(tmp_path):
+ """The same archive extracted twice into one root, which is what install() does."""
+ target = tmp_path / "install"
+ target.mkdir()
+ archive = tmp_path / "symlink.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ zf.writestr("build/bin/libfoo.so.1", b"ELF")
+ _link_member(zf, "build/bin/libfoo.so", "libfoo.so.1")
+ for _ in range(2):
+ with zipfile.ZipFile(archive) as zf:
+ _safe_extractall(zf, target)
+ return target
+
+
+def test_safe_extractall_restores_symlink_members_on_reinstall(tmp_path):
+ # install() merges rather than wipes, so the same archive lands on the links it already wrote.
+ if not _can_create_symlinks(tmp_path):
+ pytest.skip("symlink creation needs privilege on this host (Windows non-dev-mode)")
+ target = _reinstall_twice(tmp_path)
+ link = target / "build" / "bin" / "libfoo.so"
+ assert link.is_symlink()
+ assert link.readlink() == Path("libfoo.so.1")
+ assert (target / "build" / "bin" / "libfoo.so.1").read_bytes() == b"ELF"
+
+
+def test_safe_extractall_reinstall_is_idempotent_without_symlink_privilege(tmp_path):
+ # The other half of the test above, and the only one a Windows non-dev-mode host can run:
+ # the fallback flattens, but reinstalling over it must still succeed and leave the same
+ # shape rather than erroring or compounding.
+ if _can_create_symlinks(tmp_path):
+ pytest.skip("this host can create symlinks, so the flattening fallback is not in play")
+ target = _reinstall_twice(tmp_path)
+ flattened = target / "build" / "bin" / "libfoo.so"
+ assert not flattened.is_symlink()
+ assert flattened.read_bytes() == b"libfoo.so.1"
+ assert (target / "build" / "bin" / "libfoo.so.1").read_bytes() == b"ELF"
+
+
+def test_safe_extractall_replaces_stale_symlink_with_regular_member(tmp_path):
+ # A name one bundle ships as a link the next can ship as a file: the mirror ships copies
+ # where upstream ships links, and extractall would otherwise write through the stale link.
+ target = tmp_path / "install"
+ target.mkdir()
+ old_archive = tmp_path / "old.zip"
+ with zipfile.ZipFile(old_archive, "w") as zf:
+ zf.writestr("build/bin/libfoo.so.1", b"OLD")
+ _link_member(zf, "build/bin/libfoo.so", "libfoo.so.1")
+ with zipfile.ZipFile(old_archive) as zf:
+ _safe_extractall(zf, target)
+
+ new_archive = tmp_path / "new.zip"
+ with zipfile.ZipFile(new_archive, "w") as zf:
+ zf.writestr("build/bin/libfoo.so.1", b"TARGET")
+ zf.writestr("build/bin/libfoo.so", b"NEW")
+ with zipfile.ZipFile(new_archive) as zf:
+ _safe_extractall(zf, target)
+
+ assert not (target / "build" / "bin" / "libfoo.so").is_symlink()
+ assert (target / "build" / "bin" / "libfoo.so").read_bytes() == b"NEW"
+ assert (target / "build" / "bin" / "libfoo.so.1").read_bytes() == b"TARGET"
+
+
+def test_safe_extractall_rejects_symlink_escaping_target(tmp_path):
+ target = tmp_path / "install"
+ target.mkdir()
+ archive = tmp_path / "symlink-escape.zip"
+ with zipfile.ZipFile(archive, "w") as zf:
+ _link_member(zf, "build/bin/escape.so", "../../../escape.txt")
+ with zipfile.ZipFile(archive) as zf:
+ with pytest.raises(RuntimeError, match = "unsafe symlink"):
+ _safe_extractall(zf, target)
+ assert not (tmp_path / "escape.txt").exists()
diff --git a/studio/install_sd_cpp_prebuilt.py b/studio/install_sd_cpp_prebuilt.py
index f8aaf45244e..9a37faf61d1 100644
--- a/studio/install_sd_cpp_prebuilt.py
+++ b/studio/install_sd_cpp_prebuilt.py
@@ -36,7 +36,7 @@ import sys
import urllib.error
import urllib.request
import zipfile
-from pathlib import Path
+from pathlib import Path, PurePosixPath, PureWindowsPath
from typing import Optional, Sequence
# Default source: the Unsloth mirror's CPU/Apple prebuilts (override with UNSLOTH_SD_CPP_REPO). GPU hosts run diffusers, so only CPU/Apple assets are needed.
@@ -66,6 +66,9 @@ _MIRROR_ONLY_TAG_RE = re.compile(r"^master-\d+-[0-9a-f]+-u[0-9a-f]+$")
# bundle from a CUDA one instead of reusing whatever binary happens to be on disk.
INSTALL_RECORD = ".unsloth-sd-cpp-install.json"
+# Marks the directory as one Studio created, so an uninstall never wipes a user's own tree.
+OWNERSHIP_MARKER = ".unsloth-studio-owned"
+
def accelerator_class(accelerator: Optional[str]) -> str:
"""The accelerator an install actually serves. ``auto`` resolves to the plain build, so it and
@@ -431,16 +434,30 @@ def _binary_names() -> tuple[str, ...]:
return (f"sd-cli{suffix}", f"sd-server{suffix}")
+def _binary_key(path: Path) -> Path:
+ """How a binary is compared: parents resolved, final component left alone.
+
+ Both halves matter now that the tree holds symlinks. Resolving the leaf would turn a bundle
+ shipping ``sd-cli -> sd-cli-1.2`` into a name no member has; leaving the parents lexical
+ would spell a member under a symlinked directory differently from ``rglob``, and the sweep
+ would delete the binary this bundle just supplied."""
+ p = Path(os.path.abspath(path))
+ return Path(os.path.realpath(p.parent)) / p.name
+
+
def _archive_binary_paths(zf: zipfile.ZipFile, target: Path) -> set[Path]:
- """Where this archive puts its executables, resolved to absolute paths under ``target``.
+ """Where this archive puts its executables, as absolute LEXICAL paths under ``target``.
Read from the MEMBER LIST, never from the extracted tree: a leftover binary from an earlier
- install looks identical on disk once extraction has run, which is the whole confusion here."""
+ install looks identical on disk once extraction has run, which is the whole confusion here.
+
+ Unresolved on purpose: extraction can change what the parents mean, so resolving here would
+ key the binary off a layout that no longer exists by the time the sweep runs."""
names = _binary_names()
out: set[Path] = set()
for member in zf.namelist():
if member.rsplit("/", 1)[-1] in names:
- out.add((target / member).resolve())
+ out.add(Path(os.path.abspath(target / member)))
return out
@@ -468,9 +485,12 @@ def _discard_superseded_binaries(root: Path, supplied: set[Path]) -> None:
Raises when a copy cannot go, which withholds the record and makes the next load retry."""
names = _binary_names()
+ # Resolved HERE, not when ``supplied`` was built: the tree is final only now, and extraction
+ # may have replaced a directory symlink a member path was spelled through.
+ keys = {_binary_key(p) for p in supplied}
for name in names:
for found in sorted(root.rglob(name)):
- if not found.is_file() or found.resolve() in supplied:
+ if not found.is_file() or _binary_key(found) in keys:
continue
try:
found.unlink()
@@ -509,15 +529,249 @@ def _download(
shutil.copyfileobj(resp, f)
+# PATH_MAX: a link payload is a pathname and ``zf.read`` holds it in memory, so anything larger
+# is a decompression bomb rather than a library name.
+_MAX_LINK_TARGET_BYTES = 4096
+
+# What Linux allows before ELOOP, so a deeper layout is one the loader could not read anyway.
+_MAX_LINK_DEPTH = 40
+
+
+# Creators whose ``external_attr`` high bits are a Unix ``st_mode``: 3 (Info-ZIP, CPython) and
+# 19 (Apple's ditto, same layout). FAT and NTFS keep DOS attribute flags there, so reading a mode
+# out of one would invent symlinks the archive never described.
+_UNIX_CREATORS = (3, 19)
+
+
+def _is_symlink_member(member: zipfile.ZipInfo) -> bool:
+ """``external_attr``'s high bits are a Unix mode only when a Unix host wrote the entry."""
+ return member.create_system in _UNIX_CREATORS and stat.S_ISLNK(member.external_attr >> 16)
+
+
+def _checked_link_target(
+ zf: zipfile.ZipFile, member: zipfile.ZipInfo, dest: Path, base: Path
+) -> str:
+ """A symlink member's payload, refused unless it is relative and stays inside ``base``.
+
+ Rejects absolute (including Windows drive-relative, which Win32 resolves against that drive's
+ cwd), empty, NUL-bearing, self-referential and escaping targets."""
+ if member.file_size > _MAX_LINK_TARGET_BYTES:
+ raise RuntimeError(f"oversized symlink target in archive: {member.filename!r}")
+ link_target = zf.read(member).decode("utf-8", "surrogateescape")
+ unsafe = (
+ # Shape first: resolve() stats the path, and a NUL in it raises ValueError.
+ not link_target
+ or "\x00" in link_target
+ or PurePosixPath(link_target).is_absolute()
+ or bool(PureWindowsPath(link_target).drive)
+ )
+ if not unsafe:
+ resolved = (dest.parent / link_target).resolve()
+ # Self-check lexically: dest may already be a correct link to this very target.
+ unsafe = os.path.normpath(dest.parent / link_target) == os.path.normpath(dest) or (
+ resolved != base and base not in resolved.parents
+ )
+ if unsafe:
+ raise RuntimeError(f"unsafe symlink in archive: {member.filename!r} -> {link_target!r}")
+ return link_target
+
+
+def _plan_resolve(
+ path: Path,
+ base: Path,
+ replaced: set[str],
+ archive: dict,
+ depth: int = 0,
+) -> Path:
+ """``path`` with every component resolved as the tree WILL have it after extraction.
+
+ Links this archive ships are followed from the archive (not on disk yet); links it replaces
+ are not followed (gone before the first write); anything else is a previous bundle's. Two
+ members can point through each other's directories, so a runaway recursion is that cycle."""
+ if path == base or base not in path.parents:
+ return path
+ if depth > _MAX_LINK_DEPTH:
+ raise RuntimeError(f"symlink cycle in archive: {str(path.relative_to(base))!r}")
+ cur = base
+ for part in path.relative_to(base).parts:
+ cur = cur / part
+ target = archive.get(str(cur))
+ if target is not None:
+ cur = _plan_resolve(
+ Path(os.path.normpath(cur.parent / target)), base, replaced, archive, depth + 1
+ )
+ elif str(cur) not in replaced and cur.is_symlink():
+ cur = Path(os.path.realpath(cur))
+ return cur
+
+
+def _plan_key(dest: Path, base: Path, replaced: set[str], archive: dict) -> Path:
+ """Where ``dest`` will really land. Only the parents are resolved: the final component is the
+ link about to be created, and following it would compare the wrong thing."""
+ if dest == base or base not in dest.parents:
+ return dest
+ return _plan_resolve(dest.parent, base, replaced, archive) / dest.name
+
+
def _safe_extractall(zf: zipfile.ZipFile, target: Path) -> None:
- """``extractall`` with a per-member containment check, so an archive carrying an
- absolute path or a ``..`` entry can't write outside ``target`` (Zip-Slip)."""
+ """``extractall`` with a per-member containment check, so an archive carrying an absolute
+ path or a ``..`` entry can't write outside ``target`` (Zip-Slip).
+
+ Symlink members are RECREATED rather than extracted: CPython's ``zipfile`` writes a symlink's
+ payload (the link target text) as a regular file, which flattens the ``lib*.so`` links
+ upstream sd.cpp releases ship and leaves ``sd-cli`` with ``file too short`` libraries (#9268).
+
+ Everything is decided BEFORE the first write, so a refused archive leaves the install it was
+ refused over exactly as it was."""
base = target.resolve()
+ # The installer writes these itself. A link at one makes _write_install_record follow it and
+ # overwrite the target while the record still reads back, so a broken install reports success.
+ reserved = {base / INSTALL_RECORD, base / OWNERSHIP_MARKER}
+ links: list[tuple[Path, str, zipfile.ZipInfo]] = []
+ plain: list[zipfile.ZipInfo] = []
+ written: list[tuple[Path, str]] = []
for member in zf.infolist():
- dest = (base / member.filename).resolve()
- if dest != base and base not in dest.parents:
+ # extractall DROPS ".." instead of cancelling the component before it, so "a/.." is "a" to
+ # it and normalising here would check a path it never writes. No release ships one.
+ if ".." in PurePosixPath(member.filename).parts:
+ raise RuntimeError(f"unsafe path in archive: {member.filename!r}")
+ # Lexical, never resolve()d: extraction MERGES, and resolving would follow the previous
+ # install's link and leave the real library replaced by a link to itself.
+ dest = Path(os.path.normpath(base / member.filename))
+ checked = dest.resolve()
+ if (dest != base and base not in dest.parents) or (
+ checked != base and base not in checked.parents
+ ):
raise RuntimeError(f"unsafe path in archive: {member.filename!r}")
- zf.extractall(target)
+ written.append((dest, member.filename))
+ if _is_symlink_member(member):
+ links.append((dest, _checked_link_target(zf, member, dest, base), member))
+ else:
+ plain.append(member)
+ # No member may sit under a directory this archive turns into a link: extraction would write
+ # through it, and catching that at creation time means part of the tree is already replaced.
+ link_dests = {d for d, _, _ in links}
+ for dest, filename in written:
+ for parent in dest.parents:
+ if parent == base:
+ break
+ if parent in link_dests:
+ raise RuntimeError(
+ f"unsafe path in archive: {filename!r} is under a symlink member"
+ )
+ # Every destination this archive writes becomes its own member, so a stale link at one must
+ # not be followed.
+ replaced = {str(d) for d, _ in written}
+ archive = {str(d): t for d, t, _ in links}
+ replaced |= {str(_plan_key(d, base, replaced, archive)) for d, _ in written}
+ # A member path is not where the link lands: a previous bundle's alias -> . puts alias/<record>
+ # on the record itself, which a lexical compare misses. Same for a directory already there.
+ keys = {str(d): _plan_key(d, base, replaced, archive) for d, _, _ in links}
+ for dest, link_target, member in links:
+ key = keys[str(dest)]
+ if key in reserved:
+ raise RuntimeError(f"symlink at a reserved installer path: {member.filename!r}")
+ # Nor may one POINT at them: the marker is already there on a root Studio owns, so
+ # sd-cli -> marker leaves _locate_sd_cli reporting an empty file as the executable.
+ landing = _plan_resolve(
+ Path(os.path.normpath(key.parent / link_target)), base, replaced, archive
+ )
+ if landing in reserved:
+ raise RuntimeError(f"symlink onto a reserved installer path: {member.filename!r}")
+ if key.is_dir() and not key.is_symlink():
+ raise RuntimeError(f"symlink member collides with a directory: {member.filename!r}")
+ # Chains are normal (libwebp.so -> .so.7 -> .so.7.2.0) but must terminate: a cycle installs a
+ # library nothing can read, so every load reinstalls it. Walk the graph the tree WILL have,
+ # keyed by landing point so alias/a and real/b count as one cycle.
+ by_dest = {str(keys[str(d)]): t for d, t, _ in links}
+ for dest, _, member in links:
+ seen, cur, hops = set(), str(keys[str(dest)]), 0
+ while cur not in seen:
+ seen.add(cur)
+ if cur in by_dest:
+ nxt = by_dest[cur]
+ elif cur not in replaced and os.path.islink(cur):
+ nxt = os.readlink(cur)
+ else:
+ break
+ # Counted per hop FOLLOWED, not per node seen: the file a chain ends at is not a
+ # traversal. A chain the kernel cannot walk is unreadable for the same reason a
+ # cycle is, and terminating does not save it, so it is refused rather than installed.
+ hops += 1
+ if hops > _MAX_LINK_DEPTH:
+ raise RuntimeError(f"symlink chain too deep in archive: {member.filename!r}")
+ nxt = Path(os.path.normpath(os.path.join(os.path.dirname(cur), nxt)))
+ # a -> a/x never reaches a second node, so repetition never fires, yet resolving a
+ # walks a again. Anything under the link is a loop.
+ if Path(cur) in nxt.parents:
+ raise RuntimeError(f"symlink cycle in archive: {member.filename!r}")
+ cur = str(_plan_key(nxt, base, replaced, archive))
+ else:
+ raise RuntimeError(f"symlink cycle in archive: {member.filename!r}")
+ # Last thing decided before the first write: can this filesystem hold links at all? Some mounts
+ # (exFAT, SMB without unix extensions) refuse, and learning that at creation time means
+ # extractall has already put the new binary over the working one.
+ if links:
+ # extractall would create the tree itself, so the probe must not be what needs it first.
+ base.mkdir(parents = True, exist_ok = True)
+ # A probe a killed install left behind must not answer for this one: symlink_to raises
+ # EEXIST on an existing path, which reads below as "no symlink support", and a restarted
+ # container reuses the pid while the directory persists. Sweep stragglers, and take a
+ # unique name so a concurrent install cannot collide either.
+ for stale in base.glob(".unsloth-symlink-probe-*"):
+ try:
+ stale.unlink()
+ except OSError:
+ pass
+ probe = base / f".unsloth-symlink-probe-{os.getpid()}-{os.urandom(4).hex()}"
+ try:
+ probe.symlink_to(".")
+ except OSError as exc:
+ # Windows outside developer mode is the one place flattening is right; see below.
+ if sys.platform != "win32":
+ raise RuntimeError(f"this filesystem cannot store symlinks: {exc}") from exc
+ else:
+ # missing_ok: a concurrent install's sweep may have taken this one already.
+ probe.unlink(missing_ok = True)
+ # extractall opens each destination "wb", which FOLLOWS a link a previous bundle left and
+ # writes the member into its target. Drop stale links first: a name one bundle ships as a link
+ # the next can ship as a file (the mirror ships copies where upstream ships links).
+ for dest, _ in written:
+ if dest.is_symlink():
+ dest.unlink()
+ zf.extractall(target, members = plain)
+ for dest, link_target, member in links:
+ # Re-resolved HERE: the pass above ran before any link existed, so an earlier member
+ # (a -> .) can turn a later member's parent into a link and send this outside base. Both
+ # ends are checked for containment, not for being link-free, so a tree that legitimately
+ # symlinks its own subdirectory still installs.
+ parent = Path(os.path.realpath(dest.parent))
+ resolved = (dest.parent / link_target).resolve()
+ if (parent != base and base not in parent.parents) or (
+ resolved != base and base not in resolved.parents
+ ):
+ raise RuntimeError(f"unsafe symlink in archive: {member.filename!r} -> {link_target!r}")
+ if dest.is_dir() and not dest.is_symlink():
+ raise RuntimeError(f"symlink member collides with a directory: {member.filename!r}")
+ dest.parent.mkdir(parents = True, exist_ok = True)
+ if dest.is_symlink() or dest.exists():
+ dest.unlink()
+ try:
+ dest.symlink_to(link_target)
+ except OSError as exc:
+ # Windows outside developer mode cannot create a link, and every Windows asset ships
+ # plain files, so flattening there costs nothing and keeps an install that used to
+ # finish finishing. Anywhere else a refusal means the filesystem cannot hold the layout
+ # sd-cli needs, and writing the link text back is the "file too short" install of #9268.
+ if sys.platform != "win32":
+ raise RuntimeError(
+ f"could not restore the symlink {member.filename!r}: {exc}"
+ ) from exc
+ # Load-bearing assumption: no published Windows asset ships a symlink member, so
+ # this writes the link text back only for an archive that never reaches a user.
+ # If that ever changes, this branch produces the #9268 install silently while the
+ # one above it raises, and it should be revisited rather than left as a fallback.
+ zf.extract(member, target)
def _maybe_fetch_windows_cudart(release: dict, chosen: str, target: Path) -> None:
@@ -664,7 +918,7 @@ def install(
"""
target = install_dir or default_install_dir()
# Claim ownership of `target` only if we created it, it was empty, or it is already marked: adopting a user's non-empty dir would let a later uninstall wipe it.
- marker = target / ".unsloth-studio-owned"
+ marker = target / OWNERSHIP_MARKER
_may_own = True
if target.exists():
if not target.is_dir():