#!/bin/bash
#
# This script generates the smallest pcap which causes a segmentation fault.

source "$(dirname "$0")/t2utils.sh"

# Configuration options
DIV=2         # Number of parts for the initial split
STEP=1        # Number of packets to eat when removing packets from the beginning/end/middle
#TIMEOUT=4    # if set, kill t2 after TIMEOUT seconds
#ERRMSG="ERR" # if set, grep the output for this message

# TODO
# check for tshark, editcap and timeout
# option to choose which tests to run
# try to remove sequence of packets, e.g., !(frame.number == 1) && !(frame.number == 2)
# !icmp, data/!data, ip/!ip, ipv6/!ipv6, tcp/!tcp, udp/!udp
# Try to remove 1000, then 500, then 250, ...

usage() {
    printf "Usage:\n"
    printf "    $SNAME [OPTION...] file.pcap\n\n"
    printf "Optional arguments:\n"
    printf "    -d num              Split the pcap into <num> parts (default: $DIV)\n"
    printf "    -s num              Number of packets to eat when removing packets from\n"
    printf "    -f                  Try to remove packets one by one as a last resort\n"
    printf "                        the beginning/end/middle (default: $STEP)\n"
    printf "    -t num              If set, kill T2 after <num> seconds\n"
    printf "    -e str              If set, grep the output for this message\n\n"
    printf "    -T path             Set the path to the T2 binary\n\n"
    printf "    -?, -h, --help      Show help options and exit\n"
}

while [ $# -gt 0 ]; do
    case "$1" in
        -d)
            validate_next_num "$1" "$2"
            DIV="$2"
            shift
            ;;
        -s)
            validate_next_num "$1" "$2"
            STEP="$2"
            shift
            ;;
        -f)
            FINAL=1
            ;;
        -t)
            validate_next_num "$1" "$2" # TODO could be a float...
            TIMEOUT="$2"
            shift
            ;;
        -e)
            validate_next_arg "$1" "$2"
            ERRMSG="$2"
            shift
            ;;
        -T)
            validate_next_file "$1" "$2"
            T2="$2"
            shift
            ;;
        -\?|-h|--help)
            usage
            exit 0
            ;;
        *)
            if [ ! -f "$1" ]; then
                abort_option_unknown "$1"
            fi
            FILE="$1"
            ;;
    esac
    shift
done

if [ ! -f "$T2" ]; then
    printerr "Tranalyzer not found"
    abort_with_help
fi

if [ ! -f "$FILE" ]; then
    abort_required_file
fi

IN="$FILE"
OUT="out"
CONT=1
NUM=0

while [ $CONT -eq 1 ]; do
    CONT=0
    N=$(capinfos -c -M "$IN" | grep "Number of packets:" | cut -d: -f2 | sed 's/[[:space:]]\+//')
    N=$((1+N/DIV))
    if [ -n "$M" ] && [ $N -eq $M ]; then
        DIV=$((DIV+1))
        if [ $N -lt 20 ]; then
            break
        fi
        printinf "Dividing by $DIV\n"
        continue
    fi
    M=$N
    echo "editcap -F pcap -c $N \"$IN\" \"$OUT$NUM\""
    ERR="$(editcap -F pcap -c "$N" "$IN" "$OUT$NUM" 2>&1 | grep error)"
    if [ -z "$ERR" ]; then
        for i in ${OUT}${NUM}_*; do
            if [ "$i" != "$IN" ] && [ -n "$(file -b "$i" | grep 'capture file')" ]; then
                if [ $CONT -eq 1 ] && [ "$i" != "$FILE" ]; then
                    rm "$i"
                else
                    echo "    Testing \"$i\""
                    if [ -n "$ERRMSG" ]; then
                        ERR="$($T2 -r "$i" -w /tmp/DEL 2>&1 | grep "$ERRMSG")"
                    elif [ -n "$TIMEOUT" ]; then
                        timeout -s 11 ${TIMEOUT}s $T2 -l -r "$i" -w /tmp/DEL 2>&1 > /dev/null
                    else
                        $T2 -l -r "$i" -w /tmp/DEL 2>&1 > /dev/null
                    fi
                    ret=$?
                    if [ $ret -eq 139 ] || [ $ret -eq 124 ] || [ -n "$ERR" ]; then
                        echo "    \"$i\" causes a segfault"
                        CONT=1
                        if [ "$IN" != "$FILE" ]; then
                            rm "$IN"
                        fi
                        IN="$i"
                    elif [ "$i" != "$FILE" ]; then
                        rm "$i"
                    fi
                fi
            fi
        done
    else
        printerr "editcap failed... aborting"
        exit 1
    fi
    NUM=$((NUM+1))
done

N=$(capinfos -c -M "$IN" | grep "Number of packets:" | cut -d: -f2 | sed 's/[[:space:]]\+//')
printinf "\nRemoving first packets $N\n"
IN2="$IN"
for i in $(seq 2 $STEP $N); do
    TEST="${OUT}${NUM}"
    echo "editcap -r \"$IN\" \"$TEST\" $i-$N"
    ERR="$(editcap -F pcap -r "$IN" "$TEST" $i-$N 2>&1 | grep error)"
    if [ -z "$ERR" ]; then
        echo "    Testing \"$TEST\""
        if [ -n "$ERRMSG" ]; then
            ERR="$($T2 -r "$TEST" -w /tmp/DEL 2>&1 | grep "$ERRMSG")"
        elif [ -n "$TIMEOUT" ]; then
            timeout -s 11 ${TIMEOUT}s $T2 -l -r "$TEST" -w /tmp/DEL 2>&1 > /dev/null
        else
            $T2 -l -r "$TEST" -w /tmp/DEL 2>&1 > /dev/null
        fi
        ret=$?
        if [ $ret -eq 139 ] || [ $ret -eq 124 ] || [ -n "$ERR" ]; then
            if [ -f "$IN2" ] && [ "$IN2" != "$IN" ] && [ "$IN2" != "$FILE" ]; then
                rm "$IN2"
            fi
            IN2="$TEST"
        elif [ "$TEST" != "$FILE" ]; then
            rm "$TEST"
            break
        fi
    else
        printerr "editcap failed... aborting"
        exit 1
    fi
    NUM=$((NUM+1))
done

if [ "$IN2" != "$IN" ] && [ "$IN" != "$FILE" ]; then
    rm "$IN"
fi

IN="$IN2"
N=$(capinfos -c -M "$IN" | grep "Number of packets:" | cut -d: -f2 | sed 's/[[:space:]]\+//')
printinf "\nRemoving last packets $N\n"
IN2="$IN"
for i in $(seq $N -$STEP 1); do
    TEST="${OUT}${NUM}"
    echo "editcap -r \"$IN\" \"$TEST\" 1-$i"
    ERR="$(editcap -F pcap -r "$IN" "$TEST" 1-$i 2>&1 | grep error)"
    if [ -z "$ERR" ]; then
        echo "    Testing \"$TEST\""
        if [ -n "$ERRMSG" ]; then
            ERR="$($T2 -r "$TEST" -w /tmp/DEL 2>&1 | grep "$ERRMSG")"
        elif [ -n "$TIMEOUT" ]; then
            timeout -s 11 ${TIMEOUT}s $T2 -l -r "$TEST" -w /tmp/DEL 2>&1 > /dev/null
        else
            $T2 -l -r "$TEST" -w /tmp/DEL 2>&1 > /dev/null
        fi
        ret=$?
        if [ $ret -eq 139 ] || [ $ret -eq 124 ] || [ -n "$ERR" ]; then
            if [ -f "$IN2" ] && [ "$IN2" != "$IN" ] && [ "$IN2" != "$FILE" ]; then
                rm "$IN2"
            fi
            IN2="$TEST"
        elif [ "$TEST" != "$FILE" ]; then
            rm "$TEST"
            break
        fi
    else
        printerr "editcap failed... aborting"
        exit 1
    fi
    NUM=$((NUM+1))
done

if [ "$IN2" != "$IN" ] && [ "$IN" != "$FILE" ]; then
    rm "$IN"
fi

IN="$IN2"
# TODO remove from the beginning, then from the end
N=$(capinfos -c -M "$IN" | grep "Number of packets:" | cut -d: -f2 | sed 's/[[:space:]]\+//')
printinf "\nRemoving middle packets $N\n"
MID=$((N/2))
IN2="$IN"
for i in $(seq 1 $STEP $N); do
    TEST="${OUT}${NUM}"
    echo "tshark -F pcap -r \"$IN\" -w \"$TEST\" -Y \"frame.number < $((MID-i)) || frame.number > $((MID+i))\""
    #ERR="$(tshark -F pcap -r "$IN" -w "$TEST" -Y "frame.number < $((MID-i)) || frame.number > $MID")"
    #ERR="$(tshark -F pcap -r "$IN" -w "$TEST" -Y "frame.number < $MID || frame.number > $((MID+i))")"
    ERR="$(tshark -F pcap -r "$IN" -w "$TEST" -Y "frame.number < $((MID-i)) || frame.number > $((MID+i))")"
    if [ -z "$ERR" ]; then
        echo "    Testing \"$TEST\""
        if [ -n "$ERRMSG" ]; then
            ERR="$($T2 -r "$TEST" -w /tmp/DEL 2>&1 | grep "$ERRMSG")"
        elif [ -n "$TIMEOUT" ]; then
            timeout -s 11 ${TIMEOUT}s $T2 -l -r "$TEST" -w /tmp/DEL 2>&1 > /dev/null
        else
            $T2 -l -r "$TEST" -w /tmp/DEL 2>&1 > /dev/null
        fi
        ret=$?
        if [ $ret -eq 139 ] || [ $ret -eq 124 ] || [ -n "$ERR" ]; then
            if [ -f "$IN2" ] && [ "$IN2" != "$IN" ] && [ "$IN2" != "$FILE" ]; then
                rm "$IN2"
            fi
            IN2="$TEST"
        elif [ "$TEST" != "$FILE" ]; then
            rm "$TEST"
            break
        fi
    else
        printerr "tshark failed... aborting"
        exit 1
    fi
    NUM=$((NUM+1))
done

if [ "$IN2" != "$IN" ] && [ "$IN" != "$FILE" ]; then
    rm "$IN"
fi

IN="$IN2"
N=$(capinfos -c -M "$IN" | grep "Number of packets:" | cut -d: -f2 | sed 's/[[:space:]]\+//')
printinf "\nRemoving TCP streams $N\n"
IN2="$IN"
for i in $(seq 2 $STEP $N); do
    TEST="${OUT}${NUM}"
    echo "tshark -F pcap -r \"$IN\" -w \"$TEST\" -Y \"tcp.stream < $i\""
    ERR="$(tshark -F pcap -r "$IN" -w "$TEST" -Y "tcp.stream < $i")"
    NTEST=$(capinfos -c -M "$TEST" | grep "Number of packets:" | cut -d: -f2 | sed 's/[[:space:]]\+//')
    if [ $NTEST -eq 0 ]; then
        break
    elif [ -z "$ERR" ]; then
        echo "    Testing \"$TEST\""
        if [ -n "$ERRMSG" ]; then
            ERR="$($T2 -r "$TEST" -w /tmp/DEL 2>&1 | grep "$ERRMSG")"
        elif [ -n "$TIMEOUT" ]; then
            timeout -s 11 ${TIMEOUT}s $T2 -l -r "$TEST" -w /tmp/DEL 2>&1 > /dev/null
        else
            $T2 -l -r "$TEST" -w /tmp/DEL 2>&1 > /dev/null
        fi
        ret=$?
        if [ $ret -eq 139 ] || [ $ret -eq 124 ] || [ -n "$ERR" ]; then
            if [ -f "$IN2" ] && [ "$IN2" != "$IN" ] && [ "$IN2" != "$FILE" ]; then
                rm "$IN2"
            fi
            IN2="$TEST"
        elif [ "$TEST" != "$FILE" ]; then
            rm "$TEST"
            break
        fi
    else
        printerr "tshark failed... aborting"
        exit 1
    fi
    NUM=$((NUM+1))
done

if [ "$IN2" != "$IN" ] && [ "$IN" != "$FILE" ]; then
    rm "$IN"
fi

IN="$IN2"
N=$(capinfos -c -M "$IN" | grep "Number of packets:" | cut -d: -f2 | sed 's/[[:space:]]\+//')
printinf "\nRemoving UDP streams $N\n"
IN2="$IN"
for i in $(seq 2 $STEP $N); do
    TEST="${OUT}${NUM}"
    echo "tshark -F pcap -r \"$IN\" -w \"$TEST\" -Y \"udp.stream < $i\""
    ERR="$(tshark -F pcap -r "$IN" -w "$TEST" -Y "udp.stream < $i")"
    NTEST=$(capinfos -c -M "$TEST" | grep "Number of packets:" | cut -d: -f2 | sed 's/[[:space:]]\+//')
    if [ $NTEST -eq 0 ]; then
        break
    elif [ -z "$ERR" ]; then
        echo "    Testing \"$TEST\""
        if [ -n "$ERRMSG" ]; then
            ERR="$($T2 -r "$TEST" -w /tmp/DEL 2>&1 | grep "$ERRMSG")"
        elif [ -n "$TIMEOUT" ]; then
            timeout -s 11 ${TIMEOUT}s $T2 -l -r "$TEST" -w /tmp/DEL 2>&1 > /dev/null
        else
            $T2 -l -r "$TEST" -w /tmp/DEL 2>&1 > /dev/null
        fi
        ret=$?
        if [ $ret -eq 139 ] || [ $ret -eq 124 ] || [ -n "$ERR" ]; then
            if [ -f "$IN2" ] && [ "$IN2" != "$IN" ] && [ "$IN2" != "$FILE" ]; then
                rm "$IN2"
            fi
            IN2="$TEST"
        elif [ "$TEST" != "$FILE" ]; then
            rm "$TEST"
            break
        fi
    else
        printerr "tshark failed... aborting"
        exit 1
    fi
    NUM=$((NUM+1))
done

if [ "$IN2" != "$IN" ] && [ "$IN" != "$FILE" ]; then
    rm "$IN"
fi

if [ -n "$FINAL" ]; then
    IN="$IN2"
    N=$(capinfos -c -M "$IN" | grep "Number of packets:" | cut -d: -f2 | sed 's/[[:space:]]\+//')
    printinf "\nRemoving packets one by one $N\n"
    IN2="$IN"
    i=1
    while [ $i -ne $N ]; do
        TEST="${OUT}${NUM}"
        echo "tshark -F pcap -r \"$IN\" -w \"$TEST\" -Y \"!(frame.number == $i)\" # $N"
        ERR="$(tshark -F pcap -r "$IN" -w "$TEST" -Y "!(frame.number == $i)")"
        NTEST=$(capinfos -c -M "$TEST" | grep "Number of packets:" | cut -d: -f2 | sed 's/[[:space:]]\+//')
        if [ $NTEST -eq 0 ]; then
            break
        elif [ -z "$ERR" ]; then
            echo "    Testing \"$TEST\""
            if [ -n "$ERRMSG" ]; then
                ERR="$($T2 -r "$TEST" -w /tmp/DEL 2>&1 | grep "$ERRMSG")"
            elif [ -n "$TIMEOUT" ]; then
                timeout -s 11 ${TIMEOUT}s $T2 -l -r "$TEST" -w /tmp/DEL 2>&1 > /dev/null
            else
                $T2 -l -r "$TEST" -w /tmp/DEL 2>&1 > /dev/null
            fi
            ret=$?
            if [ $ret -eq 139 ] || [ $ret -eq 124 ] || [ -n "$ERR" ]; then
                if [ -f "$IN2" ] && [ "$IN2" != "$IN" ] && [ "$IN2" != "$FILE" ]; then
                    rm "$IN2"
                fi
                IN2="$TEST"
            elif [ "$TEST" != "$FILE" ]; then
                rm "$TEST"
                i=$((i+1))
                #break
            else
                i=$((i+1))
            fi
        else
            printerr "tshark failed... aborting"
            exit 1
        fi
        NUM=$((NUM+1))
        if [ "$IN2" != "$IN" ] && [ "$IN" != "$FILE" ]; then
            #XYZ="$IN"
            ##i=1
            #IN="$IN2"
            #XXX=$(capinfos -c -M "$IN" | grep "Number of packets:" | cut -d: -f2 | sed 's/[[:space:]]\+//')
            #printf "\n$N => $XXX\n"
            #N=$XXX
            #if [ $XXX -gt $N ]; then
            #    printf "WTF?!?"
            #    read
            #fi
            #rm "$XYZ"
            rm "$IN"
            i=1
            IN="$IN2"
            N=$(capinfos -c -M "$IN" | grep "Number of packets:" | cut -d: -f2 | sed 's/[[:space:]]\+//')
        fi
    done

    if [ "$IN2" != "$IN" ] && [ "$IN" != "$FILE" ]; then
        rm "$IN"
    fi
    IN="$IN2"
fi

if [ $IN != "$FILE" ]; then
    N=$(capinfos -c -M "$IN" | grep "Number of packets:" | cut -d: -f2 | sed 's/^[[:space:]]\+//')
    printinf "\n$IN is the smallest PCAP which causes a segfault ($N packets)"
else
    printok "\nThis pcap does not cause a segmentation fault"
fi
