#!/bin/sh
# =============================================================================
# autopkgtest "tcp": daemon handling, waiting and certificates, tested against
# a mock echo server written in python3.
#
# The mock server (debian/tests/data/echo-server.py) echoes every line back
# and can listen on a TCP port, on a unix socket, with TLS, and optionally
# daemonize itself.  The client (echo-client.py) sends one line and prints the
# reply.  Together they stand in for "a real daemon" such as a proxy or SMTP
# server, so the library's start/wait/stop logic can be tested without one.
#
# HOW TO ADAPT THIS FILE
#  * This is also the best template for your own tests: start a daemon with
#    fx_start, wait for it with fx_wait_listen / fx_wait_socket, talk to it,
#    and let the library stop it.
#  * To test another daemon, replace "python3 $SERVER ..." in the fx_start
#    lines with its command line.  The daemon must stay in the foreground; if
#    it insists on forking, start it normally and use fx_adopt with its
#    pidfile (see the "forking daemon" block).
#  * Run from a checkout:  FX_LIBDIR=$PWD/lib sh debian/tests/tcp
# =============================================================================
set -eu

LIB="${FX_LIBDIR:-/usr/share/autopkgtest-helper}"
export FX_LIBDIR="$LIB"
. "$LIB/fixtures.sh"
fx_init

# autopkgtest runs tests with the source tree as the current directory.
D="$(pwd)/debian/tests/data"
SERVER="$D/echo-server.py"
CLIENT="$D/echo-client.py"
T=$FX_ROOT/selftest
mkdir "$T"

# port_closed PORT: true when nothing listens on PORT (for use with fx_wait_cmd,
# which can only wait for a command to SUCCEED).
port_closed() { ! fx_is_listening "$1"; }

# expect_echo MESSAGE CLIENT-ARGS...
# Send MESSAGE through the echo client and require the identical reply.
expect_echo() {
    _msg=$1
    shift
    _got=$("$CLIENT" "$@" "$_msg") || fx_fail "client failed: $*"
    [ "$_got" = "$_msg" ] || fx_fail "expected '$_msg', got '$_got'"
}

# ---------------------------------------------------------------------------
fx_step "plain TCP: fx_free_port, fx_start, fx_wait_listen"
# Pick a port nobody listens on, start the server there and wait until it
# actually accepts connections.  Never "sleep N" instead of waiting: that is
# either too slow or too fast depending on the testbed.
port=$(fx_free_port)
fx_is_listening "$port" && fx_fail "fresh port $port already in use"
fx_start echo python3 "$SERVER" --port "$port"
fx_wait_listen "$port" 10 || fx_fail "server did not start listening"
fx_is_listening "$port" || fx_fail "fx_is_listening disagrees with fx_wait_listen"
expect_echo "hello fixtures" --host 127.0.0.1 --port "$port"
# While our server holds $port, fx_free_port must never hand it out again.
other=$(fx_free_port)
[ "$other" != "$port" ] || fx_fail "fx_free_port returned a port in use"
# fx_start captured the server's stderr in $FX_LOGDIR/echo.log.
fx_assert_contains "$FX_LOGDIR/echo.log" "listening"

# ---------------------------------------------------------------------------
fx_step "fx_stop closes the port"
fx_stop echo
# The kernel may need a moment to close the listener, so poll.
fx_wait_cmd 5 port_closed "$port" || fx_fail "port $port still open after fx_stop"
expect_failed=0
"$CLIENT" --host 127.0.0.1 --port "$port" x >/dev/null 2>&1 || expect_failed=1
[ "$expect_failed" -eq 1 ] || fx_fail "client could still connect after fx_stop"

# ---------------------------------------------------------------------------
fx_step "fx_wait_listen times out when nothing listens"
# A broken daemon must make the test fail quickly, not hang forever.
start=$(date +%s)
fx_wait_listen "$port" 1 && fx_fail "fx_wait_listen succeeded on a closed port"
[ $(($(date +%s) - start)) -le 3 ] || fx_fail "fx_wait_listen took far too long"

# ---------------------------------------------------------------------------
fx_step "unix socket: fx_wait_socket"
# Unix sockets avoid port races entirely; use them whenever the daemon allows.
fx_start echo-unix python3 "$SERVER" --unix "$T/echo.sock"
fx_wait_socket "$T/echo.sock" 10 || fx_fail "unix socket did not appear"
expect_echo "over unix socket" --unix "$T/echo.sock"
fx_stop echo-unix

# ---------------------------------------------------------------------------
fx_step "forking daemon: fx_adopt"
# Some daemons detach themselves.  Start them by hand, then hand the pidfile
# to fx_adopt so that teardown still stops them.
port=$(fx_free_port)
python3 "$SERVER" --port "$port" --daemonize "$T/echo.pid"
fx_adopt forker "$T/echo.pid"
fx_wait_listen "$port" 10 || fx_fail "daemonized server not listening"
expect_echo "from a forked daemon" --host 127.0.0.1 --port "$port"
pid=$(cat "$FX_RUNDIR/forker.pid")
fx_stop forker
fx_alive "$pid" && fx_fail "adopted daemon survived fx_stop"

# ---------------------------------------------------------------------------
fx_step "TLS: fx_cert chain is accepted by a verifying client"
# The server presents a certificate from fx_cert.  The client verifies it
# against the library's CA ($FX_CA_CERT) AND checks the host name "localhost",
# which only works if the SANs were generated correctly.
fx_cert echo.test DNS:echo.test DNS:localhost IP:127.0.0.1
port=$(fx_free_port)
fx_start echo-tls python3 "$SERVER" --port "$port" \
    --tls "$FX_CERTDIR/echo.test.crt" "$FX_CERTDIR/echo.test.key"
fx_wait_listen "$port" 10 || fx_fail "TLS server not listening"
expect_echo "secret hello" --host localhost --port "$port" --cafile "$FX_CA_CERT"
# Negative check: a client that trusts only an unrelated certificate must
# reject the server.  Without this, the positive check above could pass
# because verification is accidentally switched off.
fx_cert other.test DNS:other.test
cp "$FX_CERTDIR/other.test.crt" "$T/other.crt"
if "$CLIENT" --host localhost --port "$port" --cafile "$T/other.crt" x >/dev/null 2>&1; then
    fx_fail "client accepted a server certificate it does not trust"
fi
fx_stop echo-tls

# ---------------------------------------------------------------------------
fx_step "failing test leaves no server behind"
# The most important property for a testbed: even if a test dies in the
# middle, no daemon keeps running.  The child starts a server, then exits
# with status 3; we check the status is kept and the port is closed.
# Escaped variables (\$p) are expanded by the child, others right here.
cat >"$T/leak.sh" <<SUB
set -e
. "$LIB/fixtures.sh"
fx_init
p=\$(fx_free_port)
fx_start leak python3 "$SERVER" --port "\$p"
fx_wait_listen "\$p" 10
echo "\$p" >"$T/leak.port"
exit 3
SUB
rc=0
sh "$T/leak.sh" 2>/dev/null || rc=$?
[ "$rc" -eq 3 ] || fx_fail "leak.sh exit status $rc, expected 3"
fx_is_listening "$(cat "$T/leak.port")" && fx_fail "server survived failed test"

echo "tcp: all tests passed"
