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
12 changes: 12 additions & 0 deletions DEVELOPING.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ This is the guide for working on 1401's source. To report a bug, see `CONTRIBUTI
|---|---|---|---|
| Engine (scan, build, BIOS guide, stick writer) | `p1401/` | any OS for the tests; Windows in the app | Python 3.12 or newer |
| Windows app (the window) | `windows/App/` | Windows | .NET SDK 8.0.425 (`global.json` pins it), Visual Studio C++ tools for `native/` |
| Linux app (the same four steps) | `linux/` | Linux | Python 3.12 or newer, GTK 4, PyGObject, polkit |
| Mac app (after the install) | `mac/` | macOS 15 or newer | Xcode (Swift 6.3 and 6.4 both build it) |
| UEFI loader (experimental, unused by the app) | `loader/` | QEMU | Rust |
| Upstream engines (pinned copies) | `upstream/` | | do not edit; `PINNED.json` names the commits |
Expand All @@ -31,6 +32,8 @@ Most work is in the engine, and the engine's tests need no special hardware.
`nullmoth.py` (Build the Mac setup and its rules), `guide.py` (Your BIOS steps), `usbwriter.py` (Create the macOS
stick), `report.py` (Send logs). `community_gpu.py` lists other people's GPU drivers and when to mention them.
- `windows/App/`: the C# window. It runs each engine step as `python -u -m <module>` and shows its output.
- `linux/`: the GTK 4 window, its launcher, and `linuxusb.py`'s Linux entry point in `p1401/`. It runs the same engine
modules as the C# window; root steps go through `pkexec`.
- `mac/`: the Mac app that finishes the setup after macOS is installed. `mac/build.sh` builds it and runs its own tests.
- `tests/`: unit tests (`test_*.py`), the hardware corpus (`tests/corpus/`), and the corpus runner (`run_corpus.py`).
- `tools/`: release, packaging and corpus tools.
Expand Down Expand Up @@ -81,6 +84,15 @@ dotnet build windows/App/App.csproj --configuration Release --output build

`.github/workflows/windows-candidate.yml` is the full packaging run, step by step.

**Linux app:**

```bash
bash linux/build.sh /tmp/1401-linux
```

It runs the Linux writer tests and a window self-test, then stages a folder that runs with `./1401`. The packages it
needs and the places it keeps scans and logs are in `linux/README.md`.

**Mac app:**

```bash
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ Install macOS on the PC you already own: the reverse of Boot Camp. 1401 runs on
an OpenCore setup for it and writes a macOS install stick. It is free and open source.

- Download: [releases page](https://github.com/nullmoth/1401/releases) (`1401-Windows-<version>.zip`)
- Linux: [build and run it from source](linux/README.md); the window does the same four steps
- Changes: [CHANGELOG.md](CHANGELOG.md)
- Problems: [troubleshooting](docs/TROUBLESHOOTING.md)
- How it works: [docs/HOW-IT-WORKS.md](docs/HOW-IT-WORKS.md)
Expand Down
3 changes: 3 additions & 0 deletions docs/HOW-IT-WORKS.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
1401 is a Windows app that turns a USB stick into a macOS installer built for one specific PC. This page follows the
four steps of the app through the code.

The source tree also has a Linux window (`linux/README.md`) that runs the same engine steps; the paths below describe
the Windows release, which is what most people use.

> 1401 is new and may not work on every PC. If it does not work on yours, set up OpenCore by hand with the
> [OpenCore Install Guide](https://dortania.github.io/OpenCore-Install-Guide/). The NVIDIA driver and its Mac app work
> on any OpenCore setup.
Expand Down
5 changes: 5 additions & 0 deletions linux/1401
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#!/bin/sh
# Starts 1401 from this checkout. The engine and the window need the repository around them, so this stays in linux/.
set -eu
here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
exec python3 -u "$here/1401.py" "$@"
7 changes: 7 additions & 0 deletions linux/1401.desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[Desktop Entry]
Type=Application
Name=1401
Comment=Build a macOS installer for this PC
Exec=@EXEC@
Terminal=false
Categories=System;
1,097 changes: 1,097 additions & 0 deletions linux/1401.py

Large diffs are not rendered by default.

98 changes: 98 additions & 0 deletions linux/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# 1401 on Linux

The Linux window does the same four steps as the Windows app: Check this PC, Build the Mac setup, Your BIOS steps, and
Create the macOS stick. It is GTK 4 on top of the same Python engine, so the rules, downloads and checks are the ones
described in `docs/HOW-IT-WORKS.md`, not a second implementation.

The Linux app is newer than the Windows one. The engine steps are tested, but the window and the stick writer have not
been through as many real installs. Treat the first stick you write as a test.

## Packages

Debian and Ubuntu:

```bash
sudo apt install python3-gi gir1.2-gtk-4.0 policykit-1 dosfstools exfatprogs
```

Fedora:

```bash
sudo dnf install python3-gobject gtk4 polkit dosfstools exfatprogs
```

Arch:

```bash
sudo pacman -S python-gobject gtk4 polkit dosfstools exfatprogs
```

`util-linux`, `systemd` and `pciutils` are already part of a normal desktop install and provide `lsblk`, `mount`,
`udevadm`, `lspci` and `blockdev`. `exfatprogs` is only needed for the optional full installer; without it the online
installer still works. `partprobe` from `parted` is used when present, and skipped otherwise.

The window runs as your user. Two steps ask policykit for root:

- the hardware check reads `/sys/firmware/acpi/tables`, which only root may open;
- writing the stick erases the disk, formats it and mounts it.

`pkexec` shows the usual password dialog. The app never runs the whole window as root.

## Running it

From the checkout:

```bash
python3 linux/1401.py
```

or `linux/1401`. To make a folder that can be moved out of the checkout:

```bash
bash linux/build.sh # writes dist/1401-linux
dist/1401-linux/1401
```

The build runs the writer tests and a window self-test first, then copies the engine, `upstream/`, `vendor/` and the
window. It does not download OpenCore; the first build does that, into the copy's `upstream/` folder.

`dist/1401-linux/1401.desktop` points at the staged launcher. Copy it to `~/.local/share/applications` if you want a
menu entry.

## What it writes

The stick gets a new MBR with a FAT32 partition labelled `1401`, the OpenCore EFI, and Apple's recovery image under
`com.apple.recovery.boot/`. The image is downloaded from Apple after the stick is erased and checked chunk by chunk
against Apple's signed chunklist. The EFI is copied and read back.

The full installer option needs a stick of 32 GB or more and a download of Apple's `InstallAssistant.pkg`. The package
is checked with `xar` before anything is written, then unpacked onto a second exFAT partition labelled `NMINSTALL`.
Without the option, macOS downloads the rest itself after the installer starts.

Only USB disks are offered. A disk with `/`, `/boot`, `/home` or another system directory mounted on it is refused by
both the window and the writer, and a disk still held open by LUKS, LVM or RAID is refused until that layer is closed.
The writer looks the stick up again by serial, size and model before erasing it, so a stick that came back as
`/dev/sdc` cannot be confused with another disk. A stick that holds an APFS, HFS+, Windows recovery or Linux partition
is reported before it is erased; the window asks once more.

The NVIDIA driver packages are downloaded by the user's process before the elevated write, so the build folder does not
end up with root-owned files.

## Where things are kept

- scans, the built EFI and the BIOS page: `$XDG_STATE_HOME/nullmoth/1401/` (usually `~/.local/state/nullmoth/1401`);
- a recovery image you picked by hand: `$XDG_DATA_HOME/nullmoth/1401/Recovery/` (usually
`~/.local/share/nullmoth/1401/Recovery`);
- the log: `$XDG_STATE_HOME/nullmoth/1401/1401.log`, also shown in the window.

Nothing is uploaded. The Linux window has no log-upload step; the log and the scan folder stay on this PC.

## Tests

```bash
python3 -m unittest tests.test_linux_usb tests.test_linux_root
python3 linux/1401.py --selftest # needs a display; builds every page and exits
python3 -m unittest discover -s tests -t . -p 'test_*.py'
```

The writer tests use fake `lsblk` output and a fake ACPI tree. They never touch a disk.
41 changes: 41 additions & 0 deletions linux/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#!/bin/bash
# Stages a folder that runs without the rest of the checkout: the engine, the pinned upstream copies it needs, and the
# GTK window. The engine is Python, so nothing is compiled; this is a copy plus a launcher.
set -euo pipefail
cd "$(dirname "$0")/.."

OUT=${1:-dist/1401-linux}
mkdir -p "$(dirname "$OUT")"
OUT=$(realpath -m "$OUT")

python3 -m unittest tests.test_linux_usb tests.test_linux_root \
|| { echo "STOP: the Linux stick writer tests failed"; exit 1; }

if [ -n "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ]; then
python3 linux/1401.py --selftest || { echo "STOP: the window could not build its pages"; exit 1; }
else
echo "note: no display, skipped the window self-test"
fi

rm -rf "$OUT"
mkdir -p "$OUT"
cp -a p1401 upstream vendor linux "$OUT/"
rm -f "$OUT/linux/1401.desktop" # the staged copy gets one with an absolute Exec below
find "$OUT" -name __pycache__ -type d -prune -exec rm -rf {} +
rm -rf "$OUT/upstream/OpCore-Simplify/OCK_Files" "$OUT/upstream/OpCore-Simplify/Results"
cp LICENSE NOTICE.md README.md "$OUT/"

cat > "$OUT/1401" <<'LAUNCHER'
#!/bin/sh
# Starts 1401 from the folder this script is in. The engine downloads OpenCore and the kexts into upstream/ on first use.
set -eu
here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
exec python3 -u "$here/linux/1401.py" "$@"
LAUNCHER
chmod 755 "$OUT/1401"

case $OUT in
*[[:space:]]*) echo "STOP: the output path has a space, which a desktop entry cannot express"; exit 1 ;;
esac
sed "s|@EXEC@|$OUT/1401|" linux/1401.desktop > "$OUT/1401.desktop"
echo "built $OUT"
158 changes: 158 additions & 0 deletions p1401/linuxroot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
"""The two steps of the Linux app that need root: reading the firmware's ACPI tables, and writing a USB stick.

The app runs as the user. ACPI tables under /sys/firmware/acpi/tables are readable by root only, so the scan asks
policykit to run this file's `acpi` command once. The USB writer is started the same way (`usb write ...`) so the
whole erase, format and mount sequence happens in one elevated process rather than a mix of sudo calls.

pkexec python3 p1401/linuxroot.py acpi <dest> --owner UID:GID
pkexec python3 p1401/linuxroot.py usb write <device> <EFI build> <darwin major> [options]

When the app itself is already root (a root shell, a live session) the same functions are called directly.
"""
import os
import shutil
import subprocess
import sys

REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TABLES = "/sys/firmware/acpi/tables"
SYSTEM_ACPI = ("DSDT", "FACP", "FACS", "APIC", "MCFG", "HPET", "SRAT", "SLIT", "XSDT", "RSDT")


class RootError(RuntimeError):
pass


def _destination(relative):
"""sysfs names one table `DSDT`; the builder expects `DSDT.aml`. Subdirectories (dynamic/) stay subdirectories."""
return os.path.join(*[part.upper() for part in relative.split(os.sep)]) + ".aml"


def copy_tables(source=TABLES, dest=None, owner=None):
"""Copies every table under `source` into `dest`, returns the paths written.

Reads are done as root and each file is made readable by its owner before the scan continues as the user. A
table that vanishes between listdir and open is skipped: hot-plugged Thunderbolt boxes can add and remove SSDTs
while the scan runs, and one missing optional table should not lose the DSDT.
"""
if not dest:
raise RootError("no destination for the ACPI tables")
if not os.path.isdir(source):
raise RootError(f"{source} does not exist: this kernel has no ACPI table directory")
written = []
for folder, folders, names in os.walk(source, followlinks=False):
folders.sort()
rel_dir = os.path.relpath(folder, source)
for name in sorted(names):
src = os.path.join(folder, name)
if os.path.islink(src) or not os.path.isfile(src):
continue
relative = name if rel_dir == "." else os.path.join(rel_dir, name)
dst = os.path.join(dest, _destination(relative))
os.makedirs(os.path.dirname(dst), exist_ok=True)
try:
with open(src, "rb") as source_file:
data = source_file.read()
except FileNotFoundError:
continue
with open(dst + ".tmp", "wb") as out:
out.write(data)
os.replace(dst + ".tmp", dst)
os.chmod(dst, 0o644)
if owner:
os.chown(dst, owner[0], owner[1])
written.append(dst)
if not table_has(os.path.join(dest, "DSDT.aml"), b"DSDT"):
raise RootError(f"the ACPI directory {source} had no DSDT; this PC's firmware tables cannot be read")
return written


def table_has(path, signature):
try:
with open(path, "rb") as fh:
return fh.read(4) == signature
except OSError:
return False


def _owner(value):
if not value:
return None
try:
uid, gid = value.split(":", 1)
return int(uid), int(gid)
except ValueError as error:
raise RootError(f"bad --owner {value!r}; expected UID:GID") from error


def _write_acpi(dest, owner):
if os.geteuid() != 0:
raise RootError("reading /sys/firmware/acpi/tables needs root")
tables = copy_tables(dest=dest, owner=owner)
print(f"copied {len(tables)} ACPI table(s) to {dest}", flush=True)
return 0


def elevate_acpi(dest):
"""Runs the ACPI copy through pkexec, or directly when the process is already root. Returns the child's output.

pkexec exits 126 when the password dialog is dismissed and 127 when no agent answers; both mean the scan
cannot see the firmware, so they get one sentence instead of an exit code.
"""
owner = f"{os.getuid()}:{os.getgid()}"
if os.geteuid() == 0:
_write_acpi(dest, None)
return
tool = shutil.which("pkexec")
if not tool:
raise RootError("pkexec is not installed. Install policykit-1/polkit, or run 1401 from a root terminal.")
command = [tool, sys.executable, os.path.join(REPO, "p1401", "linuxroot.py"), "acpi", dest, "--owner", owner]
result = subprocess.run(command, capture_output=True, text=True, timeout=300)
if result.returncode != 0:
detail = " ".join((result.stderr or result.stdout or "").split())[-500:]
if result.returncode in (126, 127):
raise RootError("the ACPI read was not authorised, so the hardware check cannot finish. Approve the "
"password prompt and run Check this PC again.")
raise RootError(f"copying the ACPI tables failed (pkexec exit {result.returncode}): {detail or 'no detail'}")
if result.stdout:
print(result.stdout.rstrip(), flush=True)


def main(argv=None):
argv = list(sys.argv[1:] if argv is None else argv)
if not argv:
print("usage: linuxroot.py acpi <dest> --owner UID:GID | usb <command> ...", file=sys.stderr)
return 2
command, rest = argv[0], argv[1:]
try:
if command == "acpi":
dest, owner = None, None
i = 0
while i < len(rest):
if rest[i] == "--owner" and i + 1 < len(rest):
owner = _owner(rest[i + 1])
i += 2
continue
if dest is None:
dest = rest[i]
i += 1
if not dest:
raise RootError("acpi needs a destination directory")
return _write_acpi(dest, owner)
if command == "usb":
from p1401 import linuxusb # noqa: PLC0415 - the writer imports the engine only when it is used
return linuxusb.main(rest)
except RootError as error:
print(f"STOP {error}", file=sys.stderr)
return 1
print(f"unknown command {command!r}", file=sys.stderr)
return 2


if __name__ == "__main__":
if not __package__:
# pkexec starts this file by path, so make `p1401` importable before reloading it under its real name.
sys.path.insert(0, REPO)
from p1401 import linuxroot # noqa: PLC0415
sys.exit(linuxroot.main())
sys.exit(main())
Loading