interplane.Get Omega
Read in your language

interplane-forge

INTERPLANE Forge

Brought by drakestapleton

branch main Branches Tags History

interplane-forge / research / decode.sh

175 lines · 9096 bytes Raw Blame History
1#!/bin/sh
2# Approved host-migration adapter: systemd/bwrap/poppler perform isolation and IO.
3# Success installs a new output; every refusal leaves that destination absent.
4# Existing destinations are refused, never removed or followed.
5# Omega successor: process-tree resource and isolated decoder host words; this is
6# not an Omega decoder. No unit file, daemon or persistent manager setting exists.
7exec /usr/bin/env -i PATH=/usr/bin:/bin LC_ALL=C \
8 XDG_RUNTIME_DIR="/run/user/$(/usr/bin/id -u)" \
9 DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$(/usr/bin/id -u)/bus" \
10 /bin/sh -s -- "$@" <<'DECODE'
11set -eu
12umask 077
13refuse() { printf 'research decode: %s\n' "$*" >&2; exit 1; }
14[ "$#" = 2 ] || refuse 'usage: decode.sh INPUT OUTPUT'
15[ -f "$1" ] && [ ! -L "$1" ] || refuse 'input is not a regular nonsymlink file'
16input=$(realpath -e -- "$1") || refuse 'input path unavailable'
17[ ! -e "$2" ] && [ ! -L "$2" ] || refuse 'output already exists'
18outdir=$(dirname -- "$2")
19outdir=$(realpath -e -- "$outdir") || refuse 'output directory unavailable'
20output=$outdir/$(basename -- "$2")
21for tool in systemd-run systemctl bwrap pdftotext timeout dd head mkfifo; do
22 [ -x "/usr/bin/$tool" ] || refuse "required tool unavailable: $tool"
23done
24[ -S "$XDG_RUNTIME_DIR/bus" ] || refuse 'user scope unavailable: no user manager bus'
25# A fresh per-invocation nonce no earlier unit can carry. Only the nonce enters
26# the manager (scope Description); no path or metadata leaves private staging.
27nonce=$(cat /proc/sys/kernel/random/uuid) || refuse 'cannot draw scope ownership nonce'
28case $nonce in *[!0-9a-f-]*|'') refuse 'scope ownership nonce malformed' ;; esac
29description="interplane research pdf decoder $nonce"
30work=$(mktemp -d "$outdir/.interplane-research-pdf.XXXXXXXXXX") || refuse 'cannot stage output'
31unit=interplane-research-pdf-${work##*.}.scope
32runner=; errreader=; owned=0; invocation=
33# The name alone proves nothing: a unit of that name may predate this run, and a
34# failed creation must leave it untouched. owned is set only by prove_scope
35# below, after the manager created the scope and the claimant inside it was
36# bound to this run. Stop only while the name still resolves to that exact
37# manager InvocationID, never a unit that replaced ours after it ended.
38owns_scope() {
39 [ "$owned" = 1 ] || return 1
40 current=$(/usr/bin/timeout --kill-after=1s 5s /usr/bin/systemctl --user show \
41 --property=InvocationID --value -- "$unit" 2>/dev/null) || return 1
42 [ "$current" = "$invocation" ]
43}
44# All descendants of an owned scope are killed, including a decoder that forks
45# or changes its process group.
46stop_scope() {
47 owns_scope || return 0
48 /usr/bin/timeout --kill-after=1s 5s /usr/bin/systemctl --user stop "$unit" >/dev/null 2>&1 || :
49}
50cleanup() {
51 stop_scope
52 if [ -n "$runner" ]; then kill "$runner" 2>/dev/null || :; wait "$runner" 2>/dev/null || :; fi
53 if [ -n "$errreader" ]; then kill "$errreader" 2>/dev/null || :; wait "$errreader" 2>/dev/null || :; fi
54 rm -rf -- "$work"
55}
56trap cleanup EXIT
57trap 'refuse interrupted' HUP INT TERM
58# The claimant is the process systemd-run became after the manager created the
59# scope. Its parent must be this run's own unreaped launcher ($runner), and its
60# cgroup is read before and after the manager reports the unit, so the reported
61# identity belongs to the live unit holding the claimant at that moment.
62claimant_cgroup() {
63 stat=$(cat "/proc/$1/stat" 2>/dev/null) || return 1
64 set -- "$1" ${stat##*) }
65 [ "$#" -ge 3 ] && [ "$3" = "$runner" ] || return 1
66 cg=$(sed -n 's/^0:://p' "/proc/$1/cgroup" 2>/dev/null) || return 1
67 [ -n "$cg" ] || return 1
68 printf '%s\n' "$cg"
69}
70prove_scope() {
71 case $1 in ''|*[!0-9]*) return 1 ;; esac
72 before=$(claimant_cgroup "$1") || return 1
73 shown=$(/usr/bin/timeout --kill-after=1s 5s /usr/bin/systemctl --user show \
74 --property=Id,Description,InvocationID,ControlGroup,ActiveState -- "$unit" 2>/dev/null) || return 1
75 after=$(claimant_cgroup "$1") || return 1
76 [ "$before" = "$after" ] || return 1
77 id=; desc=; inv=; cgroup=; state=
78 while IFS= read -r line; do
79 case $line in
80 Id=*) id=${line#Id=} ;;
81 Description=*) desc=${line#Description=} ;;
82 InvocationID=*) inv=${line#InvocationID=} ;;
83 ControlGroup=*) cgroup=${line#ControlGroup=} ;;
84 ActiveState=*) state=${line#ActiveState=} ;;
85 esac
86 done <<SHOWN
87$shown
88SHOWN
89 [ "$id" = "$unit" ] && [ "$desc" = "$description" ] && [ "$cgroup" = "$before" ] &&
90 [ "$state" = active ] || return 1
91 case $inv in *[!0-9a-f]*) return 1 ;; esac
92 [ "${#inv}" = 32 ] || return 1
93 invocation=$inv; owned=1
94}
95mkfifo "$work/stdout" "$work/stderr" "$work/claim" "$work/release" || refuse 'cannot create extraction pipes'
96# Decoder diagnostics are hostile too: save only a bounded prefix, drain the
97# remainder without disk IO, and preserve the launcher's exact property errors.
98{ head -c 4096; cat >/dev/null; } < "$work/stderr" > "$work/diagnostic" &
99errreader=$!
100# This shell holds the only writer of the release gate: if it refuses or dies
101# before releasing, the claimant reads end of file and exits without decoding.
102exec 7<>"$work/release"
103printf 'research decode: scope=%s MemoryMax=128M MemorySwapMax=0 TasksMax=8 timeout=30s stdout_max=8388607\n' "$unit" >&2
104# Eight tasks allow timeout, bwrap's namespace supervisor and the single-threaded
105# poppler decoder plus startup headroom. 128M is a containment policy for public
106# PDFs, not a promise that every legitimate PDF can be extracted.
107# The outer deadline also contains a stuck manager RPC. The inner deadline and
108# PID namespace contain decoder descendants. Scope creation MUST NOT fall back.
109# The claimant execs in place (no extra task): it reports its PID, then waits
110# for release before the decoder starts.
111/usr/bin/timeout --kill-after=2s 35s \
112 /usr/bin/systemd-run --user --scope --collect --quiet --unit="$unit" \
113 -p MemoryMax=128M -p MemorySwapMax=0 -p TasksMax=8 -p KillMode=control-group \
114 --description="$description" \
115 /bin/sh -c 'printf "%s\n" "$$" >&5 && exec 5>&- && IFS= read -r gate <&7 && [ "$gate" = release ] && exec 7<&- "$@"' interplane-research-claim \
116 /usr/bin/env -i PATH=/usr/bin:/bin LC_ALL=C \
117 /usr/bin/timeout --kill-after=2s 30s \
118 /usr/bin/bwrap --unshare-all --die-with-parent --new-session --cap-drop ALL \
119 --clearenv --setenv PATH /usr/bin:/bin --setenv LC_ALL C --setenv PWD / \
120 --ro-bind /usr /usr --symlink usr/lib /lib --symlink usr/bin /bin \
121 --proc /proc --dev /dev --tmpfs /tmp --dir /home --chdir / \
122 --ro-bind "$input" /paper.pdf \
123 /usr/bin/pdftotext -enc UTF-8 /paper.pdf - \
124 5> "$work/claim" 7< "$work/release" < /dev/null > "$work/stdout" 2> "$work/stderr" &
125runner=$!
126# Open order matches the launcher's redirections, so neither side blocks. A
127# launch that never reaches the claimant (name collision, manager refusal,
128# deadline) closes every claim writer: the read sees end of file.
129exec 5< "$work/claim" 6< "$work/stdout"
130claim=; IFS= read -r claim <&5 || :
131exec 5<&-
132if ! prove_scope "$claim"; then
133 exec 7>&- 6<&-
134 rc=0; wait "$runner" || rc=$?; runner=
135 wait "$errreader" || :; errreader=
136 printf 'research decode: scope %s was not proven created by this invocation status=%s; it was not stopped; staged text discarded; diagnostic follows\n' "$unit" "$rc" >&2
137 cat "$work/diagnostic" >&2
138 exit 1
139fi
140printf 'release\n' >&7
141exec 7>&-
142# One shared pipe descriptor: dd consumes no byte beyond count; the sentinel is
143# counted in memory, never appended to staged text. A pipeline's last exit code
144# must not hide the actual producer status (wait below).
145sink=0; extra=0
146{
147 dd bs=65536 count=8388607 iflag=count_bytes,fullblock status=none > "$work/plain" || sink=$?
148 if [ "$sink" = 0 ]; then
149 extra=$(dd bs=1 count=1 status=none | wc -c) || sink=$?
150 fi
151} <&6
152exec 6<&-
153if [ "$sink" != 0 ] || [ "$extra" != 0 ]; then stop_scope; fi
154rc=0; wait "$runner" || rc=$?; runner=
155# Successful launch exit is insufficient if an escaped descendant remains.
156stop_scope
157remaining=$(/usr/bin/timeout --kill-after=1s 5s /usr/bin/systemctl --user show \
158 --property=InvocationID,ActiveState -- "$unit") || refuse 'cannot verify extraction scope stopped'
159case $remaining in
160 *"InvocationID=$invocation"*)
161 case $remaining in *ActiveState=inactive*|*ActiveState=failed*) ;; *) refuse 'extraction scope did not stop' ;; esac ;;
162esac
163wait "$errreader" || :; errreader=
164if [ "$extra" != 0 ]; then refuse "output limit exceeded (8388607 bytes); staged_bytes=$(wc -c < "$work/plain"); staged text discarded"; fi
165[ "$sink" = 0 ] || refuse 'bounded output pipe/write failed; staged text discarded'
166if [ "$rc" != 0 ]; then
167 printf 'research decode: decoder/scope failed status=%s; staged text discarded; diagnostic follows\n' "$rc" >&2
168 cat "$work/diagnostic" >&2
169 exit 1
170fi
171[ -s "$work/plain" ] || refuse 'decoder produced no text'
172# ln is atomic and cannot overwrite a destination created since the first check.
173ln -- "$work/plain" "$output" || refuse 'output installation failed'
174printf 'research decode: extracted bytes=%s\n' "$(wc -c < "$work/plain")" >&2
175DECODE