#!/usr/bin/env bash
#
# Count the number of hosts of each OS and creates
# a file _IP_OS.txt mapping every IP to its OS.
#
# Note that p0f require a fingerprints file (p0f.fp), the location of which can
# be specified using the '-f' option. Version 2 looks first in the current
# directoy, then in /etc/p0f. Version 3 looks only in the current directory.
#
# Example output (tab separated)
#   Windows  28
#   Linux    45
#   UNKNOWN  11

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

check_dependency p0f

usage() {
    printf "Usage:\n"
    printf "    $SNAME [OPTION...] file.pcap\n"
    printf "\n"
    printf "Optional arguments:\n"
    printf "    -n N            only output top (N>0) or bottom (N<0) N OS\n"
    printf "\n"
    printf "    -f file         p0f fingerprints file [$P0FFP]\n"
    printf "\n"
    printf "Help and documentation arguments:\n"
    printf "    -h, --help      display this help, then exit\n"
}

# Default values
P0F="$(which p0f)"       # p0f
P0FFP="/etc/p0f/p0f.fp"  # fingerprints file
TOPFUNC=head

if [ "$(uname)" = "Darwin" ]; then
    P0FFP="/usr/local$P0FFP"
fi

while [ $# -gt 0 ]; do
    case "$1" in
        # -n=-N, -n=N, -nN, -n-N, -n N, -n -N
        -n=-*)
            N="${1#*=-}"
            TOPFUNC=tail
            validate_next_int "-n" "-$N"
            ;;
        -n-*)
            N="${1#*n-}"
            TOPFUNC=tail
            validate_next_int "-n" "-$N"
            ;;
        -n=*)
            N="${1#*=}"
            validate_next_int "-n" "$N"
            ;;
        -n)
            validate_next_int "$1" "$2"
            if [ $2 -ge 0 ]; then
                N="$2"
            else
                N="$((-$2))"
                TOPFUNC=tail
            fi
            shift
            ;;
        -n*)
            N="${1#*n}"
            validate_next_int "-n" "$N"
            ;;

        -f)
            validate_next_file "$1" "$2"
            P0FFP="$2"
            shift
            ;;

        -h|-\?|--help)
            usage
            exit 0
            ;;
        *)
            if [ ! -f "$1" ]; then
                abort_option_unknown "$1"
            fi
            FILE="$1"
            ;;
    esac
    shift
done

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

if [ ! -f "$P0FFP" ]; then
    printerr "p0f fingerprints could not be found"
    exit 1
fi

# Make sure p0f finds the fingerprints
P0F="$P0F -f $P0FFP"

_cleanup() {
    local ret=$1
    #echo "Cleaning temporary files"
    rm -f "$TMPFILE"
    exit $ret
}

trap "trap - SIGTERM && _cleanup 1" HUP INT QUIT TERM
trap "_cleanup \$?" EXIT

# Returns a list of IP-OS pairs (tab separated)
if [ -z "$($P0F -h 2> /dev/null | grep "p0f 3.")" ]; then
    IPOS=$($P0F -lSqvDNs "$FILE" 2> /dev/null | perl -pe 's/^([^:]+):\d+ - ([^ ]+) .+$/\1\t\2/' | sort -u)
else
    TMPFILE=$(mktemp)
    $P0F -r "$FILE" -o "$TMPFILE" &> /dev/null
    IPOS=$(grep os "$TMPFILE" | AWK -F'|' -v OFS="\t" '{
        colcli = 0
        colsrv = 0
        colos  = 0
        colsub = 0
        for (i = 1; i <= NF; i++) {
                 if (match($i, /^cli=/ )) colcli = i
            else if (match($i, /^srv=/ )) colsrv = i
            else if (match($i, /^os=/  )) colos  = i
            else if (match($i, /^subj=/)) colsub = i
        }
        if (colcli && colsrv && colos && colsub) {
            split($colsub, d, "=")
            if (d[2] == "cli") ipp = $colcli
            else ipp = $colsrv
            split(ipp, _ip, "=")
            split(_ip[2], ip, "/")
            split($colos, os, "=")
            printf "%s\t%s\n", ip[1], os[2]
        }
    }' | sort -u)
fi

if [ -z "$IPOS" ]; then
    printerr "Failed to run p0f"
    exit 1
fi

declare -A NUMOS

# Merge duplicate entries
IPOS=$(AWK -F"\t" -v OFS="\t" '{
    if (os[$1]) os[$1] = os[$1] "," $2
    else os[$1] = $2
} END {
    for (ip in os) {
        l = split(os[ip], o, ",")
        if (l == 1) {
            print ip, os[ip]
        } else {
            printf "%s", ip
            for (i = 1; i <= l; i++) {  # FIXME: what if l > 2
                if (o[i] != "UNKNOWN" && o[i] != "???") printf "\t%s", o[i]
            }
            printf "\n"
        }
    }
}' <<< "$IPOS" | sort -Vu)

# print the list of IP-OS
echo "$IPOS" > "${FILE}_IP_OS.txt"

# Count the number of hosts of each OS
while read -r line; do
    i=$(AWK -F"\t" '{ print $2 }' <<< "$line")
    NUMOS[$i]=$((NUMOS[$i]+1))
done <<< "$IPOS"

# Print the number of hosts of each OS
OUT=$(for i in "${!NUMOS[@]}"; do
    if [ "$i" == "???" ]; then
        echo -e "UNKNOWN\t" ${NUMOS[$i]}
    else
        echo -e "$i\t" ${NUMOS[$i]}
    fi
done)

# Sort by number of hosts
if [ -z "$N" ]; then
    sort -t$'\t' -rnk2 <<< "$OUT"
else
    sort -t$'\t' -rnk2 <<< "$OUT" | $TOPFUNC -"$N"
fi

unset -v NUMOS
