#!/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-007 (d): when the client's UDP source port changes, main
# forwards a new socket to the worker, which must read the DTLS session's
# further records from it.
#
# Method: with DTLS established, rewrite the client's UDP source port in
# its namespace with stateless nft rules, as a NAT rebinding would. The
# DTLS DPD is 90 seconds, so the client keeps sending over DTLS; pings
# through the tunnel succeed only if the worker reads the new socket.

OCCTL="${OCCTL:-../src/occtl/occtl}"
SERV="${SERV:-../src/ocserv}"
srcdir=${srcdir:-.}
PIDFILE=ocserv-pid.$$.tmp
CLIPID=oc-pid.$$.tmp
OUTFILE=dtls-port-change.$$.tmp
OCCTL_SOCKET=./occtl-dtls-port-change-$$.socket
NFT_TABLE=ocserv_dtls_port_$$
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 inet ${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-port-change.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
}

dtls_handshakes() {
	grep -c "DTLS handshake completed" "${OUTFILE}"
}

udp_fds() {
	grep -c "received new UDP fd and connected to peer" "${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 "$(dtls_handshakes)" -ge 1' 15; then
	fail $PID "FAIL: expected a DTLS session, got none in the server log"
fi

if ! ${CMDNS1} ping -c 3 ${VPNADDR}; then
	fail $PID "FAIL: expected pings over DTLS to succeed, they failed"
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}"

CLI_PORT=$(${CMDNS1} ss -Hun dst ${ADDRESS}:${PORT} | awk '{n = split($(NF - 1), a, ":"); print a[n]; exit}')
if test -z "${CLI_PORT}"; then
	${CMDNS1} ss -uan
	fail $PID "FAIL: expected the client's DTLS socket to ${ADDRESS}:${PORT}, found none"
fi
NEW_PORT=$((CLI_PORT == 40000 ? 40001 : 40000))
FDS=$(udp_fds)

echo " * Changing the client's UDP port from ${CLI_PORT} to ${NEW_PORT}..."
${CMDNS1} nft add table inet ${NFT_TABLE} &&
	${CMDNS1} nft add chain inet ${NFT_TABLE} out \
		"{ type filter hook output priority -300 ; }" &&
	${CMDNS1} nft add rule inet ${NFT_TABLE} out \
		ip daddr ${ADDRESS} udp sport ${CLI_PORT} udp dport ${PORT} \
		udp sport set ${NEW_PORT} &&
	${CMDNS1} nft add chain inet ${NFT_TABLE} in \
		"{ type filter hook prerouting priority -300 ; }" &&
	${CMDNS1} nft add rule inet ${NFT_TABLE} in \
		ip saddr ${ADDRESS} udp sport ${PORT} udp dport ${NEW_PORT} \
		udp dport set ${CLI_PORT}
if test $? != 0; then
	fail $PID "FAIL: could not install the nft rules"
fi

# The worker checks that the first record on the new socket decrypts, and
# drops it; this ping makes main forward the socket.
${CMDNS1} ping -c 1 -W 2 ${VPNADDR}

if ! wait_for 'test "$(udp_fds)" -gt "${FDS}"' 10; then
	fail $PID "FAIL: expected the worker to receive a new UDP socket after the port change, got none"
fi
if grep -q "received UDP fd message but its session has invalid data" "${OUTFILE}"; then
	fail $PID "FAIL: expected the worker to accept the new UDP socket of its established session, it discarded it"
fi

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

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

UDP_SOCKETS=$(${CMDNS2} ss -Huanp | grep "pid=${WID},")
if test "$(echo "${UDP_SOCKETS}" | grep -c .)" != 1 ||
	! echo "${UDP_SOCKETS}" | grep -q ":${NEW_PORT} "; then
	${CMDNS2} ss -uanp
	fail $PID "FAIL: expected the worker to hold 1 UDP socket, connected to port ${NEW_PORT}, got: ${UDP_SOCKETS}"
fi

echo " * The DTLS session continued on the new UDP port."
exit 0
