#!/bin/sh
# Autopkgtest: functional and regression tests for tcpxtract, run against
# the installed package (binary and /etc/tcpxtract.conf).
# test.pcap  - regular HTTP capture, must extract the known files.
# crash.pcap - malformed capture reproducing the heap buffer overflow
#              fixed for #945092, must be processed without crashing.
#
# Note: the system configuration is used (not $SRCDIR/tcpxtract.conf) so
# that the test does not depend on the quilt state of the source tree.

set -e

SRCDIR="$(pwd)"
WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT

fail() {
    echo "FAIL: $1" >&2
    exit 1
}

[ -r /etc/tcpxtract.conf ] || fail "/etc/tcpxtract.conf is not installed"

echo "== extracting files from the sample capture"
cd "$WORK"
tcpxtract -c /etc/tcpxtract.conf -f "$SRCDIR/debian/tests/test.pcap" > extract.log 2>&1 \
    || fail "tcpxtract exited with an error on the sample capture"

grep -q "Found file of type" extract.log \
    || fail "no file was recognized in the sample capture"

ls *.html >/dev/null 2>&1 \
    || fail "no html file was extracted from the sample capture"

PNG="$(ls *.png 2>/dev/null | head -n1)"
[ -n "$PNG" ] && [ -s "$PNG" ] \
    || fail "no non-empty png file was extracted from the sample capture"

head -c 4 "$PNG" | od -An -tx1 | grep -qi "89 50 4e 47" \
    || fail "extracted png does not start with the PNG magic bytes"

echo "== processing the malformed capture (regression for #945092)"
tcpxtract -c /etc/tcpxtract.conf -f "$SRCDIR/debian/tests/crash.pcap" > crash.log 2>&1 \
    || fail "tcpxtract crashed or failed on the malformed capture"

echo "== parsing the configuration file"
tcpxtract -c /etc/tcpxtract.conf -f "$SRCDIR/debian/tests/test.pcap" > conf.log 2>&1 \
    || fail "tcpxtract failed to parse /etc/tcpxtract.conf"

grep -q "Found file of type" conf.log \
    || fail "no file was recognized while using the system configuration"

echo "PASS: all extraction tests succeeded"
