Repository navigation
Expand file tree
/
Copy pathsync
More file actions
executable file
·657 lines (597 loc) · 23 KB
/
Copy pathsync
File metadata and controls
executable file
·657 lines (597 loc) · 23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
#!/usr/bin/env python3
# pyright: strict
"""Preview and apply tracked rootfs configuration to the installed system."""
import argparse
import difflib
import gzip
import hashlib
import logging
import os
import pwd
import re
import shlex
import stat
import subprocess
import sys
import tempfile
import zlib
from dataclasses import dataclass, replace
from functools import cache
from pathlib import Path
from typing import ClassVar, override
logger = logging.getLogger("sync")
class ColoredFormatter(logging.Formatter):
COLORS: ClassVar[dict[int, str]] = {
logging.DEBUG: "\033[36m",
logging.INFO: "\033[34m",
logging.WARNING: "\033[33m",
logging.ERROR: "\033[31m",
logging.CRITICAL: "\033[1;31m",
}
def __init__(self, use_color: bool) -> None:
super().__init__("[%(name)s] [%(levelname)s] %(message)s")
self.use_color = use_color
@override
def formatMessage(self, record: logging.LogRecord) -> str:
message = super().formatMessage(record)
color = self.COLORS.get(record.levelno) if self.use_color else None
if color:
tag = f"[{record.levelname}]"
message = message.replace(tag, f"{color}{tag}\033[0m", 1)
return message
def configure_logging() -> None:
handler = logging.StreamHandler(sys.stderr)
color = (
sys.stderr.isatty()
and "NO_COLOR" not in os.environ
and os.environ.get("TERM") != "dumb"
)
handler.setFormatter(ColoredFormatter(use_color=color))
logger.handlers.clear()
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.propagate = False
@dataclass(frozen=True)
class FileEntry:
data: bytes
metadata: os.stat_result
@dataclass(frozen=True)
class SymlinkEntry:
data: str
metadata: os.stat_result
type PresentEntry = FileEntry | SymlinkEntry
type Entry = PresentEntry | None
type Change = tuple[Path, Entry, PresentEntry]
type MetadataVersion = tuple[int, int, int, int, int, int, int]
type EntryVersion = tuple[bytes | str, MetadataVersion] | None
class Arguments(argparse.Namespace):
dry_run: bool
apply: bool
yes: bool
user: str | None
def entry_version(entry: Entry) -> EntryVersion:
if entry is None:
return None
info = entry.metadata
return entry.data, (
info.st_dev,
info.st_ino,
info.st_mode,
info.st_uid,
info.st_gid,
info.st_mtime_ns,
info.st_ctime_ns,
)
def read_entry(path: Path) -> Entry:
try:
info = path.lstat()
except FileNotFoundError:
return None
if stat.S_ISLNK(info.st_mode):
return SymlinkEntry(os.readlink(path), info)
if stat.S_ISREG(info.st_mode):
return FileEntry(path.read_bytes(), info)
raise ValueError(f"Not a regular file or symlink: {path}")
def check_parents(path: Path) -> None:
for parent in path.parents:
if parent.is_symlink():
raise ValueError(f"Parent directory is a symlink: {parent}")
def render_diff(path: Path, before: Entry, after: PresentEntry) -> str:
if isinstance(after, SymlinkEntry):
old = (
repr(before.data) if isinstance(before, SymlinkEntry) else "(not a symlink)"
)
return f"{path}: {old} -> symlink {after.data!r}\n"
lines = difflib.unified_diff(
(before.data if isinstance(before, FileEntry) else b"")
.decode("utf-8", errors="backslashreplace")
.splitlines(keepends=True),
after.data.decode("utf-8", errors="backslashreplace").splitlines(keepends=True),
fromfile=f"{path} (installed)",
tofile=f"{path} (proposed)",
)
heading = f"\n{path}: {'new file' if before is None else 'modified'}\n"
return heading + "".join(
line if line.endswith("\n") else line + "\n\\ No newline at end of file\n"
for line in lines
)
def save_diffs(changes: list[Change], user: str | None) -> Path | None:
if not changes:
return None
# Keep the diff after exit, private to the user who will review it.
with tempfile.NamedTemporaryFile(
mode="w",
encoding="utf-8",
prefix="archlinux-sync-",
suffix=".diff",
delete=False,
) as output:
path = Path(output.name)
try:
output.writelines(render_diff(*change) for change in changes)
output.flush()
if os.geteuid() == 0 and user:
owner = pwd.getpwnam(user)
os.fchown(output.fileno(), owner.pw_uid, owner.pw_gid)
except BaseException:
path.unlink(missing_ok=True)
raise
logger.info("Diff written to %s — open it to review the planned changes", path)
return path
def apply_change(path: Path, before: Entry, after: PresentEntry) -> None:
check_parents(path)
path.parent.mkdir(parents=True, exist_ok=True, mode=0o755)
# Stage on the destination filesystem, then publish the complete file atomically.
with tempfile.TemporaryDirectory(
prefix=".archlinux-sync-", dir=path.parent
) as directory:
staged = Path(directory) / "file"
if isinstance(after, SymlinkEntry):
staged.symlink_to(after.data)
else:
staged.write_bytes(after.data)
if before is not None:
info = before.metadata
os.chown(staged, info.st_uid, info.st_gid)
staged.chmod(stat.S_IMODE(info.st_mode))
for name in os.listxattr(path):
os.setxattr(staged, name, os.getxattr(path, name))
else:
mode = 0o755 if after.metadata.st_mode & 0o111 else 0o644
if path == Path("/etc/sudoers") or path.parent == Path(
"/etc/sudoers.d"
):
mode = 0o440
staged.chmod(mode)
check_parents(path)
if entry_version(read_entry(path)) != entry_version(before):
raise ValueError(f"Destination changed during review: {path}")
os.replace(staged, path)
logger.info("Updated %s", path)
def git_paths(repo: Path, *arguments: str) -> list[Path]:
result = subprocess.run(
["git", "-c", f"safe.directory={repo}", *arguments, "--", "rootfs/"],
cwd=repo,
stdout=subprocess.PIPE,
check=True,
)
return [Path(os.fsdecode(item)) for item in result.stdout.split(b"\0") if item]
def audit_packages(repo: Path) -> dict[str, str]:
# Use the actual binary, bypassing the interactive local pacman wrapper.
query = subprocess.run(
["/usr/bin/pacman", "-Q"], capture_output=True, text=True, check=True
)
versions = dict(line.split(maxsplit=1) for line in query.stdout.splitlines())
query = subprocess.run(
["/usr/bin/pacman", "-Qqe"], capture_output=True, text=True, check=True
)
explicit = set(query.stdout.splitlines())
listed: set[str] = set()
for name in ("regular", "aur"):
for line in (repo / "packages" / name).read_text().splitlines():
listed.update(line.partition("#")[0].split())
# These are conditional hardware packages, not required on every machine.
conditional = set(
re.findall(
r"^\s*echo\s+([a-z0-9][a-z0-9@._+-]*)\s*(?:>>\s*(?:regular|aur)_packages_to_install)?\s*$",
(repo / "install").read_text(),
re.MULTILINE,
)
)
missing = listed - versions.keys()
extra = explicit - listed - conditional - {"yay"}
if missing:
logger.warning(
"Listed packages are not installed: %s", ", ".join(sorted(missing))
)
if extra:
logger.warning(
"Explicitly installed packages are not listed: %s", ", ".join(sorted(extra))
)
return versions
def decode_mtree(value: str) -> str:
# mtree quotes spaces and other special filename bytes with octal escapes.
return os.fsdecode(
re.sub(
rb"\\([0-7]{3})",
lambda match: bytes((int(match[1], 8),)),
os.fsencode(value),
)
)
def installer_subvolumes(repo: Path) -> tuple[set[str], dict[str, str]]:
"""Read literal create/mount commands, without executing the installer."""
created: set[str] = set()
mounts: dict[str, str] = {}
text = (repo / "install").read_text().replace("\\\n", "")
for line in text.splitlines():
if re.match(r"\s*btrfs subvolume create\s", line):
words = shlex.split(line, comments=True)
if len(words) != 4 or not words[3].startswith("/mnt/"):
raise ValueError("Unsupported installer subvolume creation command")
created.add(words[3].removeprefix("/mnt/"))
elif re.match(r"\s*mount\s", line) and "subvol=" in line:
words = shlex.split(line, comments=True)
options = words[words.index("-o") + 1].split(",")
subvolume = next(
(
opt.removeprefix("subvol=")
for opt in options
if opt.startswith("subvol=")
),
"",
)
if not subvolume or "$" in subvolume:
raise ValueError("Unsupported installer subvolume mount options")
target = words[-1]
if target != "/mnt" and not target.startswith("/mnt/"):
raise ValueError("Unsupported installer subvolume mount target")
mounts[target.removeprefix("/mnt") or "/"] = subvolume.lstrip("/")
if not created or set(mounts.values()) != created:
raise ValueError("Installer subvolume creation and mount declarations differ")
return created, mounts
@dataclass(frozen=True)
class Mount:
device: str
root: str
filesystem: str
def live_mounts() -> dict[str, Mount]:
mounts: dict[str, Mount] = {}
for line in Path("/proc/self/mountinfo").read_text().splitlines():
fields, separator, details = line.partition(" - ")
before, after = fields.split(), details.split()
if not separator or len(before) < 6 or len(after) < 3:
raise ValueError("Malformed mountinfo record")
mounts[decode_mtree(before[4])] = Mount(
before[2], decode_mtree(before[3]), after[0]
)
return mounts
def audit_subvolumes(repo: Path, user: str | None) -> None:
expected, targets = installer_subvolumes(repo)
mounted = live_mounts()
root = mounted.get("/")
if root is None or root.filesystem != "btrfs":
logger.warning("Btrfs layout differs: / is not mounted as Btrfs")
return
for target, subvolume in targets.items():
if "$user" in target or "${user}" in target:
if not user:
logger.warning("Cannot check Btrfs mount %s: use --user USER", target)
continue
target = target.replace("${user}", user).replace("$user", user)
if "$" in target:
raise ValueError(
f"Unsupported variable in installer mount target: {target}"
)
actual = mounted.get(target)
if actual is None:
logger.warning("Btrfs subvolume %s is not mounted at %s", subvolume, target)
elif actual != Mount(root.device, "/" + subvolume, "btrfs"):
logger.warning(
"Btrfs mount differs at %s: expected /%s on the root filesystem; live %s %s (device %s)",
target,
subvolume,
actual.filesystem,
actual.root,
actual.device,
)
# Listing all subvolumes requires privileges; mount checks above do not.
query = subprocess.run(
["btrfs", "subvolume", "list", "-a", "/"],
capture_output=True,
text=True,
env=os.environ | {"LC_ALL": "C"},
)
if query.returncode:
logger.warning(
"Cannot inventory Btrfs subvolumes: %s; mount checks completed, inventory unchecked (may require sudo)",
query.stderr.strip() or f"btrfs exited with status {query.returncode}",
)
return
actual_paths: set[str] = set()
for line in query.stdout.splitlines():
match = re.fullmatch(r"ID \d+ gen \d+ top level (\d+) path (.+)", line)
if match is None:
raise ValueError("Unrecognized btrfs subvolume list output")
# Nested snapshots and container subvolumes are not installer layout entries.
if match[1] == "5":
actual_paths.add(match[2].removeprefix("<FS_TREE>/"))
if missing := expected - actual_paths:
logger.warning(
"Installer Btrfs subvolumes are missing: %s", ", ".join(sorted(missing))
)
if extra := actual_paths - expected:
logger.warning(
"Top-level Btrfs subvolumes are not in the installer: %s",
", ".join(sorted(extra)),
)
def package_file_attributes(manifest: Path, relative: Path) -> dict[str, str]:
defaults: dict[str, str] = {}
with gzip.open(
manifest, "rt", encoding="utf-8", errors="surrogateescape"
) as stream:
text = stream.read().replace("\\\n", "")
for line in text.splitlines():
fields = line.split()
if not fields or fields[0].startswith("#"):
continue
attributes = dict(field.split("=", 1) for field in fields[1:] if "=" in field)
if fields[0] == "/set":
defaults.update(attributes)
elif fields[0] == "/unset":
if "all" in fields[1:]:
defaults.clear()
else:
for name in fields[1:]:
defaults.pop(name, None)
elif decode_mtree(fields[0]).removeprefix("./") == relative.as_posix():
return defaults | attributes
raise ValueError("file is absent from the package manifest")
def package_file_matches(attributes: dict[str, str], installed: PresentEntry) -> bool:
if attributes.get("type") == "link" and "link" in attributes:
return isinstance(installed, SymlinkEntry) and installed.data == decode_mtree(
attributes["link"]
)
if attributes.get("type") == "file" and "sha256digest" in attributes:
return (
isinstance(installed, FileEntry)
and hashlib.sha256(installed.data).hexdigest() == attributes["sha256digest"]
)
raise ValueError(
"package manifest has no comparable content checksum or symlink target"
)
@cache
def package_database() -> Path:
query = subprocess.run(
["/usr/bin/pacman-conf", "DBPath"], capture_output=True, text=True, check=True
)
return Path(query.stdout.strip()) / "local"
def package_default(
path: Path, versions: dict[str, str]
) -> tuple[str, dict[str, str]] | None:
owner = subprocess.run(
["/usr/bin/pacman", "-Qoq", "--", str(path)],
capture_output=True,
text=True,
env=os.environ | {"LC_ALL": "C"},
)
if owner.returncode == 1 and "No package owns" in owner.stderr:
return None
owner.check_returncode()
package = owner.stdout.strip()
if package not in versions:
raise ValueError(f"installed version of {package!r} is unavailable")
manifest = package_database() / f"{package}-{versions[package]}" / "mtree"
return package, package_file_attributes(manifest, path.relative_to("/"))
def audit_permissions(
path: Path, installed: FileEntry, versions: dict[str, str]
) -> None:
try:
packaged = package_default(path, versions)
if packaged is None:
return
package, attributes = packaged
if attributes.get("type") != "file" or "mode" not in attributes:
raise ValueError(
"package manifest has no regular-file permissions to compare"
)
expected = int(attributes["mode"], 8)
actual = stat.S_IMODE(installed.metadata.st_mode)
if actual != expected:
logger.warning(
"Permissions differ from package %s: %s (live %04o, packaged %04o); preserving live permissions",
package,
path,
actual,
expected,
)
except (
OSError,
ValueError,
EOFError,
zlib.error,
subprocess.CalledProcessError,
) as error:
logger.warning("Cannot verify package permissions for %s: %s", path, error)
def audit_removed_files(
repo: Path, tracked: set[Path], active: set[Path], versions: dict[str, str]
) -> None:
removed = set(
git_paths(
repo,
"log",
"--format=",
"--name-only",
"-z",
"--diff-filter=D",
"--no-renames",
"HEAD",
)
)
removed.update(
git_paths(
repo,
"diff",
"--cached",
"--name-only",
"-z",
"--diff-filter=D",
"--no-renames",
"HEAD",
)
)
removed.update(tracked - active)
for relative in sorted(removed - active):
destination = Path("/") / relative.relative_to("rootfs")
try:
installed = read_entry(destination)
if installed is None:
continue
packaged = package_default(destination, versions)
if packaged is None:
logger.warning(
"Removed from repository but still present and unowned: %s",
destination,
)
continue
package, attributes = packaged
if not package_file_matches(attributes, installed):
logger.warning(
"Removed from repository; live contents differ from package %s: %s",
package,
destination,
)
except (
OSError,
ValueError,
EOFError,
zlib.error,
subprocess.CalledProcessError,
) as error:
logger.warning("Cannot verify removed file %s: %s", destination, error)
def main() -> int:
configure_logging()
parser = argparse.ArgumentParser(description=__doc__)
mode = parser.add_mutually_exclusive_group()
mode.add_argument(
"--dry-run", action="store_true", help="preview changes (default)"
)
mode.add_argument(
"--apply", action="store_true", help="apply changes; requires root"
)
parser.add_argument(
"--yes", action="store_true", help="skip confirmation with --apply"
)
parser.add_argument(
"--user", help="username for placeholders; defaults to SUDO_USER or your login"
)
args = parser.parse_args(namespace=Arguments())
if args.yes and not args.apply:
parser.error("--yes requires --apply")
if args.apply and os.geteuid() != 0:
parser.error("use sudo to apply changes")
user = args.user or os.environ.get("SUDO_USER")
if not user and os.getuid() != 0:
user = pwd.getpwuid(os.getuid()).pw_name
if user:
try:
pwd.getpwnam(user)
except KeyError:
parser.error(f"unknown local user: {user}")
repo = Path(__file__).resolve().parent
try:
audit_subvolumes(repo, user)
except (OSError, ValueError, subprocess.CalledProcessError) as error:
logger.warning("Cannot audit Btrfs subvolumes: %s", error)
for path in git_paths(repo, "ls-files", "-z", "--others", "--exclude-standard"):
logger.warning("Ignoring untracked file: %s", path)
tracked = set(git_paths(repo, "ls-files", "-z"))
# Include working-tree deletions in the warnings, never in the apply plan.
active = {
path for path in tracked if (repo / path).exists() or (repo / path).is_symlink()
}
versions: dict[str, str] = {}
try:
versions = audit_packages(repo)
except (OSError, ValueError, subprocess.CalledProcessError) as error:
logger.warning("Cannot audit installed packages: %s", error)
try:
audit_removed_files(repo, tracked, active, versions)
except (OSError, ValueError, subprocess.CalledProcessError) as error:
logger.warning("Cannot inspect removed-file history: %s", error)
changes: list[Change] = []
unchanged = 0
unreadable = 0
for relative in sorted(active):
destination = Path("/") / relative.relative_to("rootfs")
try:
source = read_entry(repo / relative)
check_parents(destination)
installed = read_entry(destination)
except PermissionError as error:
if args.apply:
raise
unreadable += 1
logger.warning(
"Cannot read %s: %s; skipped (unchecked)",
error.filename or destination,
error.strerror or str(error),
)
continue
if source is None:
raise ValueError(f"Tracked source is missing: {relative}")
if isinstance(source, FileEntry) and b"username_placeholder" in source.data:
if not user:
parser.error("use --user USER when running directly as root")
source = replace(
source,
data=source.data.replace(b"username_placeholder", os.fsencode(user)),
)
if isinstance(installed, FileEntry):
audit_permissions(destination, installed, versions)
if isinstance(installed, SymlinkEntry) and isinstance(source, FileEntry):
raise ValueError(
f"Refusing to overwrite a symlink with a regular file: {destination}"
)
if installed is not None and installed.data == source.data:
unchanged += 1
else:
changes.append((destination, installed, source))
save_diffs(changes, os.environ.get("SUDO_USER") or user)
logger.info(
"%d changed, %d unchanged, %d unchecked.", len(changes), unchanged, unreadable
)
if unreadable:
logger.warning(
"Preview incomplete: %d unreadable file%s. Run with sudo for a complete preview.",
unreadable,
"" if unreadable == 1 else "s",
)
if not changes:
return 1 if unreadable else 0
if not args.apply:
logger.info("Preview only. Use sudo and --apply to install these changes.")
return 1 if unreadable else 0
if not args.yes:
with open("/dev/tty") as terminal:
print("Apply all planned changes? [y/N] ", end="", flush=True)
if terminal.readline().strip().lower() != "y":
logger.info("No changes applied.")
return 0
for destination, installed, _ in changes:
check_parents(destination)
if entry_version(read_entry(destination)) != entry_version(installed):
raise ValueError(f"Destination changed during review: {destination}")
for change in changes:
apply_change(*change)
logger.info("Sync complete. Reload or restart affected services when appropriate.")
return 0
if __name__ == "__main__":
os.umask(0o022)
try:
sys.exit(main())
except (OSError, ValueError, subprocess.CalledProcessError) as error:
logger.error("%s", error)
sys.exit(1)
except KeyboardInterrupt:
logger.warning("Interrupted")
sys.exit(130)