#!/bin/sh
### Usage:
### Get http://www.life-gone-hazy.com/src/tcpdump-tools/tcpdump-split.c
### Compile it with "cc -lpcap -o tcpdump-split tcpdump-split.c"
### Edit the parameters below.
### Run this script as a user with permission to listen to the interface.
### Make sure files are appearing in the desired directory.
### Dump files other than the current one can be compressed or moved elsewhere
### if space is tight.

### Parameters

## Name of the root server and anycast instance
server="X.instance"

## Directory to write into
directory="."

## Name of the network interface to monitor
interface=em0

## Number of seconds to run (50 hours == 180000 seconds)
duration=180000

## How often to rotate dump file, in seconds
interval=3600

## IPv4 and IPv6 addresses of servers, separated by "or"
hosts="192.5.5.241 or 2001:500::1035"

## your ntp server
ntpserver="time.sdsc.edu"

### choose a packet filter:
## collect TCP and UDP, requests and responses:
filter="host (${hosts}) and port 53"

## collect UDP requests, and TCP requests and responses.
# filter="(udp and dst host (${hosts}) and dst port 53) or (tcp and host (${hosts}) and port 53)"

## collect TCP and UDP requests
# filter="dst host (${hosts}) and dst port 53"

## collect UDP requests
# filter="udp and dst host (${hosts}) and dst port 53"


#### End of parameters




TZ=UTC
export TZ
metafile="${directory}/${server}.`date +%Y%m%d.%H%M`.metadata.txt"
tcpdump="tcpdump -w- -i${interface} -s0 ${filter}"
split="./tcpdump-split ${interval} ${directory}/${server}.%Y%m%d.%H%M.pcap"
test -d "${directory}" || mkdir -p - ${directory}

meta() { echo "### $@"; eval "$*"; echo; }

exec 3>&2
(
    echo "ditl-dnsroot-run metadata"
    echo
    meta "uname -a"
    meta "ntpdate -q ${ntpserver}"

    fifo="${directory}/fifo"
    mkfifo "${fifo}" || exit $?
    echo "### split: ${split}"
    ${split} <"${fifo}" &
    split_pid=$!
    echo "### tcpdump: ${tcpdump}"
    ${tcpdump} >"${fifo}" &
    tcpdump_pid=$!

    sleep 1;
    kill -0 $tcpdump_pid || {
	echo "tcpdump is not running." >&3
	exit 1
    }
    echo "tcpdump is running." >&3

    kill -0 $split_pid || {
	echo "tcpdump-split is not running." >&3
	exit 1
    }
    echo "tcpdump-split is running." >&3

    sleep ${duration}
    kill ${tcpdump_pid}
    rm "${fifo}"

    echo
    meta "ntpdate -q ${ntpserver}"

) > "${metafile}" 2>&1 || {
    echo "Error.  See ${metafile} for details."
}
