# What the guest's network looks like from the host. The argv tests say
# what vmm asked for; these say what the kernel then did with it. The
# guest is emulated, so this file needs no accelerator.
#
# /proc/net/tcp lists the local address as ADDRESS:PORT in hex, the
# address little endian, the port big endian, and state 0A is LISTEN.
# 127.0.0.1 is 0100007F and 0.0.0.0 is 00000000.

port=18022
hex=$(printf '%04X' "$port")

"$VMM" create nt1 64M >/dev/null 2>&1
cfg nt1 <<EOF
MEM=256
CPUS=1
HWACCEL=no
HOSTFWD="$port:22"
EOF

if grep -qi ":$hex " /proc/net/tcp; then
	skip 3 "port $port is already in use on this host"
elif ! "$VMM" start nt1 >/dev/null 2>&1; then
	skip 3 "nt1 did not start"
else
	holds "the two field form really listens" \
		grep -qi ":$hex .* 0A " /proc/net/tcp
	holds "and on 127.0.0.1, not on every interface" \
		grep -qi "0100007F:$hex " /proc/net/tcp
	"$VMM" kill nt1 >/dev/null 2>&1 || :
	holds "and stops listening once the guest is gone" \
		test -z "$(grep -i ":$hex .* 0A " /proc/net/tcp || :)"
fi

cfg nt1 <<EOF
MEM=256
CPUS=1
HWACCEL=no
HOSTFWD="0.0.0.0:$port:22"
EOF

if grep -qi ":$hex " /proc/net/tcp; then
	skip 1 "port $port is already in use on this host"
elif ! "$VMM" start nt1 >/dev/null 2>&1; then
	skip 1 "nt1 did not start"
else
	holds "an explicit address is bound as written" \
		grep -qi "00000000:$hex " /proc/net/tcp
	"$VMM" kill nt1 >/dev/null 2>&1 || :
fi

# Every file the guest leaves in its directory is 0600 as well, FIFOs
# included: the monitor is reachable by anyone who can write qmp.in.
cfg nt1 <<EOF
MEM=256
CPUS=1
HWACCEL=no
EOF
if "$VMM" start nt1 >/dev/null 2>&1; then
	# shellcheck disable=SC2012  # the names are vmm's own, not user input
	bad=$(ls -l "$VMMDIR/nt1" |
		awk '$1 ~ /^[-p]/ && $1 !~ /^[-p]rw-------$/ { print $NF }')
	if [ -z "$bad" ]; then
		ok "a running guest leaves every file 0600"
	else
		notok "a running guest leaves every file 0600" "$bad"
	fi
	"$VMM" kill nt1 >/dev/null 2>&1 || :
else
	skip 1 "nt1 did not start"
fi
