Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,8 +189,9 @@ Ctrl, Alt and arrows.

- Live CPU, memory, temperature, uptime and storage, with what each app and machine is using.
- Storage pools with their space, drives, layout and errors.
- If a drive got bigger (a resized virtual disk, say), it shows the space that isn't in use yet and
the exact commands to grow into it.
- If the system drive got bigger (a resized virtual disk, say), Storage on this server or a joined
computer shows the space that isn’t in use yet. Use the extra space grows the partition, its
encryption and the filesystem.
- Device name, Wi-Fi, logs, restart, shut down, factory reset, and a What's New after every update.

## Your other computers (Linux, Mac, Windows)
Expand Down
27 changes: 25 additions & 2 deletions connector/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -5349,8 +5349,12 @@ def sync_connector_files(cfg, abilities, fetch_named=None, data_dir=None, helper
return {"updated": updated, "skipped": skipped}


def helper(verb, *args):
r = subprocess.run(["sudo", "-n", HELPER, verb, *args], capture_output=True, text=True, timeout=600)
def helper(verb, *args, stdin=None):
kw = {}
# Pass stdin only when there is some, so other verbs keep the connector's own stdin.
if stdin is not None:
kw["input"] = stdin
r = subprocess.run(["sudo", "-n", HELPER, verb, *args], capture_output=True, text=True, timeout=600, **kw)
if r.returncode:
raise RuntimeError((r.stderr or r.stdout or "Storage helper failed").strip().split("\n")[-1][:300])
return r.stdout.strip()
Expand Down Expand Up @@ -5447,6 +5451,23 @@ def storage_set_sleep(args):
return True


def storage_grow_status(_args):
raw = helper("grow-status")
if not raw or raw == "null":
return None
return json.loads(raw)


def storage_grow(args):
pw = args.get("password") if isinstance(args, dict) else ""
if not isinstance(pw, str):
pw = ""
if len(pw) > 512 or re.search(r"[\r\n]", pw):
raise RuntimeError("Bad password")
# The disk password goes to the helper on stdin, then to cryptsetup. It is not an argument.
return json.loads(helper("grow-system", stdin=(pw + "\n") if pw else ""))


STORAGE_ACTIONS = {
"storage-status": storage_status,
"storage-disks": storage_disks,
Expand All @@ -5461,6 +5482,8 @@ def storage_set_sleep(args):
"storage-forgetPool": storage_forget_pool,
"storage-scrub": storage_scrub,
"storage-setSleep": storage_set_sleep,
"storage-grow-status": storage_grow_status,
"storage-grow": storage_grow,
}

# Virtual machines (ability "vms"). Session libvirt as this user: no sudo, no shell.
Expand Down
205 changes: 201 additions & 4 deletions connector/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
sleep DEV MIN spin-down time for a hard drive (0 = never)
pool-* Btrfs pools at ~/Pools/NAME (create, add, import, forget, scrub, status)
zfs-available is ZFS installed?
grow-status space on the system drive the filesystem does not use yet
grow-system grow that drive's last partition, its encryption and the filesystem
"""
import json
import os
Expand Down Expand Up @@ -101,14 +103,18 @@ def fail(message):
raise HelperError(message)


def default_run(cmd, args):
def default_run(cmd, args, stdin=None):
env = dict(os.environ)
env["PATH"] = HELPER_PATH
env["LC_ALL"] = "C"
# A drive that never answers smartctl must not hold the disk list for the full command limit.
timeout = 15 if cmd == "smartctl" else 600
kw = dict(capture_output=True, text=True, timeout=timeout, env=env)
# The disk password is stdin for cryptsetup. Other commands leave this off.
if stdin is not None:
kw["input"] = stdin
try:
r = subprocess.run([cmd, *args], capture_output=True, text=True, timeout=timeout, env=env)
r = subprocess.run([cmd, *args], **kw)
except FileNotFoundError:
raise HelperError("%s is not installed" % cmd)
except subprocess.TimeoutExpired:
Expand Down Expand Up @@ -147,7 +153,187 @@ def parse_smart(j):
}


def handle(verb, args, run=None, user=None, realpath=None, fstab_text=None, files=None, chown=None, now=None):
MB = 1024 * 1024


def _num(value):
if isinstance(value, bool) or value is None or value == "":
return 0
try:
return int(value)
except (TypeError, ValueError):
try:
return int(float(value))
except (TypeError, ValueError):
return 0


def _fs_size(path, statvfs):
try:
st = statvfs(path)
except OSError:
return 0
fr = getattr(st, "f_frsize", 0) or getattr(st, "f_bsize", 0) or 0
blocks = getattr(st, "f_blocks", 0) or 0
try:
return int(blocks) * int(fr)
except (TypeError, ValueError):
return 0


def _unused_drive_bytes(disk_size, part_sizes, fs_partition_size, fs_size):
# Same thresholds as the server: unallocated space after the partitions, plus a filesystem
# that is meaningfully smaller than its own partition. Other partitions are in use.
parts = [n for n in part_sizes if n > 0]
part_lag = max(0, disk_size - sum(parts)) if parts else 0
raw_fs = (fs_partition_size - fs_size) if fs_partition_size and fs_size else 0
fs_threshold = max(1024 * MB, (fs_partition_size or 0) * 0.06)
fs_lag = raw_fs if raw_fs > fs_threshold else 0
return (part_lag if part_lag > 256 * MB else 0) + fs_lag


def _system_layout(run, user, with_target):
cols = "SOURCE,FSTYPE,TARGET" if with_target else "SOURCE,FSTYPE"
fields = run("findmnt", ["-n", "-o", cols, "-T", user["home"]]).strip().split()
if len(fields) < (3 if with_target else 2):
fail("The system drive couldn’t be found")
source, fstype = fields[0], fields[1]
target = fields[2] if with_target else None
dev = re.sub(r"\[.*\]$", "", source)
if not dev.startswith("/dev/"):
fail("The system drive couldn’t be found")
parsed = json.loads(run("lsblk", ["-J", "-b", "-s", "-o", "NAME,PATH,SIZE,TYPE", dev]) or "{}")
node = (parsed.get("blockdevices") or [None])[0]
layers = []
while isinstance(node, dict):
layers.append(node)
kids = node.get("children") or []
node = kids[0] if kids else None
part = next((n for n in layers if n.get("type") == "part"), None)
crypt = next((n for n in layers if n.get("type") == "crypt"), None)
disk = next((n for n in layers if n.get("type") == "disk"), None)
if not disk:
fail("The system drive couldn’t be found")
tree = json.loads(run("lsblk", ["-J", "-b", "-o", "NAME,PATH,SIZE,TYPE,START", disk.get("path")]) or "{}")
root = (tree.get("blockdevices") or [None])[0] or {}
parts = [c for c in (root.get("children") or []) if c.get("type") == "part"]
last = None
best = -1
for c in parts:
start = _num(c.get("start"))
if start > best:
best = start
last = c
return {
"dev": dev,
"fstype": fstype,
"target": target,
"layers": layers,
"part": part,
"crypt": crypt,
"disk": disk,
"parts": parts,
"last": last,
}


def _drive_report(info, user, statvfs):
disk, part, crypt, parts, last = info["disk"], info["part"], info["crypt"], info["parts"], info["last"]
fs_device = info["layers"][0] if info["layers"] else {}
fs_size = _fs_size(user["home"], statvfs)
part_lag = (_num(disk.get("size")) - sum(_num(c.get("size")) for c in parts)) if parts else 0
steps = []
if part and part_lag > 256 * MB:
steps.append("partition" if last and last.get("name") == part.get("name") else "partition-not-last")
if crypt and part and _num(part.get("size")) - _num(crypt.get("size")) > 256 * MB:
steps.append("encryption")
fs_dev_size = _num(fs_device.get("size"))
if fs_size and fs_dev_size - fs_size > max(1024 * MB, fs_dev_size * 0.06):
steps.append("filesystem")
if crypt and part and part_lag > 256 * MB and "encryption" not in steps:
steps.append("encryption")
if part and part_lag > 256 * MB and "filesystem" not in steps:
steps.append("filesystem")
seen = []
for step in steps:
if step not in seen:
seen.append(step)
part_number = None
if part:
number = re.search(r"(\d+)$", str(part.get("name") or ""))
if number:
part_number = int(number.group(1))
return {
"name": disk.get("path"),
"size": _num(disk.get("size")),
"notInUse": _unused_drive_bytes(_num(disk.get("size")), [_num(c.get("size")) for c in parts], _num(part.get("size")) if part else 0, fs_size),
"steps": seen,
"partition": part.get("path") if part else None,
"partitionNumber": part_number,
"encrypted": crypt.get("name") if crypt else None,
"filesystem": info["fstype"],
}


def _grow_system(run, user, stdin):
info = _system_layout(run, user, True)
layers = info["layers"]
if any(n.get("type") == "lvm" or re.match(r"^raid", str(n.get("type") or "")) for n in layers):
fail("The system is on LVM or RAID. Grow it with lvextend / mdadm instead.")
part, disk, crypt, parts, last = info["part"], info["disk"], info["crypt"], info["parts"], info["last"]
if not part or not disk:
fail("The system isn’t on a partition of a drive, so there’s nothing to grow")
if layers.index(part) != len(layers) - 2:
fail("This layout isn’t supported for growing")
if not last or last.get("path") != part.get("path"):
fail("%s isn’t the last partition on %s, so it can’t grow into the new space. Use a partition tool (GParted) from a live USB." % (part.get("path"), disk.get("path")))
number = re.search(r"(\d+)$", str(part.get("name") or ""))
if not number:
fail("The partition number couldn’t be read")
number = number.group(1)
free = _num(disk.get("size")) - sum(_num(c.get("size")) for c in parts)
passphrase = stdin or ""
if passphrase.endswith("\n"):
passphrase = passphrase[:-1]
done = []
# 1. The partition: move a GPT's backup header to the new end, then extend the last
# partition to the end of the drive and tell the kernel (works while it's mounted).
if free > 16 * MB:
dump = run("sfdisk", ["--dump", disk.get("path")])
table = re.search(r"^label:\s*(\w+)", dump or "", re.M)
if table and table.group(1) == "gpt":
run("sfdisk", ["--relocate", "gpt-bak-std", disk.get("path")])
run("sfdisk", ["--no-reread", "--force", "-N", number, disk.get("path")], ", +\n")
run("partx", ["-u", "-n", number, disk.get("path")])
done.append("partition")
# 2. The encryption layer, if any. The password arrives on stdin and is not stored.
if crypt:
try:
if passphrase:
run("cryptsetup", ["resize", crypt.get("name"), "--key-file", "-"], passphrase)
else:
run("cryptsetup", ["resize", crypt.get("name")])
except Exception as e:
if re.search(r"passphrase|key|No key available", str(e), re.I):
if passphrase:
fail("That disk password didn’t unlock the drive")
fail("NEEDS_PASSWORD: The drive is encrypted. Enter its disk password (the one you type when the computer starts).")
raise
done.append("encryption")
fstype, target, dev = info["fstype"], info["target"], info["dev"]
if fstype == "btrfs":
run("btrfs", ["filesystem", "resize", "max", target])
elif fstype in ("ext4", "ext3"):
run("resize2fs", [dev])
elif fstype == "xfs":
run("xfs_growfs", [target])
else:
fail("Growing a %s filesystem isn’t supported" % fstype)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Filesystem checked after partition grows

Medium Severity

grow-system extends the partition and its encryption before it checks the filesystem type. On ZFS, F2FS, NTFS, or anything other than btrfs, ext3, ext4, and XFS, the partition table is already rewritten when the helper then fails, and a retry hits the same error.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 2d5c8d6. Configure here.

done.append("filesystem")
return {"grown": done, "disk": disk.get("path"), "partition": part.get("path")}


def handle(verb, args, run=None, user=None, realpath=None, fstab_text=None, files=None, chown=None, now=None, stdin=None, statvfs=None):
run = run or default_run
realpath = realpath or os.path.realpath
now = now or time.time
Expand Down Expand Up @@ -1055,12 +1241,23 @@ def virtual_of(real):
for z in zfs_importable_data():
out.append({"kind": "zfs", "uuid": "zfs:%s" % z["name"], "label": z["name"], "devices": [], "state": z.get("state"), "otherSystem": z.get("otherSystem"), "note": z.get("note")})
return json.dumps(out)
# The drive the owner's home is on, after that disk was made bigger.
if verb == "grow-status":
try:
info = _system_layout(run, user, False)
except Exception:
return "null"
return json.dumps(_drive_report(info, user, statvfs or os.statvfs))
if verb == "grow-system":
return json.dumps(_grow_system(run, user, stdin))
fail("Unknown action: %s" % verb)


def main():
verb = sys.argv[1] if len(sys.argv) > 1 else ""
args = sys.argv[2:]
# The disk password, only for a grow. It is never an argument.
stdin = sys.stdin.read() if verb == "grow-system" else None
try:
if os.geteuid() != 0:
fail("Run this through sudo as the person who installed the connector")
Expand All @@ -1077,7 +1274,7 @@ def main():
fail("Unknown user")
if pw.pw_uid != uid:
fail("Unknown user")
sys.stdout.write("%s\n" % handle(verb, args, user={"name": name, "uid": uid, "gid": pw.pw_gid, "home": pw.pw_dir}))
sys.stdout.write("%s\n" % handle(verb, args, user={"name": name, "uid": uid, "gid": pw.pw_gid, "home": pw.pw_dir}, stdin=stdin))
except HelperError as e:
sys.stderr.write("%s\n" % e)
sys.exit(2)
Expand Down
Loading
Loading