#!/usr/bin/env python3 """chroot-tool.py - Guided chroot environment setup for system recovery on Fedora/Nobara systems. Scenario: A user boots from a live USB and needs to chroot into their installed Fedora/Nobara system to perform repairs. The tool guides them through LUKS detection and unlocking, LVM detection and activation, partition selection, fstab parsing, btrfs subvolume detection, topological mount ordering, bind mount setup, and clean exit with unmount. Required privileges: root (sudo) Interactive usage: Run without arguments for guided flow. """ from __future__ import annotations # ============================================================ # SECTION 1: Imports # ============================================================ import datetime import getpass import json import logging import os import pathlib import re import shutil import signal import subprocess import sys from dataclasses import dataclass, field from typing import Any, Callable, List, Optional, Protocol, Set, Tuple __version__ = "1.0.0" # --- Custom Exceptions --- class PreconditionError(Exception): """Tool cannot run: missing prerequisites.""" class ChrootError(Exception): """Runtime error during chroot operation.""" # ============================================================ # SECTION 2: Data Model # ============================================================ # --- Constants --- MOUNT_BASE = pathlib.Path("/tmp/chroot_mnt") FHS_INDICATORS = ["/etc", "/lib", "/usr", "/bin", "/etc/passwd", "/bin/sh"] VIRTUAL_FS_TYPES = { "tmpfs", "devtmpfs", "procfs", "sysfs", "cgroup", "cgroup2", "securityfs", "pstore", "debugfs", "tracefs", "fusectl", "configfs", "mqueue", "hugetlbfs", "devpts", "efivarfs", "autofs", "binfmt_misc", "rpc_pipefs", "nfsd", } BACKUP_SUBVOL_DIR_NAMES = {"timeshift-btrfs", "timeshift", "@timeshift", "@.snapshots", "@snapshots"} BACKUP_SUBVOL_PATTERNS = [".snapshots", "@snapshots", "timeshift", "@timeshift", "timeshift-btrfs"] DEFAULT_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" LOG_MAX_SIZE = 5 * 1024 * 1024 # 5 MiB BIND_MOUNTS = [ ("/dev", "dev", True), ("/dev/pts", "dev/pts", True), ("/proc", "proc", False), ("/sys", "sys", False), ("/run", "run", True), ] # --- Data Classes --- @dataclass class BlockDevice: name: str path: str size: str fstype: Optional[str] label: Optional[str] mountpoint: Optional[str] children: List["BlockDevice"] = field(default_factory=list) @dataclass class ProbeResult: device: str fstype: Optional[str] uuid: Optional[str] label: Optional[str] @dataclass class InspectionResult: device: str score: int indicators: List[str] fstype: Optional[str] fstab_content: Optional[str] = None @dataclass class FstabEntry: device: str mount_point: str fstype: str options: List[str] dump: int passnum: int subvol: Optional[str] = None @dataclass class MountPlanEntry: device: str mount_point: str fstype: str options: List[str] subvol: Optional[str] = None @dataclass class SubvolumeInfo: id: int name: str size: int @dataclass class MissingEntry: """Represents a mount plan entry whose device cannot be resolved.""" mount_plan_entry: MountPlanEntry mount_point: str expected_fstype: str @dataclass class Ranking: """A candidate partition ranked for a missing fstab entry.""" device: BlockDevice score: int fstype_match: bool same_disk: bool label_bonus: bool # ============================================================ # SECTION 3: Business Logic Functions # ============================================================ def _run_cmd(argv: list, **kwargs) -> subprocess.CompletedProcess: """Default command runner.""" return subprocess.run(argv, **kwargs, capture_output=True, text=True, timeout=30) def _parse_device(dev_data: dict) -> BlockDevice: """Recursively parse lsblk device JSON.""" children = [] for child_data in dev_data.get("children", []): children.append(_parse_device(child_data)) return BlockDevice( name=dev_data.get("name", ""), path=dev_data.get("path", f"/dev/{dev_data.get('name', '')}"), size=dev_data.get("size", ""), fstype=dev_data.get("fstype"), label=dev_data.get("label"), mountpoint=dev_data.get("mountpoint"), children=children, ) def _flatten_devices(devices: List[BlockDevice]) -> List[BlockDevice]: """Return only leaf devices (partitions), skipping parent disks.""" leaves: List[BlockDevice] = [] for dev in devices: if dev.children: leaves.extend(_flatten_devices(dev.children)) else: leaves.append(dev) return leaves def scan_block_devices(run_cmd: Optional[Callable] = None) -> List[BlockDevice]: """Run lsblk and return leaf device list (partitions, not parent disks).""" run_cmd = run_cmd or _run_cmd result = run_cmd(["lsblk", "--json", "-o", "NAME,PATH,SIZE,FSTYPE,LABEL,MOUNTPOINT"]) if result.returncode != 0: raise ChrootError(f"lsblk failed: {result.stderr.strip()}") data = json.loads(result.stdout) devices = [_parse_device(d) for d in data.get("blockdevices", [])] return _flatten_devices(devices) def build_device_map(devices: List[BlockDevice]) -> Dict[str, str]: """Walk the full lsblk tree and map every device path to its parent disk. A disk is a node with no children. Every descendant gets the disk path. """ mapping: Dict[str, str] = {} def walk(node: BlockDevice, parent_disk: Optional[str] = None) -> None: if not node.children: # node is a disk (no children) mapping[node.path] = node.path parent_disk = node.path else: parent_disk = parent_disk or node.path for child in node.children: mapping[child.path] = parent_disk or node.path walk(child, parent_disk or node.path) for dev in devices: walk(dev) return mapping def probe_device(device: str, run_cmd: Optional[Callable] = None) -> ProbeResult: """Run blkid -p on device and return filesystem info.""" run_cmd = run_cmd or _run_cmd result = run_cmd(["blkid", "-p", device]) if result.returncode != 0: return ProbeResult(device=device, fstype=None, uuid=None, label=None) output = result.stdout.strip() fstype = uuid = label = None for part in output.split(): if part.startswith("TYPE="): fstype = part.split('"')[1] if '"' in part else None elif part.startswith("UUID="): uuid = part.split('"')[1] if '"' in part else None elif part.startswith("LABEL="): label = part.split('"')[1] if '"' in part else None return ProbeResult(device=device, fstype=fstype, uuid=uuid, label=label) def get_host_mounts() -> Set[str]: """Read /proc/mounts to get set of block device paths currently mounted.""" mounts: Set[str] = set() try: content = pathlib.Path("/proc/mounts").read_text() for line in content.splitlines(): parts = line.split() if len(parts) >= 2 and parts[0].startswith("/dev/"): mounts.add(parts[0]) except Exception: pass return mounts def is_mounted_on_host( device: str, host_mounts: Optional[Set[str]] = None, probe_result: Optional[ProbeResult] = None, run_cmd: Optional[Callable] = None, ) -> bool: """Check if device is already mounted on host or referenced in host fstab.""" run_cmd = run_cmd or _run_cmd real_device = device try: real_device = str(pathlib.Path(device).resolve()) except OSError: pass if host_mounts: if device in host_mounts or real_device in host_mounts: return True result = run_cmd(["findmnt", "-n", "-o", "SOURCE", device]) if result.returncode == 0 and result.stdout.strip(): return True try: fstab_path = pathlib.Path("/etc/fstab") if fstab_path.exists(): content = fstab_path.read_text() for line in content.splitlines(): line = line.strip() if not line or line.startswith("#"): continue parts = line.split() if len(parts) < 2: continue dev = parts[0] mount = parts[1] if mount in ("/", "/boot", "/boot/efi", "/home", "/var"): if dev == device: return True if probe_result and probe_result.uuid and dev.startswith("UUID="): uuid_part = dev.split("=", 1)[1].strip('"') if uuid_part == probe_result.uuid: return True except Exception: pass return False def inspect_partition( device: str, mount_base: pathlib.Path, probe_result: ProbeResult, run_cmd: Optional[Callable] = None, logger: Optional[logging.Logger] = None, ) -> InspectionResult: """Check FHS indicators on a device. If the device is already mounted (e.g. from a previous run that didn't fully clean up), use the existing mount point instead of trying to mount it again. """ run_cmd = run_cmd or _run_cmd dev_name = pathlib.Path(device).name mount_point = mount_base / f".inspect_{dev_name}" indicators: List[str] = [] fstab_content: Optional[str] = None already_mounted = False try: # Check if device is already mounted somewhere result = run_cmd(["findmnt", "-n", "-o", "TARGET", device]) existing_mount: Optional[str] = None if result.returncode == 0 and result.stdout.strip(): existing_mount = result.stdout.strip().split()[0] already_mounted = True if already_mounted and existing_mount: # Device already mounted — use existing mount point mount_point = pathlib.Path(existing_mount) else: # Not mounted — mount it read-only mount_point.mkdir(parents=True, exist_ok=True) result = run_cmd(["mount", "-o", "ro", device, str(mount_point)]) if result.returncode != 0: stderr = result.stderr.strip() if result.stderr else "(empty)" if logger: logger.error("Mount failed for %s: %s", device, stderr) return InspectionResult( device=device, score=0, indicators=[], fstype=probe_result.fstype ) for indicator in FHS_INDICATORS: check_path = mount_point / indicator.lstrip("/") if check_path.exists(): indicators.append(indicator) fstab_path = mount_point / "etc" / "fstab" if fstab_path.exists(): try: fstab_content = fstab_path.read_text() except OSError: pass return InspectionResult( device=device, score=len(indicators), indicators=indicators, fstype=probe_result.fstype, fstab_content=fstab_content, ) finally: if not already_mounted: try: run_cmd(["umount", str(mount_point)]) except Exception: pass try: mount_point.rmdir() except OSError: pass try: mount_point.rmdir() except OSError: pass def score_candidates(candidates: List[InspectionResult]) -> List[InspectionResult]: """Rank by score descending, then device path for determinism.""" return sorted(candidates, key=lambda c: (-c.score, c.device)) def is_btrfs(probe_result: ProbeResult) -> bool: """Check if device filesystem is btrfs.""" return probe_result.fstype == "btrfs" def btrfs_read_fstab( device: str, mount_base: pathlib.Path, run_cmd: Optional[Callable] = None, ) -> Optional[str]: """Mount btrfs top-level (ID 5) read-only, find fstab, unmount, return contents.""" run_cmd = run_cmd or _run_cmd mount_point = mount_base / ".btrfs_top" try: mount_point.mkdir(parents=True, exist_ok=True) result = run_cmd(["mount", "-o", "ro,subvol=/", device, str(mount_point)]) if result.returncode != 0: return None fstab_path = mount_point / "etc" / "fstab" if fstab_path.exists(): return fstab_path.read_text() for entry in sorted(mount_point.iterdir()): if entry.name in BACKUP_SUBVOL_DIR_NAMES: continue if entry.is_dir(): candidate = entry / "etc" / "fstab" if candidate.exists(): return candidate.read_text() return None finally: try: run_cmd(["umount", str(mount_point)]) except Exception: pass try: mount_point.rmdir() except OSError: pass def btrfs_list_subvolumes( mount_point: str, run_cmd: Optional[Callable] = None, ) -> List[SubvolumeInfo]: """Run btrfs subvolume list and return list of (id, name, size).""" run_cmd = run_cmd or _run_cmd result = run_cmd(["btrfs", "subvolume", "list", mount_point]) if result.returncode != 0: return [] subvolumes: List[SubvolumeInfo] = [] for line in result.stdout.strip().splitlines(): match = re.search(r"(\d+)\s+.*\spath\s+(\S+)$", line) if match: sub_id = int(match.group(1)) name = match.group(2) subvol_path = pathlib.Path(mount_point) / name try: size_result = run_cmd(["du", "-sb", str(subvol_path)]) size = int(size_result.stdout.split()[0]) except Exception: size = 0 subvolumes.append(SubvolumeInfo(id=sub_id, name=name, size=size)) return subvolumes def btrfs_exclude_backup_subvolumes( subvolumes: List[SubvolumeInfo], ) -> List[SubvolumeInfo]: """Filter out snapper and timeshift subvolumes.""" result: List[SubvolumeInfo] = [] for sv in subvolumes: skip = False for pattern in BACKUP_SUBVOL_PATTERNS: if pattern in sv.name: skip = True break if not skip: result.append(sv) return result def btrfs_detect_root_subvol(fstab_content: str) -> Optional[str]: """Parse subvol= from fstab / entry.""" for line in fstab_content.splitlines(): line = line.strip() if not line or line.startswith("#"): continue parts = line.split() if len(parts) >= 2 and parts[1] == "/": for opt in parts[3].split(",") if len(parts) > 3 else []: if opt.startswith("subvol="): return opt.split("=", 1)[1] return None def btrfs_fallback_detect_subvolumes( subvolumes: List[SubvolumeInfo], device: str, mount_base: pathlib.Path, run_cmd: Optional[Callable] = None, ) -> Optional[str]: """Check for @, root, @root subvolumes in order and verify root indicators.""" run_cmd = run_cmd or _run_cmd candidates = ["@", "root", "@root"] for name in candidates: for sv in subvolumes: if sv.name == name: mount_point = mount_base / ".btrfs_fallback" try: mount_point.mkdir(parents=True, exist_ok=True) result = run_cmd([ "mount", "-o", f"ro,subvol={name}", device, str(mount_point) ]) if result.returncode == 0: has_passwd = (mount_point / "etc" / "passwd").exists() has_sh = ( (mount_point / "bin" / "sh").exists() or (mount_point / "usr" / "bin" / "sh").exists() ) run_cmd(["umount", str(mount_point)]) if has_passwd and has_sh: return name except Exception: pass finally: try: mount_point.rmdir() except OSError: pass return None def btrfs_mount_subvol( device: str, subvol: str, mount_point: str, run_cmd: Optional[Callable] = None, ) -> bool: """Mount with subvol= option and verify root indicators.""" run_cmd = run_cmd or _run_cmd result = run_cmd(["mount", "-o", f"subvol={subvol}", device, mount_point]) if result.returncode != 0: return False mp = pathlib.Path(mount_point) has_passwd = (mp / "etc" / "passwd").exists() has_sh = (mp / "bin" / "sh").exists() or (mp / "usr" / "bin" / "sh").exists() if not (has_passwd and has_sh): run_cmd(["umount", mount_point]) return False return True def _parse_fstab_lines(text: str) -> List[FstabEntry]: """Parse fstab content string into FstabEntry list.""" entries: List[FstabEntry] = [] for line in text.splitlines(): line = line.strip() if not line or line.startswith("#"): continue parts = line.split() if len(parts) < 2: continue device = parts[0] mount = parts[1] fstype = parts[2] if len(parts) > 2 else "unknown" options = parts[3].split(",") if len(parts) > 3 else [] dump = int(parts[4]) if len(parts) > 4 else 0 passnum = int(parts[5]) if len(parts) > 5 else 0 subvol = None for opt in options: if opt.startswith("subvol="): subvol = opt.split("=", 1)[1] break entries.append(FstabEntry( device=device, mount_point=mount, fstype=fstype, options=options, dump=dump, passnum=passnum, subvol=subvol, )) return entries def read_fstab(mount_point: str) -> List[FstabEntry]: """Read and parse /etc/fstab from mounted partition.""" fstab_path = pathlib.Path(mount_point) / "etc" / "fstab" if not fstab_path.exists(): return [] return _parse_fstab_lines(fstab_path.read_text()) def read_fstab_from_content(content: str) -> List[FstabEntry]: """Parse fstab from a string (no filesystem access).""" return _parse_fstab_lines(content) def resolve_uuid(uuid: str) -> Optional[str]: """Resolve UUID to device path via /dev/disk/by-uuid/.""" link = pathlib.Path(f"/dev/disk/by-uuid/{uuid}") if link.is_symlink(): return str(link.resolve()) return None def filter_fstab_entries(entries: List[FstabEntry]) -> List[FstabEntry]: """Skip swap, virtual filesystems, and noauto entries.""" result: List[FstabEntry] = [] for entry in entries: if entry.fstype == "swap": continue if entry.fstype in VIRTUAL_FS_TYPES: continue if "noauto" in entry.options: continue result.append(entry) return result def topological_sort(entries: List[FstabEntry]) -> List[FstabEntry]: """Sort by mount point depth then alphabetically.""" def depth(mp: str) -> int: return len(pathlib.Path(mp).parts) return sorted(entries, key=lambda e: (depth(e.mount_point), e.mount_point)) def generate_mount_plan( root_device: str, root_subvol: Optional[str], sorted_entries: List[FstabEntry], ) -> List[MountPlanEntry]: """Produce final mount plan with resolved devices and subvolumes.""" plan: List[MountPlanEntry] = [] for entry in sorted_entries: if entry.device.startswith("UUID="): uuid_part = entry.device.split("=", 1)[1] device = resolve_uuid(uuid_part) or entry.device else: device = entry.device plan.append(MountPlanEntry( device=device, mount_point=entry.mount_point, fstype=entry.fstype, options=entry.options, subvol=entry.subvol, )) if root_subvol and plan: plan[0].subvol = root_subvol return plan def detect_missing_entries( plan: List[MountPlanEntry], logger: Optional[logging.Logger] = None, ) -> List[MissingEntry]: """Detect mount plan entries whose device cannot be resolved. A device is unresolved when: - It starts with UUID= and the symlink is not in /dev/disk/by-uuid/ - It is a device path that does not exist """ missing: List[MissingEntry] = [] for entry in plan: if entry.device.startswith("UUID="): uuid_part = entry.device.split("=", 1)[1] link = pathlib.Path(f"/dev/disk/by-uuid/{uuid_part}") if not link.is_symlink(): if logger: logger.info( "Missing entry: %s (UUID=%s, fstype=%s)", entry.mount_point, uuid_part, entry.fstype, ) missing.append(MissingEntry( mount_plan_entry=entry, mount_point=entry.mount_point, expected_fstype=entry.fstype, )) else: if not pathlib.Path(entry.device).exists(): if logger: logger.info( "Missing entry: %s (device=%s, fstype=%s)", entry.mount_point, entry.device, entry.fstype, ) missing.append(MissingEntry( mount_plan_entry=entry, mount_point=entry.mount_point, expected_fstype=entry.fstype, )) return missing # --- Missing Entry Replacement Logic --- _LABEL_HINTS = {"boot", "efi", "bootefi", "boot-efi", "boot_efi"} _SIZE_THRESHOLDS = { "/boot": { "small": (536870912, 20), # ≤512MB → +20 "ok": (1073741824, 10), # ≤1GB → +10 "large": (5368709120, -10), # >5GB → −10 "huge": (21474836480, -30), # >20GB → −30 }, "/boot/efi": { "small": (104857600, 20), # ≤100MB → +20 "ok": (209715200, 10), # ≤200MB → +10 "large": (1073741824, -10), # >1GB → −10 "huge": (4294967296, -30), # >4GB → −30 }, } def _parse_size_bytes(size_str: str) -> Optional[int]: """Parse a human-readable size string (e.g. '512M', '1.0G') into bytes.""" size_str = size_str.strip().upper() multipliers = {"K": 1024, "M": 1024**2, "G": 1024**3, "T": 1024**4} for suffix, mult in multipliers.items(): if size_str.endswith(suffix): try: return int(float(size_str[: -len(suffix)]) * mult) except ValueError: return None try: return int(size_str) except ValueError: return None def _size_heuristic(mount_point: str, size_bytes: int) -> int: """Return a size bonus/penalty based on mount point and candidate size.""" thresholds = _SIZE_THRESHOLDS.get(mount_point) if thresholds is None: return 0 if size_bytes <= thresholds["small"][0]: return thresholds["small"][1] if size_bytes <= thresholds["ok"][0]: return thresholds["ok"][1] if size_bytes > thresholds["huge"][0]: return thresholds["huge"][1] if size_bytes > thresholds["large"][0]: return thresholds["large"][1] return 0 def _label_bonus(label: Optional[str], mount_point: str) -> bool: """Check if the label hints at the expected mount point. Returns True if the label contains a hint keyword. """ if not label: return False return any(hint in label.lower() for hint in _LABEL_HINTS) def compute_ranking_score( candidate: BlockDevice, expected_fstype: str, mount_point: str, root_disk: Optional[str], ) -> int: """Score a candidate partition for a missing fstab entry. Signals: - Filesystem type match: +100 - Same physical disk as root: +15 - Label match: +5 - Size heuristic: +20 to −30 """ score = 0 # Filesystem type match if candidate.fstype == expected_fstype: score += 100 # Same disk as root if root_disk and candidate.path.startswith(root_disk): score += 15 # Label match if _label_bonus(candidate.label, mount_point): score += 5 # Size heuristic size_bytes = _parse_size_bytes(candidate.size) if size_bytes is not None: score += _size_heuristic(mount_point, size_bytes) return score def find_replacement_candidates( missing: MissingEntry, all_devices: List[BlockDevice], device_map: Dict[str, str], root_disk: Optional[str], logger: Optional[logging.Logger] = None, ) -> List[Ranking]: """Score all leaf devices and return top 5 ranked candidates. all_devices should be the full tree (not flattened) so we can traverse to find parent disks. We score leaf devices only. """ # Flatten to get leaf devices leaves: List[BlockDevice] = [] for dev in all_devices: if dev.children: leaves.extend(_flatten_devices([dev])) else: leaves.append(dev) rankings: List[Ranking] = [] for dev in leaves: score = compute_ranking_score( dev, missing.expected_fstype, missing.mount_point, root_disk, ) fstype_match = dev.fstype == missing.expected_fstype same_disk = root_disk is not None and dev.path.startswith(root_disk) label_bonus = _label_bonus(dev.label, missing.mount_point) rankings.append(Ranking( device=dev, score=score, fstype_match=fstype_match, same_disk=same_disk, label_bonus=label_bonus, )) # Sort by score descending rankings.sort(key=lambda r: r.score, reverse=True) # Log score breakdown if logger: for r in rankings[:10]: # log top 10 for debugging logger.info( "Ranking %s: score=%d, fstype_match=%s, same_disk=%s, label_bonus=%s", r.device.path, r.score, r.fstype_match, r.same_disk, r.label_bonus, ) # Return top 5 return rankings[:5] # --- Parent Directory Creation --- def create_parent_directories( plan: List[MountPlanEntry], mount_base: str, mounted_paths: List[str], run_cmd: Optional[Callable] = None, confirm_create: Optional[Callable] = None, ) -> Tuple[List[str], List[str]]: """Create missing parent directories on already-mounted partitions. For each entry in the plan: - If its parent is root (no parent in plan), check mount_base - If its parent is another plan entry, check the mounted parent partition - Create the directory if it doesn't exist (with confirmation) Returns (created_paths, failed_paths). """ run_cmd = run_cmd or _run_cmd mount_point_to_path: Dict[str, str] = {} for mp in mounted_paths: mount_point_to_path[mp] = mp created: List[str] = [] failed: List[str] = [] plan_mount_points = {e.mount_point for e in plan} for entry in plan: mp = entry.mount_point.lstrip("/") if mp == "": # Root has no parent in the plan continue parent_mp = pathlib.Path(mp).parent parent_mp_str = str(parent_mp) # Find the mount point for this parent if parent_mp_str in plan_mount_points: # Parent is another plan entry; check mounted partition parent_mount_path = mount_point_to_path.get(parent_mp_str) if parent_mount_path is None: # Parent not yet mounted — skip (will be handled when parent is mounted) continue dir_path = pathlib.Path(parent_mount_path) / mp else: # Parent is root; check mount_base dir_path = pathlib.Path(mount_base) / mp if dir_path.exists(): continue # Directory doesn't exist; ask user to create it if confirm_create and not confirm_create(str(dir_path)): failed.append(str(dir_path)) continue try: dir_path.mkdir(parents=True, exist_ok=True) created.append(str(dir_path)) except OSError: failed.append(str(dir_path)) return created, failed # --- LUKS/LVM Business Logic --- def _detect_luks_preexisting(device: str, run_cmd: Optional[Callable] = None) -> bool: """Check if a LUKS device is already unlocked (pre-existing).""" run_cmd = run_cmd or _run_cmd result = run_cmd(["cryptsetup", "status", device]) return result.returncode == 0 and result.stdout.strip() != "" def detect_locked_luks( devices: List[BlockDevice], run_cmd: Optional[Callable] = None, ) -> List[Tuple[str, str, str]]: """Detect locked LUKS devices. Returns list of (device_path, uuid, size) for locked LUKS partitions. Already-unlocked LUKS devices are excluded. """ run_cmd = run_cmd or _run_cmd locked: List[Tuple[str, str, str]] = [] for dev in devices: device_path = dev.path probe = probe_device(device_path, run_cmd=run_cmd) if probe.fstype != "crypto_LUKS": continue if _detect_luks_preexisting(device_path, run_cmd=run_cmd): continue locked.append((device_path, probe.uuid or "", dev.size or "")) return sorted(locked, key=lambda x: x[0]) def _generate_luks_mapper_name(device: str) -> str: """Generate a deterministic mapper name from device path.""" base = pathlib.Path(device).name return f"chroot_{base}" def _luks_mapper_exists(mapper_name: str) -> bool: """Check if a device mapper entry already exists.""" return pathlib.Path(f"/dev/mapper/{mapper_name}").exists() def prompt_luks_passphrase( device: str, mapper_name: str, passphrase: Optional[str] = None, run_cmd: Optional[Callable] = None, ) -> Optional[str]: """Validate a passphrase for a LUKS device. Returns the validated passphrase on success, None on failure. If passphrase is None, returns None (no prompting -- flow controller handles it). """ if passphrase is None: return None run_cmd = run_cmd or _run_cmd result = subprocess.run( ["cryptsetup", "open", "--test-passphrase", device], input=passphrase, capture_output=True, text=True, timeout=30, ) return passphrase if result.returncode == 0 else None def unlock_luks( device: str, mapper_name: str, run_cmd: Optional[Callable] = None, passphrase: Optional[str] = None, logger: Optional[logging.Logger] = None, ) -> bool: """Unlock a LUKS device and create the mapper entry. Requires a passphrase; returns True on success, False on failure. """ run_cmd = run_cmd or _run_cmd if passphrase is None: if logger: logger.error("No passphrase provided for %s", device) return False result = run_cmd( ["cryptsetup", "open", "--type", "luks", device, mapper_name], input=passphrase, ) if result.returncode != 0: stderr = result.stderr.strip() if result.stderr else "(empty)" if logger: logger.error("cryptsetup open failed for %s: %s", device, stderr) return result.returncode == 0 def detect_inactive_vgs( vg_preexisting: Set[str], vg_discovered_after_unlock: Optional[Set[str]] = None, run_cmd: Optional[Callable] = None, ) -> List[str]: """Detect inactive volume groups not already active. Uses lvs -o lv_attr to check whether each VG has active logical volumes. The lv_attr field has 'a' at position 4 when the LV is active, '-' when inactive. A VG that appears in vgs (because PVs are accessible — e.g. LUKS already open) but has no active LVs is considered inactive and needs activation. Returns sorted list of inactive VG names. """ run_cmd = run_cmd or _run_cmd result = run_cmd(["vgs", "--noheadings", "-o", "vg_name"]) if result.returncode != 0: return [] current_vgs: Set[str] = set() for name in result.stdout.split(): name = name.strip() if name: current_vgs.add(name) # Check lv_attr for the 'a' flag (position 4) to determine activity. active_vgs: Set[str] = set() for vg in sorted(current_vgs): lvs_result = run_cmd( ["lvs", "--noheadings", "-o", "lv_attr", vg] ) if lvs_result.returncode == 0: for line in lvs_result.stdout.splitlines(): attr = line.strip() if len(attr) >= 5 and attr[4] == 'a': active_vgs.add(vg) break # Exclude truly active VGs and VGs discovered after unlock excluded = active_vgs | (vg_discovered_after_unlock or set()) inactive = sorted(current_vgs - excluded) return inactive def activate_vg( vg_name: str, run_cmd: Optional[Callable] = None, ) -> bool: """Activate a volume group.""" run_cmd = run_cmd or _run_cmd result = run_cmd(["vgchange", "-ay", vg_name]) return result.returncode == 0 # --- Mount / Bind Mount Functions --- def is_uefi() -> bool: """Check for UEFI via /sys/firmware/efi/efivars.""" return pathlib.Path("/sys/firmware/efi/efivars").exists() def bind_mount( source: str, target: str, recursive: bool = False, run_cmd: Optional[Callable] = None, ) -> bool: """Perform a single bind mount with rslave propagation. rslave ensures the chroot sees host mounts while preventing child mounts created inside the chroot from propagating back to the host. """ run_cmd = run_cmd or _run_cmd pathlib.Path(target).mkdir(parents=True, exist_ok=True) cmd = ["mount"] if recursive: cmd.append("--rbind") else: cmd.append("--bind") cmd.extend([source, target]) result = run_cmd(cmd) if result.returncode != 0: return False # Set propagation to rslave so chroot child mounts don't leak to host result = run_cmd(["mount", "--make-rslave", target]) return result.returncode == 0 def setup_bind_mounts( base_mount: str, run_cmd: Optional[Callable] = None, ) -> List[Tuple[str, bool]]: """Set up all Fedora-standard bind mounts in order.""" results: List[Tuple[str, bool]] = [] for source, rel, recursive in BIND_MOUNTS: target = pathlib.Path(base_mount) / rel success = bind_mount(source, str(target), recursive=recursive, run_cmd=run_cmd) results.append((str(target), success)) if is_uefi(): source = "/sys/firmware/efi/efivars" target = pathlib.Path(base_mount) / "sys/firmware/efi/efivars" success = bind_mount(source, str(target), run_cmd=run_cmd) results.append((str(target), success)) return results def mount_single( entry: MountPlanEntry, base_mount: str, run_cmd: Optional[Callable] = None, ) -> Tuple[bool, str]: """Mount a single entry with error handling.""" run_cmd = run_cmd or _run_cmd target = pathlib.Path(base_mount) / entry.mount_point.lstrip("/") if not target.exists(): return False, "Directory does not exist" cmd = ["mount"] opts = list(entry.options) if entry.subvol: opts.append(f"subvol={entry.subvol}") if opts: cmd.extend(["-o", ",".join(opts)]) cmd.extend([entry.device, str(target)]) result = run_cmd(cmd) if result.returncode != 0: return False, result.stderr.strip() return True, "" def execute_mount_plan( plan: List[MountPlanEntry], mount_base: str, run_cmd: Optional[Callable] = None, prompt_create: Optional[Callable] = None, prompt_parent_create: Optional[Callable] = None, ) -> Tuple[List[str], List[str]]: """Mount each entry in order; return (mounted_paths, failures). For each entry: - If its parent is root: prompt_create for the mount point directory - If its parent is another plan entry: check the mounted parent partition for the parent directory, create it if missing (with prompt_parent_create) """ run_cmd = run_cmd or _run_cmd mounted: List[str] = [] failures: List[str] = [] plan_mount_points = {e.mount_point.lstrip("/") for e in plan} # Map mount point → mount path for already-mounted entries mounted_map: Dict[str, str] = {} for entry in plan: mp = entry.mount_point.lstrip("/") target = pathlib.Path(mount_base) / mp # Determine parent mount point parent_mp = pathlib.Path(mp).parent parent_mp_str = str(parent_mp) # Check if parent directory exists parent_dir_ok = False if parent_mp_str == "": # Parent is root — target directory will be created below parent_dir_ok = True elif parent_mp_str in plan_mount_points: # Parent is another plan entry — check mounted partition # mounted_map keys are mount points with leading slash stripped parent_key = parent_mp_str.lstrip("/") parent_mount = mounted_map.get(parent_key) if parent_mount: # Compute the relative path from parent mount point to this entry # e.g. mp="boot/efi", parent_mp_str="boot" → relative="efi" rel = pathlib.Path(mp).relative_to(parent_mp) parent_dir = pathlib.Path(parent_mount) / rel if parent_dir.exists(): parent_dir_ok = True elif prompt_parent_create and prompt_parent_create(str(parent_dir)): try: parent_dir.mkdir(parents=True, exist_ok=True) parent_dir_ok = True except OSError: pass else: # Parent is not in plan — treat as root-level parent_dir_ok = True if not parent_dir_ok: if prompt_create and not prompt_create(str(target)): return [], [f"Aborted: user declined to create {target}"] target.mkdir(parents=True) success, error = mount_single(entry, mount_base, run_cmd=run_cmd) if success: mounted.append(str(target)) # Store with stripped key for consistent lookup mounted_map[mp] = str(target) else: failures.append(f"{entry.mount_point}: {error}") return mounted, failures return mounted, failures # --- Chroot Entry --- def setup_chroot_env() -> dict: """Set environment variables for chroot.""" env = os.environ.copy() env["HOME"] = "/root" env["PATH"] = DEFAULT_PATH return env def enter_chroot(mount_point: str) -> int: """Run chroot interactively without specifying a shell; TERM preserved.""" env = setup_chroot_env() proc = subprocess.Popen( ["chroot", mount_point], env=env, ) return proc.wait() # --- Cleanup --- def umount_single(path: str, run_cmd: Optional[Callable] = None) -> bool: """Attempt unmount; return success/failure. Uses recursive unmount (-R) to handle nested sub-mounts. Falls back to lazy recursive (-lR) when the mount point is busy (e.g. host processes hold file descriptors there). With --make-rslave propagation is severed so lazy unmount never affects the host. """ run_cmd = run_cmd or _run_cmd result = run_cmd(["umount", "-R", path]) if result.returncode == 0: return True # Mount point busy — lazy unmount detaches immediately, cleans up refs result = run_cmd(["umount", "-lR", path]) return result.returncode == 0 def cleanup_mounts( mounted_paths: List[str], run_cmd: Optional[Callable] = None, ) -> List[str]: """Unmount in reverse order; return list of failed paths.""" run_cmd = run_cmd or _run_cmd failed: List[str] = [] for path in reversed(mounted_paths): success = umount_single(path, run_cmd=run_cmd) if not success: failed.append(path) return failed def report_stuck_mounts(failed: List[str]) -> List[str]: """Generate cleanup instructions for stuck mounts. Returns a list of formatted message strings. """ messages: List[str] = [] for path in failed: messages.append(f"[warn] Stuck mount: {path}") messages.append(f" Manual cleanup: sudo umount -l {path}") return messages # --- Logging --- def setup_logging(log_file: Optional[str] = None) -> logging.Logger: """Set up logging to file with banner, mode 0600, rotation.""" if log_file is None: log_file = "/tmp/chroot-tool.log" log_path = pathlib.Path(log_file) if log_path.exists() and log_path.stat().st_size > LOG_MAX_SIZE: rotated = log_path.with_suffix(log_path.suffix + ".1") log_path.rename(rotated) log_path.parent.mkdir(parents=True, exist_ok=True) fd = os.open(str(log_path), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) os.close(fd) logger = logging.getLogger("chroot-tool") logger.setLevel(logging.DEBUG) file_handler = logging.FileHandler(str(log_path), mode="a") file_handler.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s") file_handler.setFormatter(formatter) logger.addHandler(file_handler) banner_lines = [ "=" * 60, f"chroot-tool v{__version__}", f"Start time: {datetime.datetime.now().isoformat()}", f"argv: {' '.join(sys.argv)}", f"Running as root: {os.geteuid() == 0}", "=" * 60, ] logger.info("\n".join(banner_lines)) return logger # ============================================================ # SECTION 4: Flow Result # ============================================================ @dataclass class FlowResult: """Result of a flow step.""" done: bool exit_code: Optional[int] = None error: Optional[str] = None # ============================================================ # SECTION 5: ChrootView Protocol # ============================================================ class ChrootView(Protocol): """Protocol for UI views (console or tkinter). Both ConsoleView and TkView implement this protocol. """ def status(self, msg: str) -> None: ... def info(self, msg: str) -> None: ... def error(self, msg: str) -> None: ... def warn(self, msg: str) -> None: ... def prompt(self, msg: str) -> str: ... def confirm(self, msg: str) -> bool: ... def select(self, msg: str, options: List[str]) -> int: ... def display(self, data: Any) -> None: ... def display_missing(self, missing: MissingEntry, candidates: List[Ranking]) -> int: ... def confirm_dir_create(self, path: str) -> bool: ... def show_chroot_complete(self, exit_code: int) -> None: ... # ============================================================ # SECTION 6: ChrootFlow (State Machine) # ============================================================ class ChrootFlow: """Orchestrates the guided chroot setup flow via a ChrootView.""" def __init__(self, view: ChrootView, run_cmd=None): self.view = view self._run_cmd = run_cmd or _run_cmd self.state: dict = {} self.mount_base = MOUNT_BASE self.target_device: Optional[str] = None self.target_probe: Optional[ProbeResult] = None self.target_subvol: Optional[str] = None self.mount_plan: List[MountPlanEntry] = [] self.mounted_paths: List[str] = [] self.device_map: Dict[str, str] = {} self.root_disk: Optional[str] = None # LUKS/LVM state tracking self.devices: List[BlockDevice] = [] self._luks_unlocked: List[Tuple[str, str]] = [] self._luks_denied: Set[str] = set() self._luks_preexisting: Set[str] = set() self._vg_activated: List[str] = [] self._vg_denied: Set[str] = set() self._vg_preexisting: Set[str] = set() self._vg_discovered_after_unlock: Set[str] = set() def run(self) -> int: """Execute the guided chroot setup flow.""" steps = [ self._step_luks_lvm_discovery, self._step_scan, self._step_inspect, self._step_select, self._step_btrfs, self._step_fstab, self._step_plan, self._step_replace_missing, self._step_mount, self._step_bind, self._step_chroot, self._step_cleanup, ] for step in steps: result = step() if result.done: return result.exit_code or 0 return 0 def _rescan_after_luks_lvm(self) -> None: """Re-scan block devices after LUKS unlock and LVM activation.""" self.devices = scan_block_devices(run_cmd=self._run_cmd) def _step_luks_lvm_discovery(self) -> FlowResult: """Loop-based LUKS/LVM discovery with user confirmation.""" self.devices = scan_block_devices(run_cmd=self._run_cmd) # Detect pre-existing VGs try: result = self._run_cmd(["vgs", "--noheadings", "-o", "vg_name"]) if result.returncode == 0: for name in result.stdout.split(): name = name.strip() if name: self._vg_preexisting.add(name) except Exception: pass while True: locked = detect_locked_luks(self.devices, run_cmd=self._run_cmd) locked = [(d, u, s) for d, u, s in locked if d not in self._luks_denied] inactive_vgs = detect_inactive_vgs( self._vg_preexisting, vg_discovered_after_unlock=self._vg_discovered_after_unlock, run_cmd=self._run_cmd, ) inactive_vgs = [vg for vg in inactive_vgs if vg not in self._vg_denied] if not locked and not inactive_vgs: break any_unlocked = False if locked: self.view.status("Detected locked LUKS devices:") for device, uuid, size in locked: self.view.info(f" LUKS: {device} Size: {size} UUID: {uuid}") if inactive_vgs: self.view.status("Detected inactive volume groups:") for vg in inactive_vgs: self.view.info(f" VG: {vg}") for device, uuid, size in locked: if not self.view.confirm(f"Unlock {device} (size={size}, uuid={uuid})?"): self._luks_denied.add(device) continue mapper_name = _generate_luks_mapper_name(device) if _luks_mapper_exists(mapper_name): self.view.warn(f"Mapper '{mapper_name}' already exists, skipping.") continue self.view.status(f"Unlocking {device}...") passphrase = None for attempt in range(1, 4): passphrase = self.view.prompt( f"Enter passphrase for {device} (attempt {attempt}/3): " ) if not passphrase: self.view.error("No input available.") break validated = prompt_luks_passphrase( device, mapper_name, passphrase=passphrase, run_cmd=self._run_cmd ) if validated is not None: break if attempt < 3: self.view.warn("Incorrect passphrase. Try again.") else: self.view.error( f"Incorrect passphrase for {device} after 3 attempts." ) if passphrase is None: self._luks_denied.add(device) continue vgs_before_unlock = ( set(self._vg_discovered_after_unlock) | self._vg_preexisting ) if unlock_luks(device, mapper_name, run_cmd=self._run_cmd, passphrase=passphrase): self._luks_unlocked.append((device, mapper_name)) self.view.info(f"Unlocked {device} -> {mapper_name}") any_unlocked = True result = self._run_cmd(["vgs", "--noheadings", "-o", "vg_name"]) if result.returncode == 0: for name in result.stdout.split(): name = name.strip() if name: self._vg_discovered_after_unlock.add(name) if name not in vgs_before_unlock: self._vg_activated.append(name) else: self.view.error(f"Failed to unlock {device}.") self._luks_denied.add(device) for vg in inactive_vgs: if not self.view.confirm(f"Activate volume group {vg}?"): self._vg_denied.add(vg) continue self.view.status(f"Activating volume group {vg}...") if activate_vg(vg, run_cmd=self._run_cmd): self._vg_activated.append(vg) self.view.info(f"Activated volume group: {vg}") else: self.view.error(f"Failed to activate volume group: {vg}") self._vg_denied.add(vg) if any_unlocked: self._rescan_after_luks_lvm() return FlowResult(done=False) def _step_scan(self) -> FlowResult: """Scan block devices, probe, filter host-mounted, return candidates.""" self.view.status("Scanning block devices...") self._rescan_after_luks_lvm() devices = scan_block_devices(run_cmd=self._run_cmd) self.view.info(f"Found {len(devices)} block devices") self._rescan_after_luks_lvm() host_mounts = get_host_mounts() candidates: List[Tuple[str, ProbeResult]] = [] skipped: List[str] = [] for device in devices: device_path = device.path probe = probe_device(device_path, run_cmd=self._run_cmd) if is_mounted_on_host(device_path, host_mounts, probe, run_cmd=self._run_cmd): skipped.append(device_path) continue candidates.append((device_path, probe)) if skipped: self.view.warn(f"Skipped {len(skipped)} host-mounted device(s)") if not candidates: self.view.error("No non-host block devices found.") return FlowResult(done=True, exit_code=1) self.state["candidates"] = candidates return FlowResult(done=False) def _step_inspect(self) -> FlowResult: """Mount each candidate read-only, score by FHS indicators, sort, return scored list.""" self.view.status("Inspecting candidates (read-only)...") candidates = self.state.get("candidates", []) scored: List[InspectionResult] = [] for device_path, probe in candidates: result = inspect_partition( device_path, self.mount_base, probe, run_cmd=self._run_cmd, ) if result.score > 0: scored.append(result) self.view.info(f" {device_path}: score={result.score}, indicators={result.indicators}") else: self.view.info(f" {device_path}: score=0, no indicators") if not scored: self.view.error("No root filesystem candidates found.") return FlowResult(done=True, exit_code=1) scored = score_candidates(scored) self.state["scored"] = scored return FlowResult(done=False) def _step_select(self) -> FlowResult: """Display candidates via view, get user selection, store in state.""" scored = self.state.get("scored", []) self.view.display(scored) options = [f"{i+1}. {c.device} (score={c.score}/{len(FHS_INDICATORS)})" for i, c in enumerate(scored)] idx = self.view.select("Select candidate", options) if idx < 0 or idx >= len(scored): self.view.status("No selection made. Exiting.") return FlowResult(done=True, exit_code=0) selected = scored[idx] self.target_device = selected.device self.target_probe = next(p for d, p in self.state["candidates"] if d == selected.device) self.view.info(f"Selected: {selected.device} (score={selected.score})") return FlowResult(done=False) def _step_btrfs(self) -> FlowResult: """Handle btrfs subvolume detection, fstab reading, root subvol auto-detection.""" if not is_btrfs(self.target_probe): self.target_subvol = None return FlowResult(done=False) self.view.status("Handling btrfs subvolume detection...") top_mount = self.mount_base / ".btrfs_top" top_mount.mkdir(parents=True, exist_ok=True) result = self._run_cmd([ "mount", "-o", "ro,subvol=/", self.target_device, str(top_mount) ]) if result.returncode != 0: self.view.error(f"Failed to mount btrfs top-level: {result.stderr.strip()}") try: top_mount.rmdir() except OSError: pass self.target_subvol = None return FlowResult(done=False) subvolumes = btrfs_list_subvolumes(str(top_mount), run_cmd=self._run_cmd) subvolumes = btrfs_exclude_backup_subvolumes(subvolumes) if subvolumes: self.view.display(subvolumes) fstab_content = btrfs_read_fstab( self.target_device, self.mount_base, run_cmd=self._run_cmd ) if not fstab_content: self.view.warn("Could not find fstab on btrfs partition.") self.target_subvol = btrfs_fallback_detect_subvolumes( subvolumes, self.target_device, self.mount_base, run_cmd=self._run_cmd, ) if self.target_subvol: self.view.info(f"Fallback detected root subvolume: {self.target_subvol}") else: self.target_subvol = btrfs_detect_root_subvol(fstab_content) if self.target_subvol: self.view.info(f"Detected root subvolume from fstab: {self.target_subvol}") self._run_cmd(["umount", str(top_mount)]) try: top_mount.rmdir() except OSError: pass return FlowResult(done=False) def _step_fstab(self) -> FlowResult: """Parse fstab, filter, sort topologically, generate mount plan.""" self.view.status("Parsing fstab from target partition...") scored = self.state.get("scored", []) selected = next(s for s in scored if s.device == self.target_device) fstab_content = selected.fstab_content if fstab_content is None: self.view.warn("No fstab found on target partition.") fstab_entries: List[FstabEntry] = [] else: fstab_entries = read_fstab_from_content(fstab_content) self.view.info(f"Parsed {len(fstab_entries)} fstab entries") filtered = filter_fstab_entries(fstab_entries) sorted_entries = topological_sort(filtered) self.mount_plan = generate_mount_plan( self.target_device, self.target_subvol, sorted_entries, ) return FlowResult(done=False) def _step_plan(self) -> FlowResult: """Display mount plan via view, confirm with user.""" self.view.display(self.mount_plan) if not self.view.confirm("Proceed with mount plan?"): self.view.status("Mount plan declined. Exiting.") return FlowResult(done=True, exit_code=0) return FlowResult(done=False) def _step_replace_missing(self) -> FlowResult: """Detect missing fstab entries and offer interactive replacements.""" # Build device map and find root disk self.device_map = build_device_map(self.devices) if self.target_device: self.root_disk = self.device_map.get(self.target_device) missing = detect_missing_entries(self.mount_plan) if not missing: self.view.status("All fstab entries resolved.") return FlowResult(done=False) self.view.status(f"Found {len(missing)} missing fstab entry(ies).") for entry in missing: if entry.mount_point == "/": self.view.error( "Root (/) device cannot be resolved. " "Please fix /etc/fstab on the target partition and re-run." ) self.view.status("Aborting — root is unrecoverable interactively.") return FlowResult(done=True, exit_code=1) candidates = find_replacement_candidates( entry, self.devices, self.device_map, self.root_disk, ) choice = self.view.display_missing(entry, candidates) if choice == -1: # Quit self.view.status("No selection made. Exiting.") return FlowResult(done=True, exit_code=0) if choice == 0: # Skip self.view.warn(f"Skipping missing entry: {entry.mount_point}") continue # User selected a candidate (1-indexed) idx = choice - 1 if 0 <= idx < len(candidates): selected = candidates[idx] self.mount_plan = [ e if e.mount_point != entry.mount_point else MountPlanEntry( device=selected.device.path, mount_point=e.mount_point, fstype=e.fstype, options=e.options, subvol=e.subvol, ) for e in self.mount_plan ] self.view.info( f"Replaced {entry.mount_point}: {entry.mount_plan_entry.device} " f"-> {selected.device.path}" ) return FlowResult(done=False) def _step_mount(self) -> FlowResult: """Execute mount plan, handle directory creation prompts, report results.""" self.view.status("Executing mount plan...") mounted, failures = execute_mount_plan( self.mount_plan, str(self.mount_base), run_cmd=self._run_cmd, prompt_create=lambda p: self.view.confirm(f"Create directory {p}?"), prompt_parent_create=lambda p: self.view.confirm(f"Create parent directory {p}?"), ) self.mounted_paths.extend(mounted) if failures: self.view.error("Mount failures:") for f in failures: self.view.error(f" {f}") self._step_cleanup() return FlowResult(done=True, exit_code=1) self.view.info(f"All {len(mounted)} mounts successful.") return FlowResult(done=False) def _step_bind(self) -> FlowResult: """Set up bind mounts, report results.""" self.view.status("Setting up bind mounts...") bind_results = setup_bind_mounts(str(self.mount_base), run_cmd=self._run_cmd) for target, success in bind_results: if success: self.mounted_paths.append(target) self.view.info(f" {target}") else: self.view.error(f" {target}") return FlowResult(done=False) def _step_chroot(self) -> FlowResult: """Spawn chroot subprocess, poll for completion, return exit code.""" self.view.status("Entering chroot environment...") # Guide user to the terminal before launching self.view.show_chroot_complete(0) def handler(signum, frame) -> None: sig_name = signal.Signals(signum).name self.view.warn(f"Signal {sig_name} received, cleaning up...") self._run_cmd(["kill", "-TERM", str(proc.pid)]) if proc.poll() is None else None self._step_cleanup() sys.exit(1) signal.signal(signal.SIGINT, handler) signal.signal(signal.SIGTERM, handler) env = setup_chroot_env() proc = subprocess.Popen(["chroot", str(self.mount_base)], env=env) self.view.status("Chroot session launched — check your terminal.") exit_code = proc.wait() return FlowResult(done=False, exit_code=exit_code) def _step_cleanup(self) -> FlowResult: """Unmount in reverse, deactivate LVM, close LUKS, report results. Order matters: LUKS contains LVM which contains mounted filesystems. We must unmount first, then deactivate LVM (releases LVs), then close LUKS (releases the container). """ self.view.status("Cleaning up...") if self.mounted_paths: failed = cleanup_mounts(self.mounted_paths, run_cmd=self._run_cmd) if failed: messages = report_stuck_mounts(failed) for msg in messages: self.view.warn(msg) else: self.view.info("All mounts cleaned up successfully") self.deactivate_lvm() self.close_luks_devices() return FlowResult(done=True) def close_luks_devices(self) -> None: """Close LUKS devices opened by the tool, in reverse order.""" if not self._luks_unlocked: return for device, mapper_name in reversed(self._luks_unlocked): result = self._run_cmd(["cryptsetup", "close", mapper_name]) if result.returncode != 0: self.view.warn(f"Failed to close LUKS: {mapper_name}") else: self.view.info(f"Closed LUKS: {mapper_name}") def deactivate_lvm(self) -> None: """Deactivate LVM volume groups activated by the tool.""" if not self._vg_activated: return result = self._run_cmd(["vgchange", "-an"]) if result.returncode == 0: self.view.info("All volume groups deactivated") else: self.view.warn(f"Failed to deactivate volume groups: {result.stderr.strip()}") # ============================================================ # SECTION 7: ConsoleView # ============================================================ class ConsoleView: """Console implementation of ChrootView protocol. Delegates to print()/input() for all UI operations. """ def status(self, msg: str) -> None: self._print_with_marker("[*]", msg) def info(self, msg: str) -> None: self._print_with_marker("[ok]", msg) def error(self, msg: str) -> None: self._print_with_marker("[fail]", msg) def warn(self, msg: str) -> None: self._print_with_marker("[warn]", msg) def prompt(self, msg: str) -> str: try: return input(msg).strip() except EOFError: return "" def confirm(self, msg: str) -> bool: while True: try: choice = input(f"\n{msg} [Y/n]: ").strip().lower() except EOFError: return False if choice in ('y', 'yes', ''): return True if choice in ('n', 'no'): return False self._print_with_marker("", " Please enter y or n.") def select(self, msg: str, options: List[str]) -> int: while True: try: choice = input(f"\n{msg}\n" + "\n".join(f" {i+1}. {o}" for i, o in enumerate(options)) + f"\n [1-{len(options)}] (Enter=1, q=quit): ").strip() except EOFError: return -1 if choice.lower() in ('q', 'quit'): return -1 if not choice: return 0 try: idx = int(choice) - 1 if 0 <= idx < len(options): return idx except ValueError: pass self._print_with_marker("", f" Invalid. Enter 1-{len(options)} or q to quit.") def display(self, data: Any) -> None: if isinstance(data, list): if data and isinstance(data[0], InspectionResult): self._display_inspection_results(data) elif data and isinstance(data[0], SubvolumeInfo): self._display_subvolume_info(data) elif data and isinstance(data[0], MountPlanEntry): self._display_mount_plan(data) else: self._print_with_marker("", str(data)) def _print_with_marker(self, marker: str, msg: str) -> None: if marker: print(f" {marker} {msg}") else: print(f" {msg}") def _display_inspection_results(self, candidates: List[InspectionResult]) -> None: print("\n=== Root Filesystem Candidates ===\n") for i, candidate in enumerate(candidates, 1): print(f" {i}. {candidate.device}") print(f" Score: {candidate.score}/{len(FHS_INDICATORS)}") print(f" Indicators: {', '.join(candidate.indicators)}") if candidate.fstype: print(f" Filesystem: {candidate.fstype}") print() def _display_subvolume_info(self, subvolumes: List[SubvolumeInfo]) -> None: print("\n=== Btrfs Subvolumes ===\n") for sv in subvolumes: print(f" ID {sv.id}: {sv.name} ({format_size(sv.size)})") print() def _display_mount_plan(self, plan: List[MountPlanEntry]) -> None: print("\n=== Mount Plan ===\n") for i, entry in enumerate(plan, 1): target = f"/tmp/chroot_mnt{entry.mount_point}" print(f" {i}. {entry.device} -> {target}") print(f" Type: {entry.fstype}") if entry.subvol: print(f" Subvolume: {entry.subvol}") print() def display_missing(self, missing: MissingEntry, candidates: List[Ranking]) -> int: """Display a missing entry and ranked candidates. Returns user choice.""" dev_hint = missing.mount_plan_entry.device print(f"\n Missing: {missing.mount_point} (device: {dev_hint})") if dev_hint.startswith("UUID="): print(f" Expected fstype: {missing.expected_fstype}") else: print(f" Expected fstype: {missing.expected_fstype}") print(" Note: device paths are order-dependent. " "fstab should use UUID= for stability.") print(" The target fstab will need editing after recovery.") if not candidates: print("\n No candidate partitions found.") return 0 # skip print("\n Candidates:") for i, c in enumerate(candidates, 1): parts = [c.device.path, c.device.size, c.device.fstype or "unknown"] if c.device.label: parts.append(f"(label: {c.device.label})") parts.append(f"score: {c.score}") print(f" {i}. {' '.join(parts)}") print(f"\n [1-{len(candidates)}] to select, 0=skip, q=quit") while True: try: choice = input(" Select replacement: ").strip() except EOFError: return -1 if choice.lower() in ('q', 'quit'): return -1 if not choice: continue if choice == '0': return 0 try: idx = int(choice) - 1 if 0 <= idx < len(candidates): return idx + 1 except ValueError: pass print(f" Invalid. Enter 1-{len(candidates)}, 0 to skip, or q to quit.") def confirm_dir_create(self, path: str) -> bool: """Confirm creation of a parent directory.""" return self.confirm(f"Create directory {path}?") def show_chroot_complete(self, exit_code: int) -> None: """Inform user that chroot session is launching — guide to terminal.""" print("\n[*] Chroot session launching...") print("[*] Switch to the terminal window where you started this tool.") print("[*] Exit the shell inside chroot when done to return here.") def format_size(size: int) -> str: """Format bytes to human-readable string.""" for unit in ["B", "KB", "MB", "GB", "TB"]: if size < 1024: return f"{size:.1f} {unit}" size /= 1024 return f"{size:.1f} PB" # ============================================================ # SECTION 8: TkView # ============================================================ class TkView: """Tkinter implementation of ChrootView protocol. Imports tkinter only when instantiated (never at module level). """ def __init__(self): import tkinter as tk from tkinter import messagebox, simpledialog, ttk self.root = tk.Tk() self.root.title("Chroot Setup Tool") self.root.geometry("800x600") # Status panel (top) self.status_frame = tk.Frame(self.root, bg="#f0f0f0") self.status_frame.pack(fill="x", padx=5, pady=5) self.status_var = tk.StringVar(value="Ready") self.status_label = tk.Label( self.status_frame, textvariable=self.status_var, anchor="w", bg="#f0f0f0", padx=5, pady=2, ) self.status_label.pack(fill="x") # Content area (center, scrollable) self.content_frame = tk.Frame(self.root) self.content_frame.pack(fill="both", expand=True, padx=5, pady=5) self.tree = ttk.Treeview(self.content_frame) self.tree_scroll = tk.Scrollbar(self.content_frame, orient="vertical", command=self.tree.yview) self.tree.configure(yscrollcommand=self.tree_scroll.set) self.tree.pack(side="left", fill="both", expand=True) self.tree_scroll.pack(side="right", fill="y") # Navigation bar (bottom) self.nav_frame = tk.Frame(self.root) self.nav_frame.pack(fill="x", padx=5, pady=5) def status(self, msg: str) -> None: self.status_var.set(msg) self.root.update() def info(self, msg: str) -> None: self.status_var.set(f"[ok] {msg}") self.root.update() def error(self, msg: str) -> None: self.status_var.set(f"[fail] {msg}") self.status_label.config(fg="red") self.root.update() def warn(self, msg: str) -> None: self.status_var.set(f"[warn] {msg}") self.root.update() def prompt(self, msg: str) -> str: from tkinter import simpledialog return simpledialog.askstring("Input", msg, show="*") or "" def confirm(self, msg: str) -> bool: from tkinter import messagebox return messagebox.askyesno("Confirm", msg) def select(self, msg: str, options: List[str]) -> int: """Show a list of candidates and return the selected index (0-based).""" import tkinter as tk from tkinter import ttk class _SelectDialog(tk.Toplevel): def __init__(self, parent, title, options): super().__init__(parent) self._choices = options self._result = -1 self.title(title) self.geometry("600x350") self.transient(parent) self.grab_set() ttk.Label(self, text="Select a candidate:").pack(pady=8) # Listbox with details list_frame = ttk.Frame(self) list_frame.pack(fill="both", expand=True, padx=15, pady=5) self._listbox = tk.Listbox(list_frame, selectmode="single", font=("Monospace", 10), height=10) scrollbar = ttk.Scrollbar(list_frame, orient="vertical", command=self._listbox.yview) self._listbox.configure(yscrollcommand=scrollbar.set) self._listbox.pack(side="left", fill="both", expand=True) scrollbar.pack(side="right", fill="y") for opt in self._choices: self._listbox.insert("end", opt) self._listbox.bind("<>", self._on_select) # Buttons btn_frame = ttk.Frame(self) btn_frame.pack(pady=10) self._ok_btn = ttk.Button(btn_frame, text="OK", command=self._on_ok, state="disabled") self._ok_btn.pack(side="left", padx=10) ttk.Button(btn_frame, text="Cancel", command=self.destroy).pack(side="left", padx=10) self.protocol("WM_DELETE_WINDOW", self.destroy) def _on_select(self, event=None): sel = self._listbox.curselection() self._ok_btn.configure(state="normal" if sel else "disabled") def _on_ok(self): sel = self._listbox.curselection() if sel: self._result = sel[0] self.destroy() if not options: return -1 dlg = _SelectDialog(self.root, "Select", options) self.root.wait_window(dlg) return dlg._result def display(self, data: Any) -> None: self.tree.delete(*self.tree.get_children()) self.tree["show"] = "headings" if isinstance(data, list) and data: if isinstance(data[0], InspectionResult): self.tree["columns"] = ("device", "score", "fstype", "indicators") self.tree.heading("device", text="Device") self.tree.column("device", width=200, minwidth=100) self.tree.heading("score", text="Score") self.tree.column("score", width=80, minwidth=60) self.tree.heading("fstype", text="Filesystem") self.tree.column("fstype", width=80, minwidth=60) self.tree.heading("indicators", text="Indicators") self.tree.column("indicators", width=300, minwidth=150) for item in data: self.tree.insert("", "end", values=( item.device, f"{item.score}/{len(FHS_INDICATORS)}", item.fstype, ", ".join(item.indicators), )) elif isinstance(data[0], SubvolumeInfo): self.tree["columns"] = ("id", "name", "size") self.tree.heading("id", text="ID") self.tree.column("id", width=60, minwidth=40) self.tree.heading("name", text="Name") self.tree.column("name", width=250, minwidth=100) self.tree.heading("size", text="Size") self.tree.column("size", width=120, minwidth=80) for item in data: self.tree.insert("", "end", values=(item.id, item.name, format_size(item.size))) elif isinstance(data[0], MountPlanEntry): self.tree["columns"] = ("device", "mount_point", "fstype", "subvol") self.tree.heading("device", text="Device") self.tree.column("device", width=200, minwidth=100) self.tree.heading("mount_point", text="Mount Point") self.tree.column("mount_point", width=200, minwidth=100) self.tree.heading("fstype", text="Type") self.tree.column("fstype", width=80, minwidth=60) self.tree.heading("subvol", text="Subvolume") self.tree.column("subvol", width=200, minwidth=100) for item in data: self.tree.insert("", "end", values=( item.device, item.mount_point, item.fstype, item.subvol or "", )) self.root.update() def display_missing(self, missing: MissingEntry, candidates: List[Ranking]) -> int: """Show missing entry details and ranked candidates as a list dialog. Returns: 1-based candidate index if selected, 0 for skip, -1 for quit. """ import tkinter as tk from tkinter import ttk class _ReplaceDialog(tk.Toplevel): def __init__(self, parent, missing, candidates): super().__init__(parent) self._result = -1 self.title(f"Missing Entry: {missing.mount_point}") self.geometry("750x500") self.transient(parent) self.grab_set() # Info frame info_frame = ttk.Frame(self) info_frame.pack(fill="x", padx=15, pady=8) ttk.Label(info_frame, text=f"Missing: {missing.mount_point}", font=("", 12, "bold")).pack(anchor="w") ttk.Label(info_frame, text=f"Expected fstype: {missing.expected_fstype}").pack(anchor="w") dev = missing.mount_plan_entry.device if dev.startswith("UUID="): ttk.Label(info_frame, text=f"Device: {dev} (UUID)").pack(anchor="w") else: ttk.Label(info_frame, text=f"Device: {dev} (path — fstab needs editing)").pack(anchor="w") # Candidates list list_frame = ttk.Frame(self) list_frame.pack(fill="both", expand=True, padx=15, pady=8) ttk.Label(list_frame, text="Candidates:").pack(anchor="w", pady=(0, 4)) self._listbox = tk.Listbox(list_frame, selectmode="single", height=10, font=("Monospace", 10)) scrollbar = ttk.Scrollbar(list_frame, orient="vertical", command=self._listbox.yview) self._listbox.configure(yscrollcommand=scrollbar.set) self._listbox.pack(side="left", fill="both", expand=True) scrollbar.pack(side="right", fill="y") for i, c in enumerate(candidates, 1): parts = [c.device.path, c.device.size, c.device.fstype or "unknown"] if c.device.label: parts.append(f"label={c.device.label}") parts.append(f"score={c.score}") self._listbox.insert("end", f"{i}. {' '.join(parts)}") if candidates: self._listbox.bind("<>", lambda e: self._on_select()) # Buttons btn_frame = ttk.Frame(self) btn_frame.pack(fill="x", padx=10, pady=5) ttk.Button(btn_frame, text="Select", command=self._on_select).pack(side="left", padx=5) ttk.Button(btn_frame, text="Skip", command=self._on_skip).pack(side="left", padx=5) ttk.Button(btn_frame, text="Quit", command=self._on_quit).pack(side="right", padx=5) self.protocol("WM_DELETE_WINDOW", self._on_quit) self.focus_set() def _on_select(self): sel = self._listbox.curselection() if sel: self._result = sel[0] + 1 # 1-based self.destroy() def _on_skip(self): self._result = 0 self.destroy() def _on_quit(self): self._result = -1 self.destroy() if not candidates: return 0 # skip when no candidates dlg = _ReplaceDialog(self.root, missing, candidates) self.root.wait_window(dlg) return dlg._result def confirm_dir_create(self, path: str) -> bool: """Stub: Tkinter not updated for replacement flow.""" from tkinter import messagebox return messagebox.askyesno("Create Directory", f"Create directory {path}?") def show_chroot_complete(self, exit_code: int) -> None: """Show dialog guiding user to the terminal when chroot launches.""" from tkinter import messagebox messagebox.showinfo( "Chroot Launching", "Chroot session is launching.\n\n" "Switch to the terminal window where you started this tool.\n" "Exit the shell inside chroot when done to return here.", ) def run(self) -> int: """Start the Tkinter main loop.""" self.root.mainloop() return 0 def destroy(self) -> None: """Destroy the Tkinter window.""" if self.root: self.root.destroy() # ============================================================ # SECTION 9: Entry Point # ============================================================ # --- Legacy ChrootTool for backward compatibility --- class ChrootTool: """Legacy wrapper for backward compatibility. New code should use ChrootFlow(ConsoleView()) instead. This class is kept so existing tests continue to work. """ def __init__(self, run_cmd=None, log_file=None): self._run_cmd = run_cmd or _run_cmd self._log_file = log_file self.logger: Optional[logging.Logger] = None self.mounted_paths: List[str] = [] self.mount_base = MOUNT_BASE self.target_device: Optional[str] = None self.target_probe: Optional[ProbeResult] = None self.target_subvol: Optional[str] = None self.mount_plan: List[MountPlanEntry] = [] # LUKS/LVM state tracking self.devices: List[BlockDevice] = [] self._luks_unlocked: List[Tuple[str, str]] = [] self._luks_denied: Set[str] = set() self._luks_preexisting: Set[str] = set() self._vg_activated: List[str] = [] self._vg_denied: Set[str] = set() self._vg_preexisting: Set[str] = set() self._vg_discovered_after_unlock: Set[str] = set() def setup_logging(self) -> None: self.logger = setup_logging(self._log_file) self.logger.info("chroot-tool starting") self.logger.info("Mount base: %s", self.mount_base) def check_privileges(self) -> None: if os.geteuid() != 0: raise PreconditionError( "This tool requires root privileges.\n" "Run with: sudo python3 chroot-tool.py" ) def check_binaries(self) -> None: required = [ "lsblk", "blkid", "mount", "umount", "findmnt", "chroot", "btrfs", "cryptsetup", "vgchange", ] missing = [b for b in required if not shutil.which(b)] if missing: raise PreconditionError( f"Missing required binaries: {', '.join(missing)}\n" f"Install them with: sudo dnf install cryptsetup lvm2" ) def _handle_btrfs(self) -> None: """Handle btrfs subvolume detection and fstab reading.""" top_mount = self.mount_base / ".btrfs_top" top_mount.mkdir(parents=True, exist_ok=True) self.logger.info("Mounting btrfs top-level at %s", top_mount) result = self._run_cmd([ "mount", "-o", "ro,subvol=/", self.target_device, str(top_mount) ]) if result.returncode != 0: print(f"[fail] Failed to mount btrfs top-level: {result.stderr.strip()}") self.logger.error("Btrfs top-level mount failed: %s", result.stderr.strip()) try: top_mount.rmdir() except OSError: pass return subvolumes = btrfs_list_subvolumes(str(top_mount), run_cmd=self._run_cmd) subvolumes = btrfs_exclude_backup_subvolumes(subvolumes) if subvolumes: self._display_btrfs_subvolumes(subvolumes) fstab_content = btrfs_read_fstab( self.target_device, self.mount_base, run_cmd=self._run_cmd ) if not fstab_content: print("[warn] Could not find fstab on btrfs partition.") self.logger.warning("Could not find fstab on btrfs partition") self.target_subvol = btrfs_fallback_detect_subvolumes( subvolumes, self.target_device, self.mount_base, run_cmd=self._run_cmd, ) if self.target_subvol: print(f"[ok] Fallback detected root subvolume: {self.target_subvol}") else: self.target_subvol = btrfs_detect_root_subvol(fstab_content) if self.target_subvol: print(f"[ok] Detected root subvolume from fstab: {self.target_subvol}") self._run_cmd(["umount", str(top_mount)]) try: top_mount.rmdir() except OSError: pass @staticmethod def _display_luks_devices(devices: List[Tuple[str, str, str]]) -> None: for device, uuid, size in devices: print(f" LUKS: {device} Size: {size} UUID: {uuid}") @staticmethod def _display_inactive_vgs(vgs: List[str]) -> None: for vg in vgs: print(f" VG: {vg}") @staticmethod def _prompt_luks_unlock(device: str, size: str, uuid: str) -> bool: while True: try: choice = input( f"\n Unlock {device} (size={size}, uuid={uuid})? [Y/n]: " ).strip().lower() except EOFError: return False if choice in ('y', 'yes', ''): return True if choice in ('n', 'no'): return False print(" Please enter y or n.") @staticmethod def _prompt_vg_activate(vg_name: str) -> bool: while True: try: choice = input( f"\n Activate volume group {vg_name}? [Y/n]: " ).strip().lower() except EOFError: return False if choice in ('y', 'yes', ''): return True if choice in ('n', 'no'): return False print(" Please enter y or n.") @staticmethod def _display_candidates(candidates: List[InspectionResult]) -> None: print("\n=== Root Filesystem Candidates ===\n") for i, candidate in enumerate(candidates, 1): print(f" {i}. {candidate.device}") print(f" Score: {candidate.score}/6") print(f" Indicators: {', '.join(candidate.indicators)}") if candidate.fstype: print(f" Filesystem: {candidate.fstype}") print() @staticmethod def _display_btrfs_subvolumes(subvolumes: List[SubvolumeInfo]) -> None: print("\n=== Btrfs Subvolumes ===\n") for sv in subvolumes: print(f" ID {sv.id}: {sv.name} ({format_size(sv.size)})") print() @staticmethod def _prompt_select_candidate(candidates: List[InspectionResult]) -> Optional[InspectionResult]: while True: try: choice = input( f"\nSelect candidate [1-{len(candidates)}] " f"(Enter=1, q=quit): " ).strip() except EOFError: return None if choice.lower() in ('q', 'quit'): return None if not choice: return candidates[0] try: idx = int(choice) - 1 if 0 <= idx < len(candidates): return candidates[idx] except ValueError: pass print(f" Invalid. Enter 1-{len(candidates)} or q to quit.") @staticmethod def _display_mount_plan(plan: List[MountPlanEntry]) -> None: print("\n=== Mount Plan ===\n") for i, entry in enumerate(plan, 1): target = f"/tmp/chroot_mnt{entry.mount_point}" print(f" {i}. {entry.device} -> {target}") print(f" Type: {entry.fstype}") if entry.subvol: print(f" Subvolume: {entry.subvol}") print() @staticmethod def _prompt_confirm_mount_plan(plan: List[MountPlanEntry]) -> bool: while True: try: choice = input("\nProceed with mount plan? [Y/n]: ").strip().lower() except EOFError: return False if choice in ('y', 'yes', ''): return True if choice in ('n', 'no'): return False print(" Please enter y or n.") @staticmethod def _prompt_create_mount_point(path: str) -> bool: while True: try: choice = input(f"\nCreate directory {path}? [Y/n]: ").strip().lower() except EOFError: return False if choice in ('y', 'yes', ''): return True if choice in ('n', 'no'): return False print(" Please enter y or n.") def _replace_missing_entries(self) -> None: """Detect missing fstab entries and offer interactive replacements.""" if not self.logger: self.logger = logging.getLogger("chroot-tool") self.device_map = build_device_map(self.devices) if self.target_device: self.root_disk = self.device_map.get(self.target_device) missing = detect_missing_entries(self.mount_plan, logger=self.logger) if not missing: print("[*] All fstab entries resolved.") return print(f"\n[warn] Found {len(missing)} missing fstab entry(ies).") for entry in missing: if entry.mount_point == "/": print("\n[fail] Root (/) device cannot be resolved.") print(" Please fix /etc/fstab on the target partition and re-run.") return candidates = find_replacement_candidates( entry, self.devices, self.device_map, self.root_disk, logger=self.logger, ) if not candidates: print(f"\n[warn] No candidates for {entry.mount_point}. Skipping.") continue # Display candidates print(f"\n Missing: {entry.mount_point} (device: {entry.mount_plan_entry.device})") print(f" Expected fstype: {entry.expected_fstype}") if not entry.mount_plan_entry.device.startswith("UUID="): print(" Note: device paths are order-dependent. fstab should use UUID=. " "The target fstab will need editing after recovery.") print("\n Candidates:") for i, c in enumerate(candidates, 1): parts = [c.device.path, c.device.size, c.device.fstype or "unknown"] if c.device.label: parts.append(f"(label: {c.device.label})") parts.append(f"score: {c.score}") print(f" {i}. {' '.join(parts)}") # Prompt for selection while True: try: choice = input( f"\n [1-{len(candidates)}] to select, 0=skip, q=quit: " ).strip() except EOFError: print("\n[*] No selection made. Exiting.") return if choice.lower() in ('q', 'quit'): print("\n[*] No selection made. Exiting.") return if choice == '0': print(f" [warn] Skipping missing entry: {entry.mount_point}") break try: idx = int(choice) - 1 if 0 <= idx < len(candidates): selected = candidates[idx] self.mount_plan = [ e if e.mount_point != entry.mount_point else MountPlanEntry( device=selected.device.path, mount_point=e.mount_point, fstype=e.fstype, options=e.options, subvol=e.subvol, ) for e in self.mount_plan ] print(f" [ok] Replaced {entry.mount_point}: " f"{entry.mount_plan_entry.device} -> {selected.device.path}") break except ValueError: pass print(f" Invalid. Enter 1-{len(candidates)}, 0 to skip, or q to quit.") def _rescan_after_luks_lvm(self) -> None: """Re-scan block devices after LUKS unlock and LVM activation.""" self.logger.info("Re-scanning block devices after LUKS/LVM changes") self.devices = scan_block_devices(run_cmd=self._run_cmd) def _run_luks_lvm_discovery(self) -> None: """Loop-based LUKS/LVM discovery with user confirmation.""" self.devices = scan_block_devices(run_cmd=self._run_cmd) while True: locked = detect_locked_luks(self.devices, run_cmd=self._run_cmd) locked = [(d, u, s) for d, u, s in locked if d not in self._luks_denied] inactive_vgs = detect_inactive_vgs( self._vg_preexisting, vg_discovered_after_unlock=self._vg_discovered_after_unlock, run_cmd=self._run_cmd, ) inactive_vgs = [vg for vg in inactive_vgs if vg not in self._vg_denied] if not locked and not inactive_vgs: self.logger.info("LUKS/LVM discovery: stable (no new devices)") break any_unlocked = False if locked: print("\n[*] Detected locked LUKS devices:") self._display_luks_devices(locked) if inactive_vgs: print("\n[*] Detected inactive volume groups:") self._display_inactive_vgs(inactive_vgs) for device, uuid, size in locked: if not self._prompt_luks_unlock(device, size, uuid): self._luks_denied.add(device) self.logger.info("LUKS denied: %s", device) continue mapper_name = _generate_luks_mapper_name(device) if _luks_mapper_exists(mapper_name): print(f" [warn] Mapper '{mapper_name}' already exists, skipping.") continue print(f" [*] Unlocking {device}...") passphrase = prompt_luks_passphrase(device, mapper_name, run_cmd=self._run_cmd) if passphrase is None: print(f" [warn] Passphrase validation failed for {device}.") self._luks_denied.add(device) continue vgs_before_unlock = ( set(self._vg_discovered_after_unlock) | self._vg_preexisting ) if unlock_luks(device, mapper_name, run_cmd=self._run_cmd, passphrase=passphrase, logger=self.logger): self._luks_unlocked.append((device, mapper_name)) print(f" [ok] Unlocked {device} -> {mapper_name}") self.logger.info("Unlocked LUKS: %s -> %s", device, mapper_name) any_unlocked = True result = self._run_cmd(["vgs", "--noheadings", "-o", "vg_name"]) if result.returncode == 0: for name in result.stdout.split(): name = name.strip() if name: self._vg_discovered_after_unlock.add(name) if name not in vgs_before_unlock: self._vg_activated.append(name) self.logger.info("Auto-activated VG (side-effect): %s", name) else: print(f" [fail] Failed to unlock {device}.") self._luks_denied.add(device) for vg in inactive_vgs: if not self._prompt_vg_activate(vg): self._vg_denied.add(vg) self.logger.info("VG denied: %s", vg) continue print(f" [*] Activating volume group {vg}...") if activate_vg(vg, run_cmd=self._run_cmd): self._vg_activated.append(vg) print(f" [ok] Activated volume group: {vg}") self.logger.info("Activated VG: %s", vg) else: print(f" [fail] Failed to activate volume group: {vg}") self._vg_denied.add(vg) if any_unlocked: self._rescan_after_luks_lvm() def run(self) -> int: """Execute the guided chroot setup flow.""" self.setup_logging() if self.logger: for handler in self.logger.handlers: if isinstance(handler, logging.FileHandler): print(f"Debug log: {handler.baseFilename}", file=sys.stderr) break self.check_privileges() self.logger.info("Privilege check passed") self.check_binaries() self.logger.info("Binary check passed") self._vg_preexisting = set() try: result = self._run_cmd(["vgs", "--noheadings", "-o", "vg_name"]) if result.returncode == 0: for name in result.stdout.split(): name = name.strip() if name: self._vg_preexisting.add(name) except Exception: pass self.logger.info("Pre-existing VGs: %s", self._vg_preexisting) self._run_luks_lvm_discovery() self._rescan_after_luks_lvm() print("\n[*] Scanning block devices...") self.logger.info("Scanning block devices") devices = scan_block_devices(run_cmd=self._run_cmd) self.logger.info("Found %d block devices", len(devices)) self._rescan_after_luks_lvm() host_mounts = get_host_mounts() self.logger.info("Host mounts: %s", host_mounts) candidates: List[Tuple[str, ProbeResult]] = [] skipped: List[str] = [] for device in devices: device_path = device.path probe = probe_device(device_path, run_cmd=self._run_cmd) if is_mounted_on_host(device_path, host_mounts, probe, run_cmd=self._run_cmd): skipped.append(device_path) continue candidates.append((device_path, probe)) if skipped: self.logger.info("Skipped host-mounted: %s", skipped) if not candidates: print("\n[fail] No non-host block devices found.") print(" The tool needs a non-mounted disk to inspect.") return 1 self.logger.info("Candidate devices: %s", [d for d, _ in candidates]) print("[*] Inspecting candidates (read-only)...") self.logger.info("Inspecting candidates") scored: List[InspectionResult] = [] for device_path, probe in candidates: result = inspect_partition( device_path, self.mount_base, probe, run_cmd=self._run_cmd, logger=self.logger, ) if result.score > 0: scored.append(result) self.logger.info( " %s: score=%d, indicators=%s", device_path, result.score, result.indicators, ) else: self.logger.info(" %s: score=0, no indicators", device_path) if not scored: print("\n[fail] No root filesystem candidates found.") print(" No partition has the expected root filesystem structure.") return 1 scored = score_candidates(scored) self._display_candidates(scored) selected = self._prompt_select_candidate(scored) if selected is None: print("\n[*] No selection made. Exiting.") return 0 self.target_device = selected.device self.target_probe = next(p for d, p in candidates if d == selected.device) self.logger.info("Selected: %s (score=%d)", selected.device, selected.score) if is_btrfs(self.target_probe): self.logger.info("Target is btrfs") self._handle_btrfs() print("[*] Parsing fstab from target partition...") self.logger.info("Parsing fstab") fstab_content = selected.fstab_content if fstab_content is None: print("[warn] No fstab found on target partition.") self.logger.warning("No fstab found on target") fstab_entries: List[FstabEntry] = [] else: fstab_entries = read_fstab_from_content(fstab_content) self.logger.info("Parsed %d fstab entries", len(fstab_entries)) filtered = filter_fstab_entries(fstab_entries) sorted_entries = topological_sort(filtered) self.mount_plan = generate_mount_plan( self.target_device, self.target_subvol, sorted_entries, ) self._display_mount_plan(self.mount_plan) if not self._prompt_confirm_mount_plan(self.mount_plan): print("\n[*] Mount plan declined. Exiting.") return 0 # Detect and replace missing fstab entries self._replace_missing_entries() print("[*] Executing mount plan...") self.logger.info("Executing mount plan") mounted, failures = execute_mount_plan( self.mount_plan, str(self.mount_base), run_cmd=self._run_cmd, prompt_create=self._prompt_create_mount_point, prompt_parent_create=self._prompt_create_mount_point, ) self.mounted_paths.extend(mounted) if failures: print("\n[fail] Mount failures:") for f in failures: print(f" {f}") self.logger.error("Mount failures: %s", failures) self.cleanup() return 1 print(f"\n[ok] All {len(mounted)} mounts successful.") print("[*] Setting up bind mounts...") self.logger.info("Setting up bind mounts") bind_results = setup_bind_mounts(str(self.mount_base), run_cmd=self._run_cmd) for target, success in bind_results: if success: self.mounted_paths.append(target) print(f" [ok] {target}") else: print(f" [fail] {target}") self.logger.warning("Bind mount failed: %s", target) print("\n[*] Entering chroot environment...") print(" Exit the shell to return and unmount.") self.logger.info("Entering chroot") setup_signal_handlers(self.mounted_paths, self.logger) exit_code = enter_chroot(str(self.mount_base)) print("\n[*] Exiting chroot. Cleaning up...") self.logger.info("Exiting chroot, cleaning up") self.cleanup() return exit_code def cleanup(self) -> None: """Clean up: unmount, deactivate LVM, close LUKS (correct order).""" if self.mounted_paths: self.logger.info("Cleaning up %d mounts", len(self.mounted_paths)) failed = cleanup_mounts(self.mounted_paths, run_cmd=self._run_cmd) if failed: for msg in report_stuck_mounts(failed): print(msg) self.logger.warning("Failed to unmount: %s", failed) else: self.logger.info("All mounts cleaned up successfully") self.deactivate_lvm() self.close_luks_devices() def close_luks_devices(self) -> None: """Close LUKS devices opened by the tool, in reverse order.""" if not self._luks_unlocked: return self.logger.info("Closing %d LUKS devices", len(self._luks_unlocked)) for device, mapper_name in reversed(self._luks_unlocked): self.logger.info("Closing LUKS: %s (%s)", device, mapper_name) result = self._run_cmd(["cryptsetup", "close", mapper_name]) if result.returncode != 0: print(f"[warn] Failed to close LUKS: {mapper_name}") self.logger.warning("Failed to close LUKS: %s", mapper_name) else: print(f" [ok] Closed LUKS: {mapper_name}") def deactivate_lvm(self) -> None: """Deactivate LVM volume groups activated by the tool.""" if not self._vg_activated: return self.logger.info("Deactivating %d volume groups", len(self._vg_activated)) result = self._run_cmd(["vgchange", "-an"]) if result.returncode == 0: print("[ok] All volume groups deactivated") self.logger.info("All volume groups deactivated") else: print(f"[warn] Failed to deactivate volume groups: {result.stderr.strip()}") self.logger.warning("Failed to deactivate volume groups: %s", result.stderr.strip()) def setup_signal_handlers( mounted_paths: List[str], logger: Optional[logging.Logger] = None, ) -> None: """Set up SIGINT/SIGTERM handlers to trigger cleanup.""" def handler(signum: int, frame) -> None: sig_name = signal.Signals(signum).name if logger: logger.info("Signal %s received, cleaning up...", sig_name) print(f"\n[*] Signal {sig_name} received, cleaning up...") failed = cleanup_mounts(mounted_paths) if failed: for msg in report_stuck_mounts(failed): print(msg) sys.exit(1) signal.signal(signal.SIGINT, handler) signal.signal(signal.SIGTERM, handler) def main() -> int: """Entry point: parse args, choose view, run flow.""" if "--help" in sys.argv or "-h" in sys.argv: print("Usage: python3 chroot_tool.py [--tk]") print() print("Guided chroot environment setup for system recovery.") print() print("Options:") print(" --tk Launch Tkinter GUI instead of console flow") print(" --help Show this help message") print() print("Required: root privileges (sudo)") print("Required binaries: lsblk, blkid, mount, umount, findmnt,") print(" chroot, btrfs, cryptsetup, vgchange") return 0 use_tk = "--tk" in sys.argv if use_tk: view = TkView() else: view = ConsoleView() flow = ChrootFlow(view) exit_code = flow.run() if use_tk and isinstance(view, TkView): view.destroy() return exit_code if __name__ == "__main__": sys.exit(main())