#!/bin/bash
#
# Copyright (C) 2026 Nikos Mavrogiannopoulos
#
# This file is part of ocserv.
#
# ocserv is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at
# your option) any later version.
#
# ocserv is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# REQ-WORKER-NET-010, REQ-WORKER-NET-011 (#774): a client-initiated DTLS
# rehandshake completes; one that stalls does not hold up the worker,
# which keeps the session on CSTP, ends the DTLS session once the
# handshake times out, and accepts a new DTLS session afterwards.
#
# Method: rekey-method = ssl makes the client rehandshake DTLS every
# rekey-time + 10 seconds. After a first rehandshake completes, an nft
# set in the client namespace lets the first DTLS handshake record of
# the next rehandshake reach the server and then drops all UDP between
# them, so the server is left waiting in the middle of the handshake.

OCCTL="${OCCTL:-../src/occtl/occtl}"
SERV="${SERV:-../src/ocserv}"
srcdir=${srcdir:-.}
PIDFILE=ocserv-pid.$$.tmp
CLIPID=oc-pid.$$.tmp
OUTFILE=dtls-rehandshake.$$.tmp
OCCTL_SOCKET=./occtl-dtls-rehandshake-$$.socket
NFT_TABLE=ocserv_dtls_rehsk_$$
PATH=${PATH}:/usr/sbin

. "$(dirname "$0")"/common.sh

eval "${GETPORT}"

if test "$(id -u)" != "0"; then
	echo "This test must be run as root"
	exit 77
fi

if ! command -v nft >/dev/null 2>&1; then
	echo "This test requires nft"
	exit 77
fi

if ! command -v jq >/dev/null 2>&1; then
	echo "This test requires jq"
	exit 77
fi

function finish {
	echo " * Cleaning up..."
	test -n "${CMDNS1}" && ${CMDNS1} nft delete table ip ${NFT_TABLE} >/dev/null 2>&1
	cleanup_client_server
	if test "$VERBOSE" = 1 && test -f "${OUTFILE}"; then
		cat "${OUTFILE}"
	fi
	rm -f "${OUTFILE}"
}
trap finish EXIT

. "$(dirname "$0")"/random-net.sh
. "$(dirname "$0")"/ns.sh

set +e

update_config dtls-rehandshake.config
${CMDNS2} ${SERV} -p ${PIDFILE} -f -c ${CONFIG} -d 3 >${OUTFILE} 2>&1 & PID=$!

sleep 3

worker_id() {
	${OCCTL} -s "${OCCTL_SOCKET}" -j show user test 2>/dev/null | jq -r '.[0].ID' 2>/dev/null
}

log_count() {
	grep -c "$1" "${OUTFILE}"
}

# wait_for COND SECONDS: run COND every second until it succeeds
wait_for() {
	local i
	for i in $(seq 1 "$2"); do
		eval "$1" && return 0
		sleep 1
	done
	return 1
}

echo " * Connecting to ${ADDRESS}:${PORT}..."
echo "test" | ${CMDNS1} ${OPENCONNECT} \
	${ADDRESS}:${PORT} \
	-u test \
	--passwd-on-stdin \
	--servercert=pin-sha256:xp3scfzy3rOQsv9NcOve/8YVVv+pHr4qNCXEXrNl5s8= \
	-s "${srcdir}/scripts/vpnc-script" \
	--pid-file="${CLIPID}" \
	-b
if test $? != 0; then
	fail $PID "FAIL: could not connect to the server"
fi

if ! wait_for 'test "$(log_count "DTLS handshake completed")" -ge 1' 15; then
	fail $PID "FAIL: expected a DTLS session, got none in the server log"
fi

WID=$(worker_id)
if test -z "${WID}" || test "${WID}" = "null"; then
	fail $PID "FAIL: expected a worker ID from occtl, got '${WID}'"
fi
echo " * Worker ID: ${WID}"

echo " * Waiting for a DTLS rehandshake to complete..."
if ! wait_for 'test "$(log_count "DTLS rehandshake completed")" -ge 1' 45; then
	fail $PID "FAIL: expected a completed DTLS rehandshake, got $(log_count "client requested rehandshake on DTLS channel") request(s) and none completed"
fi

if ! ${CMDNS1} ping -c 3 ${VPNADDR}; then
	fail $PID "FAIL: expected pings to succeed after the DTLS rehandshake, they failed"
fi

# The first DTLS handshake record (content type 22) sent to the server
# adds it to the set; from then on UDP to and from it is dropped.
echo " * Stalling the next DTLS rehandshake..."
REQUESTS=$(log_count "client requested rehandshake on DTLS channel")
${CMDNS1} nft -f - <<EOF
table ip ${NFT_TABLE} {
	set stalled {
		type ipv4_addr
		flags dynamic
	}
	chain out {
		type filter hook output priority 0;
		ip daddr @stalled udp dport ${PORT} drop
		udp dport ${PORT} @th,64,8 22 add @stalled { ip daddr }
	}
	chain in {
		type filter hook input priority 0;
		ip saddr @stalled udp sport ${PORT} drop
	}
}
EOF
if test $? != 0; then
	fail $PID "FAIL: could not install the nft rules"
fi

if ! wait_for 'test "$(log_count "client requested rehandshake on DTLS channel")" -gt ${REQUESTS}' 45; then
	fail $PID "FAIL: expected the server to receive another DTLS rehandshake request, got none"
fi
STALLED_AT=$(date +%s)

# A worker that waits for the rehandshake to finish forwards nothing.
echo " * Pinging while the rehandshake is stalled..."
OK_PINGS=0
for i in $(seq 1 6); do
	${CMDNS1} ping -c 1 -W 3 ${VPNADDR} >/dev/null && OK_PINGS=$((OK_PINGS + 1))
	sleep 2
done
if test ${OK_PINGS} -lt 3; then
	fail $PID "FAIL: expected at least 3 of 6 pings to succeed during the stalled rehandshake, got ${OK_PINGS}"
fi

NEW_WID=$(worker_id)
if test "${NEW_WID}" != "${WID}"; then
	fail $PID "FAIL: expected worker ID ${WID} during the stalled rehandshake, got '${NEW_WID}'"
fi

# The 60s GnuTLS handshake timeout, noticed by periodic_check() within
# PERIODIC_CHECK_TIME (30s) plus the 10s maintenance timer period.
echo " * Waiting for the stalled rehandshake to time out..."
if ! wait_for 'grep -q "error in DTLS handshake: .*timed out" "${OUTFILE}"' $((STALLED_AT + 110 - $(date +%s))); then
	fail $PID "FAIL: expected 'error in DTLS handshake' with a timeout within 110s of the stall, got none after $(($(date +%s) - STALLED_AT))s"
fi
echo " * Timed out $(($(date +%s) - STALLED_AT))s after the stall"

NEW_WID=$(worker_id)
if test "${NEW_WID}" != "${WID}"; then
	fail $PID "FAIL: expected worker ID ${WID} after the rehandshake timed out, got '${NEW_WID}'"
fi

echo " * Removing the nft rules, waiting for a new DTLS session..."
HANDSHAKES=$(log_count "DTLS handshake completed")
${CMDNS1} nft delete table ip ${NFT_TABLE}

if ! wait_for 'test "$(log_count "DTLS handshake completed")" -gt ${HANDSHAKES}' 60; then
	fail $PID "FAIL: expected a new DTLS session after the timeout, got none"
fi

if ! ${CMDNS1} ping -c 3 ${VPNADDR}; then
	fail $PID "FAIL: expected pings to succeed over the new DTLS session, they failed"
fi

NEW_WID=$(worker_id)
if test "${NEW_WID}" != "${WID}"; then
	fail $PID "FAIL: expected worker ID ${WID} after the new DTLS session, got '${NEW_WID}'"
fi

echo " * The session survived the stalled DTLS rehandshake."
exit 0
