Recover GitHub-generated patch distfiles; fix git ownership in the VM

The first pilot stopped building the host pkg: GitHub now abbreviates the
object names on the index lines of its generated commit patches with 10
digits instead of 9, so OPNsense's patches of ports-mgmt/pkg no longer
match distinfo, and nothing caches OPNsense's own distfiles.

- release/fetch-patch.sh: FETCH_CMD that, when fetch(1) fails for a
  GitHub commit/pull/compare patch, shortens the abbreviations until the
  size matches; the port's checksum target verifies the SHA256.
- build.sh: run tools' distfiles step on its own, repair the ports it
  could not fetch on the host into the distfiles set, and rerun it; the
  pilot fetches its ports' distfiles too; host pkg uses the wrapper.
- vm.sh sync: files owned by root in the VM. They kept the workstation's
  uid, git refused the "dubious" repository, and that defeated the dirty
  check silently. build.sh now fails when git cannot read /usr/deps, and
  the package target refuses a version without the commit count.
- migrate-device.sh: FreeBSD grep rejects the empty alternative in the
  fingerprint file check, so it failed on every device. Found by running
  release/tests on the build VM, now part of the documented test run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jeremy Karst 2026-11-18 13:43:10 -05:00
parent f8276aa54a
commit 1ab64f5ba2
7 changed files with 265 additions and 16 deletions

View file

@ -59,7 +59,7 @@ DISTDIR?= ${OPSDIR}/dist
# repository, e.g. "26.1.11_74". It grows with every commit and every
# release, so it always upgrades the previous package (including the
# vendor's "26.1.5_N" versions). Override: make package PKG_VERSION=...
_PKG_REV!= git -C ${OPSDIR} rev-list --count HEAD 2>/dev/null || echo 0
_PKG_REV!= git -C ${OPSDIR} rev-list --count HEAD 2>/dev/null || true
PKG_VERSION?= ${OPS_VERSION}_${_PKG_REV}
PKG_STAGEDIR= ${BUILDDIR}/pkg-stage
PKG_CONFDIR= ${OPSDIR}/config
@ -216,6 +216,7 @@ userspace: fmlib fmc dpa_app cmm cmmctl fand
package: all
@if [ -z "${OPS_VERSION}" ]; then echo "set OPS_VERSION (e.g. 26.1.11)" >&2; exit 1; fi
@case "${PKG_VERSION}" in *_) echo "git cannot count the commits of ${OPSDIR}; set PKG_VERSION" >&2; exit 1;; esac
@rm -f ${DISTDIR}/mono-gateway-*.pkg
@rm -rf ${PKG_STAGEDIR}
@mkdir -p ${PKG_STAGEDIR}/boot/modules

View file

@ -150,8 +150,21 @@ release/vm.sh pull-out 14.3 26.1 # -> /scratch/mono-opnsense/out/26.1
becomes `<release>_<patches>`.
3. Builds base, kernel and xtools, then this repository's kernel modules, as
an early check against the new kernel.
4. Builds distfiles, ports, plugins, core and the packages set.
5. Builds the board package against the base set's headers and our libxml2,
4. Fetches the distfiles of every port and its dependencies into the
distfiles set. Some no longer download as recorded in the ports tree's
distinfo, chiefly patches GitHub generates on the fly
(`github.com/<owner>/<repo>/commit/<hash>.patch`): GitHub abbreviates
the object names on their `index` lines with more digits as a repository
grows, so an old patch now differs by a few bytes. FreeBSD's distfile
cache keeps the originals of FreeBSD's ports, but nothing keeps
OPNsense's own (e.g. the patches of `ports-mgmt/pkg`). The ports that
failed are fetched again on the build host with `release/fetch-patch.sh`,
which shortens the abbreviations until the size matches distinfo; the
port's `checksum` target then verifies the SHA256, so only the original
bytes are accepted. A distfile that still cannot be fetched stops the
build with the port's name.
5. Builds ports, plugins, core and the packages set.
6. Builds the board package against the base set's headers and our libxml2,
and puts it into the packages set.
**`finish`:**
@ -168,9 +181,14 @@ release/vm.sh pull-out 14.3 26.1 # -> /scratch/mono-opnsense/out/26.1
**Before a first full build of a series**, measure the cross-build:
```sh
release/vm.sh run 14.3 pilot 26.1 26.1.11 security/suricata lang/rust
release/vm.sh run 14.3 pilot 26.1 26.1.11 security/suricata databases/py-duckdb@py313
```
The pilot builds base, kernel and xtools, fetches the distfiles of the given
ports, and builds those ports with their dependencies, timing each. It then
removes its partial packages set (tools would otherwise consider the ports
built); base, kernel, xtools and distfiles are kept for the full build.
### Board package version
`mono-gateway` is versioned `<release>_<commit count of this repository>`,
@ -353,7 +371,10 @@ reflash from Recovery Linux with the signed image from `/releases/` (README.md,
```sh
python3 -m unittest discover -s mirror/tests # gwmirror stage/verify/publish, incl. HTTPS
python3 -m unittest discover -s release/tests # migrate-device.sh and 20-kernel-update
python3 -m unittest discover -s release/tests # migrate-device.sh, 20-kernel-update, fetch-patch.sh
release/vm.sh ssh 14.3 'cd /usr/deps && python3 -m unittest discover -s release/tests'
```
Both suites also run on the FreeBSD build VM.
Run `release/tests` on the build VM as well (after `vm.sh sync`): those
scripts run on FreeBSD, whose `grep`, `sed` and `sh` reject things the GNU
tools accept (an empty alternative in a `grep -E` pattern, for one).

View file

@ -9,8 +9,9 @@
# base, kernel, xtools, ports, plugins, core and the
# mono-gateway package; nothing is signed yet
# build.sh pilot SERIES VERSION PORT...
# base, kernel and xtools, then only the given ports
# (e.g. security/suricata, py-duckdb@py313), timed
# base, kernel and xtools, then the distfiles and
# packages of only the given ports (e.g.
# security/suricata, databases/py-duckdb@py313), timed
# build.sh finish SERIES VERSION KEYDIR
# sign every set with KEYDIR/repo.{key,pub} (must be
# the key trusted in keys/fingerprints), build and
@ -36,6 +37,8 @@ COMMITTER="-c user.name=gwmirror-build -c user.email=build@opnsense.karsttech.co
# the terminal of a daemon'd build), and a transfer that moves nothing for 10
# minutes is aborted
export GIT_TERMINAL_PROMPT=0 GIT_HTTP_LOW_SPEED_LIMIT=1 GIT_HTTP_LOW_SPEED_TIME=600
# for ports fetched on this host (make "${FETCH_PATCH}" ...)
FETCH_PATCH="FETCH_CMD=sh ${DEPS}/release/fetch-patch.sh"
die()
{
@ -121,10 +124,40 @@ host_pkg()
_have=$(pkg -v | cut -d. -f1-2)
if [ "${_want}" != "${_have}" ]; then
step "building host pkg ${_want} from the ports tree (have ${_have})"
make -C /usr/ports/ports-mgmt/pkg BATCH=yes clean all reinstall clean
make -C /usr/ports/ports-mgmt/pkg BATCH=yes "${FETCH_PATCH}" clean all reinstall clean
fi
}
# fetch_distfiles [PORTSLIST=...]: tools' distfiles step, which fetches every distfile
# of the ports (and their dependencies) into the distfiles set. Some no longer download
# as recorded in distinfo, chiefly patches GitHub generates on the fly; the failed ports
# are fetched again on this host into the set with fetch-patch.sh, whose results the
# ports' checksum target verifies, and the step is run once more.
fetch_distfiles()
{
_log=/var/tmp/gwbuild-distfiles.log
step "distfiles"
# shellcheck disable=SC2086
{ _rc=0; ${TOOLS} ${UNSIGNED} distfiles "$@" 2>&1 || _rc=$?; echo "${_rc}" > "${_log}.rc"; } |
tee "${_log}"
[ "$(cat "${_log}.rc")" != 0 ] || return 0
_ports=$(sed -n 's|^>>> Failed fetching \(/usr/ports/\)\{0,1\}||p' "${_log}" | sort -u)
[ -n "${_ports}" ] || die "the distfiles step failed (see above)"
step "repairing the distfiles of:" ${_ports}
_set=$(ls "${SETS}"/distfiles-*.tar) || die "no distfiles set"
_dir=$(mktemp -d /var/tmp/gwdistfiles.XXXXXX)
tar -C "${_dir}" -xf "${_set}"
for _port in ${_ports}; do
make -C "/usr/ports/${_port}" BATCH=yes ARCH=aarch64 DISTDIR="${_dir}/distfiles" \
"${FETCH_PATCH}" checksum || die "cannot fetch the distfiles of ${_port}"
done
tar -C "${_dir}" -cf "${_set}" distfiles
rm -rf "${_dir}"
step "distfiles, after the repair"
# shellcheck disable=SC2086
${TOOLS} ${UNSIGNED} distfiles "$@"
}
# the board package is cross-compiled against the base set's headers and libraries
sysroot_base()
{
@ -194,7 +227,8 @@ build()
{
args "$@"
[ "$(id -u)" = 0 ] || die "run as root"
if [ -z "${ALLOW_DIRTY:-}" ] && [ -n "$(git -C "${DEPS}" status --porcelain)" ]; then
_status=$(git -C "${DEPS}" status --porcelain) || die "git cannot read ${DEPS} (vm.sh sync)"
if [ -z "${ALLOW_DIRTY:-}" ] && [ -n "${_status}" ]; then
die "${DEPS} has uncommitted changes (commit them, or ALLOW_DIRTY=1 for a test build)"
fi
checkout_all
@ -205,9 +239,10 @@ build()
sysroot_base
step "mono-gateway kernel modules (early check against the new kernel)"
make -C "${DEPS}" -j"$(sysctl -n hw.ncpu)" modules OPS_SETTINGS="${SERIES}"
step "distfiles ports plugins core packages"
fetch_distfiles
step "ports plugins core packages"
# shellcheck disable=SC2086
${TOOLS} ${UNSIGNED} distfiles ports plugins core packages
${TOOLS} ${UNSIGNED} ports plugins core packages
sysroot_libxml2
step "mono-gateway package"
make -C "${DEPS}" -j"$(sysctl -n hw.ncpu)" package OPS_SETTINGS="${SERIES}" OPS_VERSION="${VERSION}"
@ -221,16 +256,20 @@ pilot()
args "$@"
shift 2
[ $# -ge 1 ] || usage
for _port in "$@"; do
echo "${_port}" | grep -Eqx '[a-z0-9_-]+/[A-Za-z0-9_.+-]+(@[A-Za-z0-9_]+)?' || die "bad port '${_port}'"
done
checkout_all
host_pkg
_t0=$(date +%s)
# shellcheck disable=SC2086
${TOOLS} ${UNSIGNED} base kernel xtools
step "base kernel xtools took $((($(date +%s) - _t0) / 60)) minutes"
# the distfiles set is kept for the real build, which fetches the rest
fetch_distfiles PORTSLIST="$*"
# PORTSLIST limits the build to one port (and its dependencies); naming
# the port in the target makes tools run the step again for each one
for _port in "$@"; do
echo "${_port}" | grep -Eqx '[a-z0-9_-]+/[A-Za-z0-9_.+-]+(@[A-Za-z0-9_]+)?' || die "bad port '${_port}'"
_t0=$(date +%s)
# shellcheck disable=SC2086
${TOOLS} ${UNSIGNED} "ports-${_port}" PORTSLIST="${_port}" PORTSENV="DEPEND=no"

61
release/fetch-patch.sh Normal file
View file

@ -0,0 +1,61 @@
#!/bin/sh
#
# fetch-patch.sh: FETCH_CMD for the ports framework (make FETCH_CMD="sh fetch-patch.sh")
# that also recovers patches GitHub generates on the fly. build.sh uses it to repair
# distfiles that no longer download as recorded in distinfo.
#
# It runs fetch(1) as the default FETCH_CMD does. When that fails for a GitHub commit,
# pull request or compare patch (or diff) and the framework passed the expected size
# (-S), it downloads the current patch and shortens the abbreviated object names on its
# "index" lines until the size matches: GitHub abbreviates them with more digits as a
# repository grows, which is how its old patches change. Only the size is checked
# here; the port's checksum target verifies the file against distinfo's SHA256, so a
# wrong guess is rejected there.
#
# Copyright 2026 Karst Tech
# SPDX-License-Identifier: BSD-2-Clause
set -u
fetch -Fpr "$@" && exit 0
SIZE=
URL=
OUT=
while [ $# -gt 0 ]; do
case ${1} in
-S) SIZE=${2:-}; shift ;;
-o) OUT=${2:-}; shift ;;
-[NT]) shift ;;
-*) ;;
*) URL=${1} ;;
esac
shift
done
case ${URL} in
https://github.com/*/*/commit/*.patch | https://github.com/*/*/commit/*.diff | \
https://github.com/*/*/pull/*.patch | https://github.com/*/*/pull/*.diff | \
https://github.com/*/*/compare/*.patch | https://github.com/*/*/compare/*.diff) ;;
*) exit 1 ;;
esac
echo "${SIZE}" | grep -Eqx '[0-9]+' || exit 1
OUT=${OUT:-${URL##*/}}
case ${OUT} in
'' | */ | /* | . | .. | ../* | */.. | */../*) exit 1 ;;
esac
TMP=$(mktemp "./.fetch-patch.XXXXXX") || exit 1
trap 'rm -f "${TMP}" "${TMP}.n"' EXIT
fetch -q -o "${TMP}" "${URL}" || exit 1
for N in 7 8 9 10 11 12; do
sed -E "s/^index ([0-9a-f]{${N}})[0-9a-f]*\.\.([0-9a-f]{${N}})[0-9a-f]*/index \1..\2/" \
"${TMP}" > "${TMP}.n" || exit 1
if [ "$(wc -c < "${TMP}.n")" -eq "${SIZE}" ]; then
mv "${TMP}.n" "${OUT}" || exit 1
echo "=> ${OUT}: recovered from GitHub's current patch (index lines at ${N} digits)"
exit 0
fi
done
echo "=> ${OUT}: no abbreviation of GitHub's current patch has the size ${SIZE}" >&2
exit 1

View file

@ -105,7 +105,7 @@ valid_fingerprint()
[ -f "${1}" ] && [ "$(wc -l < "${1}" | tr -d ' ')" -le 3 ] &&
grep -Eqx 'function: "sha256"' "${1}" &&
grep -Eqx 'fingerprint: "[0-9a-f]{64}"' "${1}" &&
[ "$(grep -cv -E '^(function: "sha256"|fingerprint: "[0-9a-f]{64}"|)$' "${1}")" = 0 ]
[ "$(grep -cv -E '^(function: "sha256"|fingerprint: "[0-9a-f]{64}")?$' "${1}")" = 0 ]
}
repoint()

View file

@ -1,6 +1,6 @@
# Copyright 2026 Karst Tech
# SPDX-License-Identifier: BSD-2-Clause
"""Tests for the shell scripts that run on the firewall.
"""Tests for the shell scripts that run on the firewall and in the build.
Run: python3 -m unittest discover -s release/tests
@ -21,6 +21,7 @@ HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(os.path.dirname(HERE))
MIGRATE = os.path.join(REPO, "release", "migrate-device.sh")
KERNEL_HOOK = os.path.join(REPO, "rc.d", "20-kernel-update")
FETCH_PATCH = os.path.join(REPO, "release", "fetch-patch.sh")
MIRROR = "https://opnsense.karsttech.com"
FP_NAME = "opnsense.karsttech.com.20261117"
@ -399,5 +400,130 @@ class KernelHookTest(unittest.TestCase):
self.assertEqual(self.content("/boot/msdos/dtb/mono-gateway-dk.dtb"), self.OLD_DTB)
# A GitHub-generated patch as distinfo recorded it (9-digit abbreviations) and as
# GitHub serves it today (10 digits).
PATCH_9 = """From a54ea1a2f7d858fe6eb2976d688c251e64acf8f8 Mon Sep 17 00:00:00 2001
Subject: [PATCH] libpkg: disable package scripts reaper
---
libpkg/lua_scripts.c | 2 +-
libpkg/scripts.c | 2 +-
diff --git a/libpkg/lua_scripts.c b/libpkg/lua_scripts.c
index 0327cae46..0f9a634f2 100644
--- a/libpkg/lua_scripts.c
+++ b/libpkg/lua_scripts.c
@@ -1 +1 @@
-\t\treturn (EPKG_FATAL);
+\t\t/* return (EPKG_FATAL); */
diff --git a/libpkg/scripts.c b/libpkg/scripts.c
index bf0c388a9..e4960ff69
--- a/libpkg/scripts.c
+++ b/libpkg/scripts.c
@@ -1 +1 @@
-x
+y
"""
PATCH_10 = (PATCH_9.replace("0327cae46..0f9a634f2", "0327cae463..0f9a634f2e")
.replace("bf0c388a9..e4960ff69", "bf0c388a9f..e4960ff69a"))
GH_URL = "https://github.com/opnsense/pkg/commit/a54ea1a2f7d858fe6eb2976d688c251e64acf8f8.patch"
class FetchPatchTest(unittest.TestCase):
"""release/fetch-patch.sh, the FETCH_CMD build.sh repairs distfiles with."""
def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="gw-fetch-")
self.addCleanup(shutil.rmtree, self.tmp)
self.fx = Fixture(self.tmp)
self.distdir = os.path.join(self.tmp, "distfiles")
os.makedirs(self.distdir)
self.served = os.path.join(self.tmp, "served.patch")
with open(self.served, "w") as f:
f.write(PATCH_10)
# the wrapper's own "fetch -q -o FILE URL" gets GitHub's current patch; the
# framework's attempt ("fetch -Fpr ...") fails on the size unless FAKE_DIRECT
self.fx.make_fake("fetch", """if [ "$1 $2" = "-q -o" ]; then
[ -z "${FAKE_DOWNLOAD_FAIL:-}" ] || exit 1
exec cp "$FAKE_SERVED" "$3"
fi
[ -n "${FAKE_DIRECT:-}" ] || exit 1
for a; do last=$a; done
echo direct > "${last##*/}"
""")
def fetch(self, *args, **env):
e = {"PATH": f"{self.fx.bin}:/usr/bin:/bin", "FAKE_LOG": self.fx.log, "FAKE_SERVED": self.served}
e.update(env)
return subprocess.run(["sh", FETCH_PATCH, *args], env=e, cwd=self.distdir,
capture_output=True, text=True)
def files(self):
out = []
for d, _, names in os.walk(self.distdir):
out += [os.path.relpath(os.path.join(d, n), self.distdir) for n in names]
return sorted(out)
def test_recovers_recorded_patch(self):
r = self.fetch("-S", str(len(PATCH_9)), GH_URL)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("9 digits", r.stdout)
name = "a54ea1a2f7d858fe6eb2976d688c251e64acf8f8.patch"
self.assertEqual(self.files(), [name], "no temporary files left")
with open(os.path.join(self.distdir, name)) as f:
self.assertEqual(f.read(), PATCH_9)
def test_direct_fetch_passes_through(self):
r = self.fetch("-S", "123", GH_URL, FAKE_DIRECT="1")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(len(self.fx.calls()), 1, "no second download")
self.assertEqual(self.fx.calls()[0], f"fetch -Fpr -S 123 {GH_URL}")
def test_output_in_subdirectory(self):
os.makedirs(os.path.join(self.distdir, "sub"))
r = self.fetch("-S", str(len(PATCH_9)), "-o", "sub/x.patch", GH_URL)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(self.files(), ["sub/x.patch"])
def test_pull_and_compare_patches(self):
for url in ("https://github.com/o/r/pull/12.patch", "https://github.com/o/r/compare/a...b.diff"):
r = self.fetch("-S", str(len(PATCH_9)), url)
self.assertEqual(r.returncode, 0, url + r.stderr)
self.assertEqual(self.files(), ["12.patch", "a...b.diff"])
def test_other_urls_are_not_rewritten(self):
for url in ("https://example.org/a54ea1a.patch",
"https://evil.example/github.com/o/r/commit/x.patch",
"https://github.com.evil.example/o/r/commit/x.patch",
"http://github.com/o/r/commit/x.patch",
"https://github.com/o/r/archive/x.tar.gz"):
r = self.fetch("-S", str(len(PATCH_9)), url)
self.assertEqual(r.returncode, 1, url)
self.assertEqual(len(self.fx.calls()), 5, "only the framework's own attempts")
self.assertEqual(self.files(), [])
def test_no_matching_size(self):
r = self.fetch("-S", str(len(PATCH_9) + 1), GH_URL)
self.assertEqual(r.returncode, 1)
self.assertIn("no abbreviation", r.stderr)
self.assertEqual(self.files(), [], "nothing written, no temporary files left")
def test_needs_numeric_size(self):
for args in ((GH_URL,), ("-S", "12x", GH_URL), ("-S", "", GH_URL)):
self.assertEqual(self.fetch(*args).returncode, 1, args)
self.assertEqual(self.files(), [])
def test_download_failure(self):
r = self.fetch("-S", str(len(PATCH_9)), GH_URL, FAKE_DOWNLOAD_FAIL="1")
self.assertEqual(r.returncode, 1)
self.assertEqual(self.files(), [])
def test_rejects_unsafe_output_names(self):
for out in ("../evil.patch", "/tmp/evil.patch", "a/../../evil.patch", "..", ".", "dir/"):
r = self.fetch("-S", str(len(PATCH_9)), "-o", out, GH_URL)
self.assertEqual(r.returncode, 1, out)
self.assertEqual(self.files(), [])
self.assertFalse(os.path.exists(os.path.join(self.tmp, "evil.patch")))
if __name__ == "__main__":
unittest.main()

View file

@ -173,7 +173,8 @@ stop()
sync_deps()
{
running || die "not running"
rsync -a --delete --exclude /dist/ --exclude /_build/ --exclude /_vendor/ --exclude /.claude/ \
# owned by root in the VM: git refuses a repository owned by another user
rsync -a --chown=0:0 --delete --exclude /dist/ --exclude /_build/ --exclude /_vendor/ --exclude /.claude/ \
-e "ssh ${SSH_OPTS}" "${HERE}/" root@127.0.0.1:/usr/deps/
echo ">>> synced ${HERE} to /usr/deps ($(git -C "${HERE}" describe --always --dirty))"
}