diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..fb91156 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,31 @@ +name: test + +on: + pull_request: + branches: [main, dev] + push: + branches: [main] + +permissions: + contents: read + +concurrency: + group: test-${{ github.ref }} + cancel-in-progress: true + +jobs: + test: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - name: Install dependencies + run: | + sudo apt-get update + sudo apt-get install -y shellcheck bubblewrap libarchive-tools + - name: Allow unprivileged user namespaces + run: sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 + - name: Test + run: make test diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..e93b657 --- /dev/null +++ b/Makefile @@ -0,0 +1,33 @@ +SHELL := bash +SHELLFILES := mgrecover.sh $(wildcard tests/*.sh) + +define need +@command -v $(1) >/dev/null || { echo "missing tool: $(1) (Debian/Ubuntu: apt install $(2); Arch: pacman -S $(3))" >&2; exit 1; } +endef + +.NOTPARALLEL: +.PHONY: test check-tools lint unit sim + +test: check-tools lint unit sim + +check-tools: + $(call need,shellcheck,shellcheck,shellcheck) + $(call need,bwrap,bubblewrap,bubblewrap) + $(call need,bsdtar,libarchive-tools,libarchive) + $(call need,python3,python3,python) + +lint: + $(call need,shellcheck,shellcheck,shellcheck) + shellcheck -x -P SCRIPTDIR $(SHELLFILES) + +unit: + $(call need,bsdtar,libarchive-tools,libarchive) + $(call need,python3,python3,python) + bash tests/unit.sh + +sim: + $(call need,bwrap,bubblewrap,bubblewrap) + $(call need,bsdtar,libarchive-tools,libarchive) + $(call need,python3,python3,python) + bash tests/sim-root.sh + bash tests/sim-sandbox.sh diff --git a/README.md b/README.md index 39b4a65..0832ec4 100644 --- a/README.md +++ b/README.md @@ -1 +1,56 @@ -# Recovery \ No newline at end of file +# MediaGarrd Recovery + +`mgrecover.sh` restores a [MediaGarrd](https://mediagarrd.github.io/MediaGarrd/) backup archive (`-media-backup.zip`) to the original paths of its files, with contents, permissions, owners (as root) and file modification times. + +## Requirements + +- bash 4+, `bsdtar` (Debian/Ubuntu: `apt install libarchive-tools`, Arch: `pacman -S libarchive`, Fedora: `dnf install bsdtar`), coreutils, `awk`, `sed` + +## Install + +```sh +git clone --depth 1 https://github.com/MediaGarrd/Recovery.git +cd Recovery +``` + +Optional: `sudo install -m 755 mgrecover.sh /usr/local/bin/mgrecover`. + +## Usage + +```sh +sudo ./mgrecover.sh 20261112-140649-938-media-backup.zip +./mgrecover.sh -n 20261112-140649-938-media-backup.zip +./mgrecover.sh -C /tmp/restore 20261112-140649-938-media-backup.zip +``` + +| Option | Meaning | +| --- | --- | +| `-C, --root DIR` | Restore under `DIR` instead of `/`. For inspection: no symlinks are created. | +| `-n, --dry-run` | Print the plan and write nothing. | +| `-y, --yes` | Do not ask for confirmation (required without a terminal). | +| `-h, --help` | Show usage. | + +Exit status is `0` on success (also with warnings) and non-zero on errors. + +## Symlinks + +- Restoring to `/`: a link `L -> T` is recreated only if its target (following links stored in the archive, up to 8 hops) exists on the machine or is stored in the archive. Otherwise the link is not created, files stored below it go to a real directory at `L` (a dangling link already there is removed), and a link with nothing below it is skipped with a warning. Real files or directories already at `L` are never replaced. Links already on the machine, such as `/var/run`, are followed. Relative `..` targets are judged by name, not through other links. Link times are not restored, link owners only as root, and directories that receive content through kept links (the link targets) get the current time. +- With `-C DIR`: no link is created; files stored below a link are restored as a real directory. Existing symlinks under `DIR` are not followed. Files are restored without owners, but setuid/setgid bits are kept, so as root review the tree before making it reachable by others. +- Both modes refuse the whole archive, before writing anything, if a name has `..`, empty or `.` components, a leading `/`, a control character or a newline. + +## Testing + +`make test` runs shellcheck, unit tests and simulated restores (some inside a `bwrap` sandbox with a private fake `/`; the real `/` is never touched). It needs `shellcheck`, `bubblewrap`, `bsdtar` and `python3` (Debian/Ubuntu: `apt install shellcheck bubblewrap libarchive-tools python3`). Link owners (`chown -h`) are not tested, since the sandbox maps only uid 0. + +## Stop the server first + +The archive contains the MediaGarrd server's database (`mediagarrd.db`). Stop the server before restoring, or the live database is corrupted. + +## Links + +- Website: +- Server: + +## License + +GPL-3.0, see [LICENSE](LICENSE). diff --git a/mgrecover.sh b/mgrecover.sh new file mode 100755 index 0000000..7bb296d --- /dev/null +++ b/mgrecover.sh @@ -0,0 +1,208 @@ +#!/usr/bin/env bash +set -euo pipefail + +PROG=${0##*/} +SEP=$'\037' +ROOT=/ DRY=0 YES=0 WARNS=0 ERRS=0 FULL=1 ARGS=() + +usage() { + cat < + -C, --root DIR restore under DIR, without creating symlinks (inspection) + -n, --dry-run show the plan and write nothing + -y, --yes do not ask for confirmation + -h, --help show this help +Stop the MediaGarrd server first. Run as root to restore owners. +USAGE +} +die() { printf '%s: error: %s\n' "$PROG" "$*" >&2; exit 1; } +warn() { printf 'warning: %s\n' "$*" >&2; WARNS=$((WARNS + 1)); } +mp() { local c="" x a; IFS=/ read -ra a <<<"$1"; for x in ${a[@]+"${a[@]}"}; do c+=${c:+/}$x; if [[ -n ${KP[$c]+y} ]]; then c=${KP[$c]}; fi; done; MP=$c; } +pat() { sed -e 's/[][\\*?^$]/\\&/g' -e "s|^|$1|" -e "s|\$|$2|"; } +chk() { LC_ALL=C awk -v d="$1" -v S="$SEP" 'function par(s) { if (!sub(/\/[^\/]*$/, "", s)) s = ""; return s } +function rs(s, o, i) { while ((i = index(s, "\001"))) { o = o substr(s, 1, i - 1) "\\"; s = substr(s, i + 1) } return o s } +function rk(l, r, s, p, i, v) { + if (l in rank) return rank[l] + rank[l] = 0 + for (i = 1; i <= 2; i++) { + p = (i == 1) ? par(l) : pp[l] + while (p != "") { if (p in tg) { v = rk(p) + 1; if (v > r) r = v } p = par(p) } + } + return rank[l] = r + 0 +} +function norm(p, n, a, i, k, o, r) { + n = split(p, a, "/"); k = 0 + for (i = 1; i <= n; i++) { + if (a[i] == "" || a[i] == ".") continue + if (a[i] == "..") { if (k > 0) k--; continue } + o[++k] = a[i] + } + for (i = 1; i <= k; i++) r = r (i > 1 ? "/" : "") o[i] + return r +} +NR == FNR { nm[FNR] = $0; nn = FNR; next } +{ + raw = nm[FNR]; ln = $0 + gsub(/\\\\/, "\001", raw); gsub(/\\\\/, "\001", ln) + if (index(raw, "\\") || index(ln, "\\")) { print "unsupported name or link target (control character): " nm[FNR] > "/dev/stderr"; bad = 1; next } + raw = rs(raw); ln = rs(ln) + c = raw; sub(/\/$/, "", c) + if (c == "" || index("/" c "/", "//") || index("/" c "/", "/./") || index("/" c "/", "/../")) { print "unsafe entry name: " raw > "/dev/stderr"; bad = 1; next } + total++; bytes += $5 + if (c ~ /(^|\/)mediagarrd\.db$/) db = 1 + if (substr($0, 1, 1) == "l") { + i = index(ln, " " raw " -> ") + if (!i) { print "cannot parse link entry: " raw > "/dev/stderr"; bad = 1; next } + tg[c] = substr(ln, i + length(raw) + 5); u[c] = $3; g[c] = $4 + } else { + nl[c] = 1 + p = par(c); while (p != "" && !(p in nla)) { nla[p] = 1; p = par(p) } + } + p = par(c); while (p != "" && !(p in all)) { all[p] = 1; p = par(p) } +} +END { + if (FNR != nn) { print "archive listing is inconsistent (newline in a name?)" > "/dev/stderr"; bad = 1 } + printf "%d %.0f %d %d\n", total, bytes, db, bad > (d "/stats") + if (bad) exit 3 + for (p in nl) print p > (d "/prov") + for (p in nla) print p > (d "/prov") + for (l in tg) { + cur = l; h = 0; ok = 1; P = "" + while (1) { + t = tg[cur] + if (t == "") { ok = 0; break } + P = (t ~ /^\//) ? norm(t) : norm(par(cur) "/" t) + if (!(P in tg)) break + if (++h > 8) { ok = 0; break } + cur = P + } + pp[l] = P; okk[l] = ok + } + for (l in tg) print rk(l) S l S tg[l] S pp[l] S okk[l] S ((pp[l] in nl) || (pp[l] in nla) ? 1 : 0) S ((l in all) ? 1 : 0) S u[l] S g[l] > (d "/links.raw") +}' "$1/n" "$1/v"; } +if [[ ${BASH_SOURCE[0]-$0} != "$0" ]]; then return 0; fi + +TMP=$(mktemp -d "${TMPDIR:-/tmp}/mgrecover.XXXXXX") +trap 'rm -rf -- "$TMP"' EXIT +trap 'exit 130' INT +trap 'exit 143' TERM + +while (($#)); do + case $1 in + -C | --root) (($# > 1)) || die "$1 needs an argument"; ROOT=$2; shift ;; + --root=*) ROOT=${1#*=} ;; + -n | --dry-run) DRY=1 ;; + -y | --yes) YES=1 ;; + -h | --help) usage; exit 0 ;; + --) shift; ARGS+=("$@"); break ;; + -?*) usage >&2; exit 2 ;; + *) ARGS+=("$1") ;; + esac + shift +done +((${#ARGS[@]} == 1)) || { usage >&2; exit 2; } +ARCH=${ARGS[0]} + +command -v bsdtar >/dev/null || die "bsdtar not found (Debian/Ubuntu: apt install libarchive-tools; Arch: pacman -S libarchive; Fedora: dnf install bsdtar)" +[[ -f $ARCH && -r $ARCH ]] || die "cannot read $ARCH" +[[ $(head -c2 -- "$ARCH") == PK ]] || die "not a zip archive: $ARCH" +[[ -n $ROOT ]] || die "empty root" +if [[ -d $ROOT ]]; then ROOT=$(CDPATH='' cd -- "$ROOT" && pwd -P); elif [[ -e $ROOT ]]; then die "not a directory: $ROOT"; fi +if [[ $ROOT =~ ^/+$ ]]; then ROOT=/; else FULL=0; fi + +u=0 +if [[ $(locale charmap 2>/dev/null) == UTF-8 ]]; then u=1; fi +for l in C.UTF-8 C.utf8 en_US.UTF-8 en_US.utf8; do + if ((u)); then break; fi + if ! command -v locale >/dev/null || locale -a 2>/dev/null | grep -xF "$l" >/dev/null; then export LC_ALL=$l; u=1; fi +done +((u)) || warn "no UTF-8 locale found; non-ASCII names may fail" + +bsdtar -tf "$ARCH" >"$TMP/n" || die "bsdtar cannot read $ARCH" +bsdtar --numeric-owner -tvf "$ARCH" >"$TMP/v" || die "bsdtar cannot read $ARCH" +[[ -s $TMP/n ]] || die "archive is empty" +: >"$TMP/links.raw"; : >"$TMP/prov" + +chk "$TMP" || die "archive has entries this tool refuses to restore; nothing was written" +read -r TOTAL BYTES DB _ <"$TMP/stats" +LC_ALL=C sort -n -t "$SEP" -k1,1 "$TMP/links.raw" >"$TMP/links" + +: >"$TMP/all"; : >"$TMP/kept"; : >"$TMP/sub"; : >"$TMP/nofile"; : >"$TMP/inc"; : >"$TMP/rm" +declare -A KP=() +D=${ROOT%/} +nk=0 nc=0 ns=0 +while IFS=$SEP read -r _ L T P OK PROV KIDS U G; do + printf '%s\n' "$L" >>"$TMP/all" + mp "$P"; pm=$MP; mp "$L"; lm=$MP + why="" + if ((!FULL)); then why="no links under --root" + elif ((!OK)); then why="broken link chain" + elif ((!PROV)) && [[ ! -e /$pm ]] && ! { [[ $pm != "$P" ]] && grep -qxF -- "$pm" "$TMP/prov"; }; then why="target /$P does not exist and is not in the archive" + elif [[ -e /$lm && ! -L /$lm ]]; then why="$D/$L already exists; real data is kept" + fi + if [[ -z $why ]]; then + printf '%s\n' "$L" >>"$TMP/sub" + if ((KIDS)); then printf '%s\n' "$L" >>"$TMP/inc"; fi + printf '%s\n' "$L$SEP$T$SEP$P$SEP$KIDS$SEP$U$SEP$G" >>"$TMP/kept" + KP[$L]=$pm + echo "keep $D/$L -> $T" + ((++nk)) + elif ((KIDS)); then + if ((FULL)) && [[ -e /$lm && ! -L /$lm && ! -d /$lm ]]; then + printf '%s\n' "$L" >>"$TMP/nofile" + warn "$D/$L is a file: entries below it are not restored (link to $T not created)" + ((++ns)) + else + how="restored as a real directory" + if ((FULL)) && [[ -L /$lm ]]; then + if [[ -e /$lm ]]; then how="written through the existing link"; else printf '%s\n' "/$lm" >>"$TMP/rm"; fi + fi + echo "convert $D/$L -> $T ($why): contents $how" + ((++nc)) + fi + else + if ((FULL)); then warn "$D/$L -> $T skipped ($why)"; else echo "skip $D/$L -> $T ($why)"; fi + ((++ns)) + fi +done <"$TMP/links" +pat '^' '$' <"$TMP/all" >"$TMP/x1" +pat '^' / <"$TMP/sub" >"$TMP/x2" +pat '^' / <"$TMP/nofile" >"$TMP/x4" +pat '' '/*' <"$TMP/inc" >"$TMP/x3" + +echo "Archive : $ARCH ($TOTAL entries, $(numfmt --to=iec "$BYTES"))" +echo "Root : $ROOT" +echo "Links : $nk kept, $nc with content below them converted, $ns skipped" +if ((DB)); then warn "archive contains mediagarrd.db: the MediaGarrd server must be stopped before restoring"; fi +if ((FULL && EUID != 0)); then warn "not running as root: owners cannot be restored and some paths may fail"; fi +if ((!FULL && EUID == 0)); then warn "running as root: setuid/setgid files from the archive keep their bits under $D"; fi +if ((DRY)); then echo "Dry run: nothing was written."; exit 0; fi + +if ((!YES)); then + [[ -t 0 ]] || die "no terminal to ask for confirmation; use --yes" + read -r -p "Restore now? [y/N] " a || a= + [[ $a == [yY]* ]] || die "aborted" +fi + +mkdir -p -- "$ROOT" +xt=(bsdtar -xpf "$ARCH" -C "$ROOT") +if ((FULL)); then xt+=(-P); else xt+=(--no-same-owner); fi +while IFS= read -r p; do rm -f -- "$p" || ERRS=$((ERRS + 1)); done <"$TMP/rm" +cat "$TMP/x1" "$TMP/x2" "$TMP/x4" >"$TMP/xa" +cat "$TMP/x1" "$TMP/x4" >"$TMP/xc" +"${xt[@]}" -X "$TMP/xa" || { ERRS=$((ERRS + 1)); echo "$PROG: bsdtar reported errors" >&2; } +if [[ -s $TMP/kept ]]; then + while IFS=$SEP read -r L T P KIDS U G; do + if ! mkdir -p -- "$(dirname -- "/$L")" || { ((KIDS)) && [[ ! -e /$P ]] && ! mkdir -p -- "/$P"; }; then + ERRS=$((ERRS + 1)); continue + fi + ln -sfnT -- "$T" "/$L" || ERRS=$((ERRS + 1)) + if ((EUID == 0)); then chown -h "$U:$G" "/$L" || true; fi + done <"$TMP/kept" +fi +if [[ -s $TMP/inc ]]; then + "${xt[@]}" -X "$TMP/xc" -T "$TMP/x3" || { ERRS=$((ERRS + 1)); echo "$PROG: bsdtar reported errors" >&2; } +fi + +echo "Done: $TOTAL entries, $nk links kept, $nc converted, $ns skipped, $WARNS warnings, $ERRS errors." +((ERRS == 0)) diff --git a/tests/common.sh b/tests/common.sh new file mode 100644 index 0000000..7d203a2 --- /dev/null +++ b/tests/common.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# shellcheck disable=SC2034 +GP=('gen/sp dir' 'gen/sp dir/a b.txt' 'gen/glob/*[x]?.txt' 'gen/glob/[a]' 'gen/utf8/héllo-日本.txt' 'gen/arrow/a -> b.txt' 'gen/back/we\ird.txt' 'gen/mode/exec.sh' 'gen/mode/secret') +GEN_SPEC='d|gen/sp dir|750 +f|gen/sp dir/a b.txt|600|spaces +f|gen/glob/*[x]?.txt|644|glob +f|gen/glob/[a]|755|bracket +f|gen/utf8/héllo-日本.txt|644|utf8 +f|gen/arrow/a -> b.txt|644|arrow +f|gen/back/we\\ird.txt|644|backslash +f|gen/mode/exec.sh|755|exec +f|gen/mode/secret|600|secret' +GEN_WANT='gen/sp dir|directory|750|1577836800 +gen/sp dir/a b.txt|regular file|600|1577836800 +gen/glob/*[x]?.txt|regular file|644|1577836800 +gen/glob/[a]|regular file|755|1577836800 +gen/utf8/héllo-日本.txt|regular file|644|1577836800 +gen/arrow/a -> b.txt|regular file|644|1577836800 +gen/back/we\ird.txt|regular file|644|1577836800 +gen/mode/exec.sh|regular file|755|1577836800 +gen/mode/secret|regular file|600|1577836800' +STAT_FMT='%n|%F|%a|%Y' diff --git a/tests/inner.sh b/tests/inner.sh new file mode 100755 index 0000000..323d08a --- /dev/null +++ b/tests/inner.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +dump() { + local skip=(\( -path /usr -o -path /proc -o -path /dev -o -path /tmp -o -path /.mg -o -path /bin -o -path /lib -o -path /lib64 -o -path /sbin -o -path /etc/alternatives \) -prune -o) + find / -mindepth 1 "${skip[@]}" ! -path /etc -printf '%p|%y|%m|%U|%l\n' | LC_ALL=C sort + find / -mindepth 1 "${skip[@]}" -type f -exec sha256sum {} + | LC_ALL=C sort +} +cd / +eval "$SETUP" +dump >/.mg/out/tree0 +for ((i = 1; i <= ${RUNS:-1}; i++)); do + bash /.mg/mgrecover.sh "$@" >"/.mg/out/log$i" 2>&1 <"${STDIN:-/dev/null}" + echo $? >"/.mg/out/rc$i" + dump >"/.mg/out/tree$i" +done +eval "$POST" >/.mg/out/post 2>&1 +exit 0 diff --git a/tests/lib.sh b/tests/lib.sh new file mode 100644 index 0000000..0f1bb0b --- /dev/null +++ b/tests/lib.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# shellcheck disable=SC2034 +export PYTHONDONTWRITEBYTECODE=1 +export TZ=UTC +HERE=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P) +SCRIPT=${HERE%/*}/mgrecover.sh +ZA=/.mg/a.zip +PASS=0 FAIL=0 N=0 +W=$(mktemp -d "${TMPDIR:-/tmp}/mgtest.XXXXXX") +cleanup() { chmod -R u+rwX -- "$W" 2>/dev/null; rm -rf -- "$W"; } +trap cleanup EXIT +trap 'exit 130' INT +trap 'exit 143' TERM + +pass() { PASS=$((PASS + 1)); printf 'ok %d - %s\n' "$((PASS + FAIL))" "$1"; } +fail() { FAIL=$((FAIL + 1)); printf 'not ok %d - %s\n' "$((PASS + FAIL))" "$1"; } +t_eq() { if [[ $2 == "$3" ]]; then pass "$1"; else fail "$1"; printf '# expected: %q\n# actual: %q\n' "$2" "$3"; fi; } +t_has() { if [[ $2 == *"$3"* ]]; then pass "$1"; else fail "$1"; printf '# missing: %q\n# in: %q\n' "$3" "$2"; fi; } +t_lacks() { if [[ $2 != *"$3"* ]]; then pass "$1"; else fail "$1"; printf '# unexpected: %q\n# in: %q\n' "$3" "$2"; fi; } +t_true() { local d=$1; shift; if "$@"; then pass "$d"; else fail "$d"; fi; } +t_false() { local d=$1; shift; if "$@"; then fail "$d"; else pass "$d"; fi; } +finish() { printf '%d passed, %d failed\n' "$PASS" "$FAIL"; ((FAIL == 0)); } + +is_dir() { [[ -d $1 && ! -L $1 ]]; } +is_file() { [[ -f $1 && ! -L $1 ]]; } +is_link() { [[ -L $1 ]]; } +absent() { [[ ! -e $1 && ! -L $1 ]]; } + +mkzip() { python3 "$HERE/mkzip.py" "$1"; } +fresh() { N=$((N + 1)); C=$W/c$N; R=$C/root; Z=$C/a.zip; mkdir -p "$R" "$C/abs"; } +runc() { OUT=$(bash "$SCRIPT" -C "$R" "$@" 2>&1 &1); RC=$?; } +snap() { + ( + cd -- "$1" || exit 1 + find . -printf "%p|%y|%m|%l${2:+|%T@}\n" | LC_ALL=C sort + find . -type f -exec sha256sum {} + | LC_ALL=C sort + ) +} +names() { find "$1" -mindepth 1 -maxdepth 1 -printf '%f\n' | LC_ALL=C sort; } +confined() { t_eq "$1: nothing written outside the root" "a.zip abs root" "$(names "$C" | paste -sd' ')"; t_eq "$1: escape target untouched" "" "$(names "$C/abs")"; } diff --git a/tests/mkzip.py b/tests/mkzip.py new file mode 100644 index 0000000..80eb8b7 --- /dev/null +++ b/tests/mkzip.py @@ -0,0 +1,39 @@ +import re +import sys +import zipfile + +ESC = re.compile(r"\\(x[0-9a-fA-F]{2}|n|t|\\)") +SIMPLE = {"n": "\n", "t": "\t", "\\": "\\"} +STAMP = (2020, 1, 1, 0, 0, 0) + + +def dec(s): + return ESC.sub(lambda m: SIMPLE.get(m.group(1)) or chr(int(m.group(1)[1:], 16)), s) + + +def entry(kind, name, a, b): + if kind == "d": + info = zipfile.ZipInfo(name.rstrip("/") + "/", STAMP) + info.external_attr = ((0o40000 | int(a or "755", 8)) << 16) | 0x10 + return info, b"" + info = zipfile.ZipInfo(name, STAMP) + if kind == "l": + info.external_attr = (0o120777 << 16) + return info, a.encode() + info.external_attr = (0o100000 | int(a or "644", 8)) << 16 + return info, (b if b is not None else "x").encode() + + +def main(): + with zipfile.ZipFile(sys.argv[1], "w", zipfile.ZIP_STORED) as z: + for line in sys.stdin.read().split("\n"): + if not line: + continue + f = [dec(x) for x in line.split("|")] + f += [None] * (4 - len(f)) + info, data = entry(f[0], f[1], f[2], f[3]) + info.create_system = 3 + z.writestr(info, data) + + +main() diff --git a/tests/ptyrun.py b/tests/ptyrun.py new file mode 100644 index 0000000..a54b92f --- /dev/null +++ b/tests/ptyrun.py @@ -0,0 +1,21 @@ +import os +import pty +import sys + +data = sys.argv[1].encode().decode("unicode_escape").encode("latin1") +pid, fd = pty.fork() +if pid == 0: + os.execvp(sys.argv[2], sys.argv[2:]) +os.write(fd, data) +out = b"" +while True: + try: + chunk = os.read(fd, 4096) + except OSError: + break + if not chunk: + break + out += chunk +_, status = os.waitpid(pid, 0) +sys.stdout.buffer.write(out) +sys.exit(os.waitstatus_to_exitcode(status)) diff --git a/tests/sim-root.sh b/tests/sim-root.sh new file mode 100644 index 0000000..b4b20b2 --- /dev/null +++ b/tests/sim-root.sh @@ -0,0 +1,176 @@ +#!/usr/bin/env bash +# shellcheck source=lib.sh +source "$(dirname -- "${BASH_SOURCE[0]}")/lib.sh" +# shellcheck source=common.sh +source "$HERE/common.sh" +export LC_ALL=C.UTF-8 + +fresh +mkzip "$Z" < l2 -> /abs: restore succeeds' 0 "$RC" +t_true 'root chain: l1 is a real directory' is_dir "$R/l1" +t_eq 'root chain: content restored in the root' pwn "$(<"$R/l1/x")" +confined 'root chain' + +fresh +mkzip "$Z" <<'EOF2' +l|d|. +l|x|d/d/../../.. +f|x/pwn|644|pwn +f|d/dd|644|dd +EOF2 +runc -y "$Z" +t_eq 'root d -> . with x -> d/d/../../..: restore succeeds' 0 "$RC" +t_true 'root: x is a real directory' is_dir "$R/x" +t_eq 'root: x/pwn is inside the root' pwn "$(<"$R/x/pwn")" +t_eq 'root: no link anywhere' '' "$(find "$R" -type l)" +confined 'root dot chain' + +fresh +mkzip "$Z" < v2 with v2/data -> /abs: restore succeeds' 0 "$RC" +t_true 'root: cur is a real directory' is_dir "$R/cur" +t_true 'root: cur/data is a real directory' is_dir "$R/cur/data" +t_eq 'root: cur/data/x is inside the root' pwn "$(<"$R/cur/data/x")" +confined 'root nested links' + +fresh +ln -s "$C/abs" "$R/esc" +mkzip "$Z" <<<'f|esc/x|644|pwn +f|fine.txt|644|ok' +runc -y "$Z" +t_eq 'root: a pre-existing escaping link makes the run fail' 1 "$RC" +t_has 'root: the failure is reported' "$OUT" 'bsdtar reported errors' +t_true 'root: a pre-existing escaping link is not followed' test ! -e "$C/abs/x" +t_eq 'root: escape target stays empty' '' "$(names "$C/abs")" +t_eq 'root: the rest of the archive is still restored' ok "$(<"$R/fine.txt")" + +fresh +mkzip "$Z" <<<"$GEN_SPEC" +runc -y "$Z" +t_eq 'root names: restore succeeds' 0 "$RC" +t_eq 'root names: modes, types and mtimes are preserved' "$GEN_WANT" "$(cd "$R" && stat -c "$STAT_FMT" -- "${GP[@]}")" +t_eq 'root names: contents are intact' 'glob|utf8|arrow|backslash|' "$(cd "$R" && for f in 'gen/glob/*[x]?.txt' 'gen/utf8/héllo-日本.txt' 'gen/arrow/a -> b.txt' 'gen/back/we\ird.txt'; do printf '%s|' "$(<"$f")"; done)" +t_eq 'root names: no extra paths appear' 'a b.txt' "$(names "$R/gen/sp dir")" + +fresh +mkzip "$Z" <<<"$GEN_SPEC +l|srv/media|/mnt/nas +f|srv/media/a.txt|644|a" +printf 'old\n' >"$R/keep.txt" +mkdir -p "$R/srv/sub" +B=$(snap "$R" t) +runc -n -y "$Z" +t_eq 'root dry run: exit 0' 0 "$RC" +t_has 'root dry run: says nothing was written' "$OUT" 'Dry run: nothing was written.' +t_eq 'root dry run: tree is byte-identical, including times' "$B" "$(snap "$R" t)" +runc -n "$Z" +t_eq 'root dry run: does not ask for confirmation' 0 "$RC" +t_eq 'root dry run: tree still identical' "$B" "$(snap "$R" t)" + +fresh +mkzip "$Z" <<<"$GEN_SPEC +l|srv/media|/mnt/nas +f|srv/media/a.txt|644|a" +runc -y "$Z"; first=$RC +A=$(snap "$R") +runc -y "$Z" +t_eq 'root re-run: both runs succeed' '0 0' "$first $RC" +t_eq 'root re-run: tree is unchanged' "$A" "$(snap "$R")" + +fresh +mkzip "$Z" <<<'f|srv/mediagarrd.db|644|db' +runc -n -y "$Z" +t_has 'root: database warning' "$OUT" 'warning: archive contains mediagarrd.db' + +fresh +mkzip "$Z" <<<'f|a.txt|644|a' +runc "$Z" +t_eq 'root: without a tty and without -y the script refuses' 1 "$RC" +t_has 'root: refusal says why' "$OUT" 'no terminal to ask for confirmation; use --yes' +t_true 'root: refusal writes nothing' absent "$R/a.txt" + +runpty '\x04' "$Z" +t_eq 'root: EOF at the prompt aborts' 1 "$RC" +t_has 'root: the prompt was shown' "$OUT" 'Restore now? [y/N]' +t_has 'root: abort is reported' "$OUT" 'aborted' +t_true 'root: EOF writes nothing' absent "$R/a.txt" +runpty 'n\n' "$Z" +t_eq 'root: answering n aborts' 1 "$RC" +t_true 'root: n writes nothing' absent "$R/a.txt" +runpty 'y\n' "$Z" +t_eq 'root: answering y restores' 0 "$RC" +t_eq 'root: y restores the file' a "$(<"$R/a.txt")" + +fresh +printf 'this is not a zip\n' >"$C/plain.zip" +runc -y "$C/plain.zip" +t_eq 'root: non-zip input is rejected' 1 "$RC" +t_has 'root: non-zip input is named' "$OUT" 'not a zip archive' +printf 'PKnot really a zip archive at all' >"$C/fake.zip" +runc -y "$C/fake.zip" +t_eq 'root: corrupt input is rejected' 1 "$RC" +t_has 'root: corrupt input is reported' "$OUT" 'bsdtar cannot read' +mkzip "$Z" <<<'f|a.txt|644|aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +f|b.txt|644|bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' +head -c 100 "$Z" >"$C/trunc.zip" +runc -y "$C/trunc.zip" +t_true 'root: truncated input is rejected' test "$RC" -ne 0 +t_eq 'root: truncated input writes nothing' '' "$(names "$R")" +python3 -c 'import zipfile,sys; zipfile.ZipFile(sys.argv[1],"w").close()' "$C/empty.zip" +runc -y "$C/empty.zip" +t_eq 'root: an empty archive is rejected' 1 "$RC" +t_has 'root: empty archive is reported' "$OUT" 'archive is empty' +runc -y "$C/missing.zip" +t_eq 'root: missing input is rejected' 1 "$RC" + +fresh +mkzip "$Z" <<<'f|loc/é-日本.txt|644|u' +OUT=$(env -u LC_ALL -u LANG -u LC_CTYPE LC_CTYPE=UTF-8 bash "$SCRIPT" -C "$R" -y "$Z" 2>&1 "$o/bwrap.log" 2>&1 + if [[ ! -f $o/post ]]; then printf 'bail out! sandbox failed: %s\n' "$(<"$o/bwrap.log")"; exit 1; fi + RC=$(<"$o/rc1"); LOG=$(<"$o/log1"); TREE=$(<"$o/tree1"); TREE0=$(<"$o/tree0"); PO=$(<"$o/post") + RC2='' TREE2='' + if [[ -f $o/rc2 ]]; then RC2=$(<"$o/rc2"); TREE2=$(<"$o/tree2"); fi + SETUP='' POST='' RUNS=1 SB_UID=0 SB_EXTRA=() +} +node() { awk -F'|' -v p="$1" -v y="$2" -v l="${3-}" '$1 == p && $2 == y && (l == "" || $5 == l) { f = 1 } END { exit !f }' <<<"$TREE"; } +gone() { ! awk -F'|' -v p="$1" '$1 == p { f = 1 } END { exit !f }' <<<"$TREE"; } +sbmk() { fresh; mkzip "$Z" <<<"$1"; } + +fresh +mkzip "$Z" <<<'f|x|644|x' +sbx -n "$ZA" +t_eq 'sandbox works: private root is writable and script runs' 0 "$RC" +t_has 'sandbox: the script sees a fake root' "$LOG" 'Root : /' +POST='id -u' sbx -n "$ZA" +t_eq 'sandbox: runs as uid 0' 0 "$PO" + +SPEC='l|srv/media|/mnt/nas +f|srv/media/a.txt|644|media +l|srv/cur|/srv/v2 +f|srv/v2/data|644|d +l|srv/rel|v2 +l|toplink|/srv/v2 +l|srv/nested/deep/lnk|/mnt/exist2' +sbmk "$SPEC" +SETUP='mkdir -p /mnt/nas /mnt/exist2; echo old >/mnt/nas/old.txt' RUNS=2 sbx -y "$ZA" +t_eq 'links: restore succeeds' 0 "$RC" +t_has 'links: summary counts' "$LOG" 'Links : 5 kept, 0 with content below them converted, 0 skipped' +t_has 'links: final summary' "$LOG" 'Done: 7 entries, 5 links kept, 0 converted, 0 skipped, 0 warnings, 0 errors.' +t_true 'links: existing target is kept as a link' node /srv/media l /mnt/nas +t_true 'links: content below a kept link lands in the target' node /mnt/nas/a.txt f +t_true 'links: a file already under a kept link is kept' node /mnt/nas/old.txt f +t_true 'links: archive-provided target is kept' node /srv/cur l /srv/v2 +t_true 'links: archive-provided target is restored' node /srv/v2/data f +t_true 'links: relative link is kept' node /srv/rel l v2 +t_true 'links: top-level link is kept' node /toplink l /srv/v2 +t_true 'links: nested link is kept' node /srv/nested/deep/lnk l /mnt/exist2 +t_eq 're-run: second run succeeds' 0 "$RC2" +t_eq 're-run: tree is idempotent' "$TREE" "$TREE2" +FIRST=$TREE +sbmk "$(tac <<<"$SPEC")" +SETUP='mkdir -p /mnt/nas /mnt/exist2; echo old >/mnt/nas/old.txt' sbx -y "$ZA" +t_eq 'links: reversed archive order gives the same tree' "$FIRST" "$TREE" + +sbmk 'l|srv/b|/srv/c +l|srv/c|/srv/missing +f|srv/b/x|644|bx +l|srv/media|/srv/m +l|srv/m|/mnt/nas +f|srv/media/a|644|ma' +sbx -y "$ZA" +t_eq 'broken chains: restore succeeds' 0 "$RC" +t_true 'broken chain with content: converted to a real directory' node /srv/b d +t_true 'broken chain: content restored' node /srv/b/x f +t_true 'unmounted chain with content: converted' node /srv/media d +t_true 'unmounted chain: content restored' node /srv/media/a f +t_true 'broken chain without content: skipped' gone /srv/c +t_true 'unmounted target link without content: skipped' gone /srv/m +t_has 'broken chain: skip is a warning' "$LOG" 'warning: /srv/c -> /srv/missing skipped (target /srv/missing does not exist and is not in the archive)' +t_has 'broken chain: conversion is reported' "$LOG" 'convert /srv/b -> /srv/c' +t_has 'broken chain: summary' "$LOG" '0 links kept, 2 converted, 2 skipped, 2 warnings, 0 errors.' + +for pair in 'b a' 'a b'; do + read -r p q <<<"$pair" + sbmk "l|srv/$p|/mnt/nas +l|srv/$q|$p/x" + SETUP='mkdir -p /mnt/nas/x' sbx -y "$ZA" + t_true "M1 ($p -> /mnt/nas, $q -> $p/x): first link kept" node "/srv/$p" l /mnt/nas + t_true "M1 ($p -> /mnt/nas, $q -> $p/x): link through it kept" node "/srv/$q" l "$p/x" + t_has "M1 ($p, $q): summary" "$LOG" '2 links kept' + SETUP='mkdir -p /mnt/nas' sbx -y "$ZA" + t_true "M1 ($p, $q) with missing /mnt/nas/x: first link kept" node "/srv/$p" l /mnt/nas + t_true "M1 ($p, $q) with missing /mnt/nas/x: link through it skipped" gone "/srv/$q" + t_has "M1 ($p, $q) with missing /mnt/nas/x: warned" "$LOG" "/srv/$q -> $p/x skipped" +done + +sbmk 'l|srv/media|/mnt/nas +l|srv/media/lib|/mnt/lib' +SETUP='mkdir -p /mnt/nas /mnt/lib' sbx -y "$ZA" +t_eq 'm-A two-level: restore succeeds' 0 "$RC" +t_true 'm-A: outer link kept' node /srv/media l /mnt/nas +t_true 'm-A: inner link is created in the link target' node /mnt/nas/lib l /mnt/lib + +sbmk 'l|srv/b|/mnt/nas +l|srv/a|/srv/b/data +f|mnt/nas/data|644|d' +sbx -y "$ZA" +t_eq 'm-B archive-provided target through a link: restore succeeds' 0 "$RC" +t_true 'm-B: outer link kept' node /srv/b l /mnt/nas +t_true 'm-B: link through it kept' node /srv/a l /srv/b/data +t_true 'm-B: target content restored' node /mnt/nas/data f +t_has 'm-B: no warnings' "$LOG" '0 warnings' + +for order in 'f|srv/b/new/q|644|q +f|srv/a/f|644|f' 'f|srv/a/f|644|f +f|srv/b/new/q|644|q'; do + sbmk "l|srv/b|/mnt/nas +l|srv/a|b/new +$order" + SETUP='mkdir -p /mnt/nas' sbx -y "$ZA" + t_eq "kept link to a target below another kept link (${order%%|*} first): restore succeeds" 0 "$RC" + t_true 'kept link with content: link created' node /srv/a l b/new + t_true 'kept link with content: target directory created through the outer link' node /mnt/nas/new d + t_true 'kept link with content: archive content in the target' node /mnt/nas/new/q f + t_true 'kept link with content: content below the link in the target' node /mnt/nas/new/f f + t_has 'kept link with content: no errors' "$LOG" '0 errors' +done + +sbmk 'l|srv/media|/mnt/nas +f|srv/media/a|644|x' +SETUP='mkdir -p /srv; ln -s /dev/gone /srv/media' sbx -y "$ZA" +t_eq 'dangling device link: restore succeeds' 0 "$RC" +t_true 'dangling device link is replaced by a real directory' node /srv/media d +t_true 'dangling device link: content restored' node /srv/media/a f + +sbmk 'l|srv/media|/mnt/nas +f|srv/other|644|o' +SETUP='mkdir -p /srv/media /mnt/nas; echo keep >/srv/media/old' POST='cat /srv/media/old' sbx -y "$ZA" +t_eq 'real data at L: restore succeeds' 0 "$RC" +t_true 'real data at L is kept' node /srv/media d +t_eq 'real data at L: content untouched' keep "$PO" +t_true 'real data at L: old file still there' node /srv/media/old f +t_has 'real data at L: warned' "$LOG" 'warning: /srv/media -> /mnt/nas skipped (/srv/media already exists; real data is kept)' + +sbmk 'l|srv/media|/mnt/nas +f|srv/media/a|644|x' +SETUP='mkdir -p /srv/media /mnt/nas; echo keep >/srv/media/old' sbx -y "$ZA" +t_true 'real data at L with content below: both kept in a real directory' node /srv/media/old f +t_true 'real data at L with content below: content restored' node /srv/media/a f +t_true 'real data at L with content below: not a link' node /srv/media d + +sbmk 'l|srv/media|/mnt/nas +f|srv/media/a|644|x' +SETUP='mkdir -p /srv /mnt/nas; echo FILE >/srv/media' POST='cat /srv/media' sbx -y "$ZA" +t_eq 'file at L: restore succeeds' 0 "$RC" +t_eq 'file at L: kept untouched' FILE "$PO" +t_true 'file at L: nothing restored below it' gone /srv/media/a +t_has 'file at L: warned' "$LOG" 'is a file: entries below it are not restored' + +sbmk 'f|var/run/x.pid|644|1' +SETUP='mkdir -p /run /var; ln -s ../run /var/run' sbx -y "$ZA" +t_true '/var/run link: still a link' node /var/run l ../run +t_true '/var/run link: file written through it' node /run/x.pid f +sbmk 'l|var/run|../run +f|var/run/y.pid|644|2' +SETUP='mkdir -p /run /var; ln -s ../run /var/run' sbx -y "$ZA" +t_eq '/var/run archive link: restore succeeds' 0 "$RC" +t_true '/var/run archive link: link kept' node /var/run l ../run +t_true '/var/run archive link: content in /run' node /run/y.pid f +t_has '/var/run archive link: counted as kept' "$LOG" '1 links kept' + +sbmk 'f|srv/ro/x|644|a +f|srv/ok.txt|644|b' +mkdir -p "$C/empty" +SB_EXTRA=(--ro-bind "$C/empty" /srv/ro) +sbx -y "$ZA" +t_eq 'read-only directory: exit status is non-zero' 1 "$RC" +t_has 'read-only directory: bsdtar error reported' "$LOG" 'bsdtar reported errors' +t_has 'read-only directory: summary still printed with the error count' "$LOG" 'Done: 2 entries, 0 links kept, 0 converted, 0 skipped, 0 warnings, 1 errors.' +t_true 'read-only directory: other files still restored' node /srv/ok.txt f + +sbmk "$GEN_SPEC" +SETUP='mkdir -p /srv' POST="cd /; stat -c '$STAT_FMT' -- $(printf '%q ' "${GP[@]}")" sbx -y "$ZA" +t_eq 'names: restore succeeds' 0 "$RC" +t_eq 'names: spaces, globs, UTF-8, arrows and backslashes; modes and mtimes preserved' "$GEN_WANT" "$PO" +t_has 'names: summary' "$LOG" 'Done: 9 entries' + +sbmk 'l|srv/a -> b|/mnt/nas +f|srv/a -> b/f.txt|644|x +l|gl*b[1]|/mnt/nas +f|gl*b[1]/g|644|g' +SETUP='mkdir -p /mnt/nas' sbx -y "$ZA" +t_eq 'odd link names: restore succeeds' 0 "$RC" +t_true 'link whose name contains " -> " is kept' node '/srv/a -> b' l /mnt/nas +t_true 'link whose name has glob characters is kept' node '/gl*b[1]' l /mnt/nas +t_true 'content below the odd link names lands in the target' node /mnt/nas/f.txt f +t_true 'content below the glob-named link lands in the target' node /mnt/nas/g f + +sbmk "$GEN_SPEC +l|srv/media|/mnt/nas +f|srv/media/a.txt|644|a" +SETUP='mkdir -p /srv/sub /mnt/nas; echo old >/srv/old.txt' sbx -n "$ZA" +t_eq 'dry run: exit 0' 0 "$RC" +t_has 'dry run: says nothing was written' "$LOG" 'Dry run: nothing was written.' +t_eq 'dry run: the fake root is byte-identical afterwards' "$TREE0" "$TREE" + +sbmk 'f|srv/mediagarrd.db|644|db' +sbx -n "$ZA" +t_has 'sandbox: database warning' "$LOG" 'warning: archive contains mediagarrd.db' + +sbmk 'f|a.txt|644|a' +SB_UID=1000 sbx -n "$ZA" +t_eq 'non-root: dry run succeeds' 0 "$RC" +t_has 'non-root: warning about owners' "$LOG" 'warning: not running as root: owners cannot be restored' + +sbmk 'f|a.txt|644|a' +sbx -n "$ZA" +t_lacks 'root: no non-root warning' "$LOG" 'not running as root' + +sbmk 'f|a.txt|644|a' +sbx "$ZA" +t_eq 'no tty and no -y: refused' 1 "$RC" +t_has 'no tty and no -y: explained' "$LOG" 'no terminal to ask for confirmation; use --yes' +t_eq 'no tty and no -y: nothing written' "$TREE0" "$TREE" + +sbmk 'f|bin/su|4755|x +f|bin/sg|2755|x +f|bin/plain|644|x +l|bin/ln|/mnt/x +f|bin/ln/f|644|f' +SETUP='mkdir -p /r' sbx -C /r -y "$ZA" +t_eq 'root under -C: restore succeeds' 0 "$RC" +t_has 'root under -C: setuid warning' "$LOG" 'warning: running as root: setuid/setgid files from the archive keep their bits under /r' +t_true 'root under -C: setuid bit kept' node /r/bin/su f +t_eq 'root under -C: setuid and setgid modes' '2755 4755' "$(awk -F'|' '$1 == "/r/bin/su" || $1 == "/r/bin/sg" { printf "%s%s", s, $3; s = " " }' <<<"$TREE")" +t_true 'root under -C: no link created' node /r/bin/ln d +t_eq 'root under -C: nothing outside /r except the root dir' '' "$(awk -F'|' 'index($0, "|") && $1 != "/r" && index($1, "/r/") != 1 { print $1 }' <<<"$TREE")" +t_eq 'root under -C: files are owned by uid 0 in the sandbox' '0' "$(awk -F'|' '$1 == "/r/bin/plain" { print $4 }' <<<"$TREE")" + +finish diff --git a/tests/unit.sh b/tests/unit.sh new file mode 100644 index 0000000..f3e47a5 --- /dev/null +++ b/tests/unit.sh @@ -0,0 +1,173 @@ +#!/usr/bin/env bash +# shellcheck disable=SC2034 +# shellcheck source=lib.sh +source "$(dirname -- "${BASH_SOURCE[0]}")/lib.sh" +# shellcheck source=/dev/null +source "$SCRIPT" +set +euo pipefail +export LC_ALL=C.UTF-8 + +declare -A KP=() + +t_eq 'pat escapes regex and glob specials' '^a.b\*\[c\]\\d\$\^\?$' "$(printf '%s\n' 'a.b*[c]\d$^?' | pat '^' '$')" +t_eq 'pat keeps spaces and applies prefix and suffix' 'x y/*' "$(printf '%s\n' 'x y' | pat '' '/*')" +t_eq 'pat handles one pattern per line' $'^a/\n^b c/' "$(printf '%s\n' a 'b c' | pat '^' /)" + +KP=() +mp 'a/b/c'; t_eq 'mp without kept links is the identity' 'a/b/c' "$MP" +mp ''; t_eq 'mp of an empty path is empty' '' "$MP" +KP=([srv/media]=mnt/nas) +mp srv/media; t_eq 'mp maps a kept link to its target' mnt/nas "$MP" +mp srv/media/a/b; t_eq 'mp maps paths below a kept link' mnt/nas/a/b "$MP" +mp srv/other/a; t_eq 'mp leaves unrelated paths alone' srv/other/a "$MP" +mp srv/mediax; t_eq 'mp matches whole components only' srv/mediax "$MP" +KP=([a]=b [b/c]=d) +mp a/c/e; t_eq 'mp resolves through a chain of kept links' d/e "$MP" +KP=([srv/b]=mnt/nas [srv/a]=mnt/nas/x) +mp srv/a/y; t_eq 'mp resolves a link that points through a kept link' mnt/nas/x/y "$MP" + +fresh +AD=$C/awk +awk_on() { + rm -rf "$AD"; mkdir -p "$AD" + mkzip "$Z" + bsdtar -tf "$Z" >"$AD/n" 2>/dev/null + bsdtar --numeric-owner -tvf "$Z" >"$AD/v" 2>/dev/null + chk "$AD" >/dev/null 2>&1 + ARC=$? + ASTATS='' + if [[ -f $AD/stats ]]; then ASTATS=$(<"$AD/stats"); fi +} +lf() { LN=$1 awk -F"$SEP" -v n="$2" '$2 == ENVIRON["LN"] { print $n }' "$AD/links.raw"; } +numeric() { [[ $1 =~ ^[0-9]+$ && $2 =~ ^[0-9]+$ ]]; } + +awk_on <<'EOF2' +f|srv/a.txt|644|hello +d|srv/dir +l|srv/l|/mnt +EOF2 +t_eq 'awk accepts canonical names' 0 "$ARC" +t_eq 'awk counts entries and bytes' '3 5 0 0' "$ASTATS" +t_eq 'awk lists non-link entries and their parents as provided paths' $'srv\nsrv/a.txt\nsrv/dir' "$(LC_ALL=C sort "$AD/prov")" + +awk_on <<'EOF2' +f|srv/mediagarrd.db|644|db +EOF2 +t_eq 'awk flags mediagarrd.db' '1 2 1 0' "$ASTATS" +awk_on <<'EOF2' +f|srv/mediagarrd.db.bak|644|db +f|srv/xmediagarrd.db|644|db +EOF2 +t_eq 'awk does not flag lookalike names' '2 4 0 0' "$ASTATS" + +for spec in 'f|../evil' 'f|a/../b' 'f|a/..' 'f|/abs/x' 'f|a//b' 'f|a/./b' 'f|./a' 'f|a\tb' 'f|a\x07b' 'f|a\nb' 'f|x/\x1b[2J'; do + awk_on <<<"$spec" + t_eq "awk rejects ${spec#f|}" 3 "$ARC" + t_true "awk writes no provided list for ${spec#f|}" test ! -e "$AD/prov" +done +awk_on <<<'l|a/b|../../x' +t_eq 'awk accepts relative link targets with ..' 0 "$ARC" +awk_on <<<'f|dir/we\\ird|644|b' +t_eq 'awk accepts a backslash in a name' 0 "$ARC" +t_eq 'awk counts the backslash name' '1 1 0 0' "$ASTATS" +awk_on <<<'l|a/we\\ird|/mnt/x' +t_eq 'awk keeps a backslash in a link name' 0 "$ARC" +t_eq 'awk reads the target of a link with a backslash name' /mnt/x "$(lf 'a/we\ird' 3)" + +awk_on <<<'l|srv/a -> b|/mnt/x -> y' +t_eq 'awk parses names and targets containing " -> "' '/mnt/x -> y' "$(lf 'srv/a -> b' 3)" + +awk_on <<'EOF2' +l|l1|l2 +l|l2|/abs/dir +EOF2 +t_eq 'chain l1 -> l2 -> /abs/dir resolves to the final path' abs/dir "$(lf l1 4)" +t_eq 'chain l1 is ok' 1 "$(lf l1 5)" +t_eq 'chain l2 resolves to the same path' abs/dir "$(lf l2 4)" + +awk_on <<'EOF2' +l|a|b +l|b|a +EOF2 +t_eq 'link loop is not ok' 0 "$(lf a 5)" + +awk_on <<'EOF2' +l|l0|l1 +l|l1|l2 +l|l2|l3 +l|l3|l4 +l|l4|l5 +l|l5|l6 +l|l6|l7 +l|l7|l8 +l|l8|l9 +l|l9|/x +EOF2 +t_eq 'chain of 9 hops is not ok' 0 "$(lf l0 5)" +t_eq 'chain of 8 hops is ok' 1 "$(lf l1 5)" + +awk_on <<'EOF2' +l|srv/a|../x/y +l|srv/b|./c/../d +l|srv/c|/p//q/./r/.. +l|d|. +l|x|d/d/../../.. +EOF2 +t_eq 'relative target with .. is normalized' x/y "$(lf srv/a 4)" +t_eq 'relative target with . and .. is normalized' srv/d "$(lf srv/b 4)" +t_eq 'absolute target is normalized' p/q "$(lf srv/c 4)" +t_eq 'link to . resolves to the root' '' "$(lf d 4)" +t_eq 'escaping relative target cannot climb above the root' '' "$(lf x 4)" + +awk_on <<'EOF2' +l|srv/b|/mnt/nas +l|srv/a|b/x +EOF2 +t_eq 'rank of a link with no link in its path is 0' 0 "$(lf srv/b 1)" +t_eq 'rank of a link pointing through another link is 1' 1 "$(lf srv/a 1)" +t_eq 'relative target through a link is resolved by name' srv/b/x "$(lf srv/a 4)" +awk_on <<'EOF2' +l|srv/media|/mnt/nas +l|srv/media/lib|/mnt/lib +l|srv/media/lib/deep|/mnt/deep +EOF2 +t_eq 'rank counts links in the parent path' 1 "$(lf srv/media/lib 1)" +t_eq 'rank increases with each level' 2 "$(lf srv/media/lib/deep 1)" + +awk_on <<'EOF2' +l|srv/m|/mnt/nas +f|srv/m/a|644|a +f|mnt/nas/q|644|q +l|srv/n|/mnt/none +EOF2 +t_eq 'link target provided by the archive is flagged' 1 "$(lf srv/m 6)" +t_eq 'link with entries below it has children' 1 "$(lf srv/m 7)" +t_eq 'link target not in the archive is not flagged' 0 "$(lf srv/n 6)" +t_eq 'link without entries below it has no children' 0 "$(lf srv/n 7)" +t_true 'owner and group columns are numeric' numeric "$(lf srv/m 8)" "$(lf srv/m 9)" + +run_cli() { OUT=$(bash "$SCRIPT" "$@" 2>&1 "$C/file" +run_cli -C "$C/file" -n "$Z"; t_eq 'a root that is a file is rejected' 1 "$RC"; t_has 'it is explained' "$OUT" 'not a directory' + +OUT=$(bash -s -- -C "$R" -h <"$SCRIPT" 2>&1); RC=$? +t_eq 'script read from stdin: -h exits 0' 0 "$RC"; t_has 'script read from stdin: usage printed' "$OUT" 'Usage:' +OUT=$(bash -s -- -C "$R" --bogus <"$SCRIPT" 2>&1); RC=$? +t_eq 'script read from stdin: bad option exits 2' 2 "$RC" +OUT=$(bash -c "$(<"$SCRIPT")" mgrecover -C "$R" --bogus 2>&1); RC=$? +t_eq 'script run through bash -c: bad option exits 2' 2 "$RC" + +finish