90 lines
2.5 KiB
Python
90 lines
2.5 KiB
Python
import os
|
|
import stat
|
|
from contextlib import contextmanager
|
|
from pathlib import Path
|
|
from tempfile import NamedTemporaryFile
|
|
|
|
|
|
def require_root_directory(path, *, create_mode=None):
|
|
for parent in reversed(path.parents):
|
|
check_root_directory(parent)
|
|
if create_mode is not None:
|
|
try:
|
|
path.mkdir(mode=create_mode)
|
|
except FileExistsError:
|
|
pass
|
|
else:
|
|
path.chmod(create_mode)
|
|
check_root_directory(path)
|
|
|
|
|
|
def check_root_directory(path):
|
|
info = path.lstat()
|
|
if (
|
|
not stat.S_ISDIR(info.st_mode)
|
|
or info.st_uid != 0
|
|
or info.st_mode & 0o022
|
|
):
|
|
raise ValueError(f"Expected a root-controlled directory at {path}.")
|
|
|
|
|
|
def read_root_file(path, *, mode=None):
|
|
check_root_file(path, mode=mode)
|
|
return path.read_text(encoding="utf-8")
|
|
|
|
|
|
def check_root_file(path, *, mode=None):
|
|
info = path.lstat()
|
|
if (
|
|
not stat.S_ISREG(info.st_mode)
|
|
or info.st_uid != 0
|
|
or info.st_mode & 0o022
|
|
):
|
|
raise ValueError(f"Expected a root-controlled file at {path}.")
|
|
if mode is not None and stat.S_IMODE(info.st_mode) != mode:
|
|
raise ValueError(f"Expected permissions {mode:04o} on {path}.")
|
|
|
|
|
|
def write_new_file(path, content, *, mode, group=None):
|
|
with NamedTemporaryFile(
|
|
mode="w", encoding="utf-8", dir=path.parent
|
|
) as staged:
|
|
staged.write(content)
|
|
staged.flush()
|
|
if group is not None:
|
|
os.fchown(staged.fileno(), -1, group)
|
|
os.fchmod(staged.fileno(), mode)
|
|
os.fsync(staged.fileno())
|
|
os.link(staged.name, path)
|
|
|
|
|
|
def replace_configuration(path, content, *, mode=0o644):
|
|
with NamedTemporaryFile(
|
|
mode="w", encoding="utf-8", dir=path.parent, delete=False
|
|
) as temporary:
|
|
staged = Path(temporary.name)
|
|
try:
|
|
temporary.write(content)
|
|
temporary.flush()
|
|
os.fchmod(temporary.fileno(), mode)
|
|
os.fsync(temporary.fileno())
|
|
staged.replace(path)
|
|
finally:
|
|
staged.unlink(missing_ok=True)
|
|
|
|
|
|
@contextmanager
|
|
def locked_root_directory(path, *, shared=False, blocking=True):
|
|
import fcntl
|
|
|
|
require_root_directory(path)
|
|
fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
|
try:
|
|
mode = fcntl.LOCK_SH if shared else fcntl.LOCK_EX
|
|
if not blocking:
|
|
mode |= fcntl.LOCK_NB
|
|
fcntl.flock(fd, mode)
|
|
yield fd
|
|
finally:
|
|
os.close(fd)
|