#!/bin/sh
#
# 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 GnuTLS; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

SERV="${SERV:-../src/ocserv}"
srcdir=${srcdir:-.}
NO_NEED_ROOT=1

. `dirname $0`/common.sh

require_oc_client

eval "${GETPORT}"

echo "Testing HTTP body and header size limits..."

update_config test-user-cert.config
launch_simple_sr_server -d 1 -f -c ${CONFIG}
PID=$!
wait_server $PID

BODY_LIMIT=$((256 * 1024))

# oversized WHAT [OPTIONS]: posts to /auth with the oversized parts in
# OPTIONS
oversized() {
	echo -n "Testing $1... "
	shift
	oc_run oversized --path /auth "$@"
	ret=$?
}

# expect_answered WHAT: the server answered the last request, with any
# status
expect_answered() {
	oc_expect 'Status: [0-9]+' "$1 was rejected"
	echo "ok (HTTP $(oc_value Status))"
}

# expect_refused WHAT: the server refused the last request with 413 or 431,
# or by closing the connection; a request that did not reach it (exit 2)
# is not a refusal
expect_refused() {
	if test $ret = 0; then
		oc_fail "$1 was not rejected"
	elif test $ret != 1; then
		oc_fail "$1: the request did not reach the server (exit $ret)"
	fi
	echo "ok ($(cat ${OC_OUT}))"
}

oversized "body within limit (${BODY_LIMIT} bytes)" --body-size ${BODY_LIMIT}
expect_answered "Body within limit"

oversized "body over limit ($((BODY_LIMIT + 1)) bytes)" \
	--body-size $((BODY_LIMIT + 1))
expect_refused "Body over limit"

# Headers of 1 KB each; with a 16 KB limit, 3 headers (3 KB) are within and
# 20 headers (20 KB) are over.
oversized "headers within limit (3 KB)" --headers 3
expect_answered "Headers within limit"

oversized "headers over limit (20 KB)" --headers 20
expect_refused "Headers over limit"

cleanup
exit 0
