#!/bin/sh

# TCP + UDP request/response stress with random packet sizes
#   $1 - destination IP (default: 127.0.0.1)
#   $2 - number of concurrent tests (default: 3)
#   $3 - number of iterations (default: 5)

[ -n "$1" ] && DST=$1 || DST="127.0.0.1"
[ -n "$2" ] && COUNT=$2 || COUNT=3
[ -n "$3" ] && ITER=$3 || ITER=5

# Test ports are dynamically allocated. Therefore, it is not possible to
# open iptables hole based on particular port numbers.

# open hole
#iptables -I INPUT -s $DST -j ACCEPT
#iptables -I OUTPUT -d $DST -j ACCEPT

while [ $ITER -gt 0 ]; do
    echo "=== $ITER iterations left ==="
    for i in `seq 1 $COUNT`; do
      hexdump -d -n 8 /dev/urandom | awk '$2>=0 { print $2+0, $3+0, $4+0, $5+0 }' >/tmp/$0-$$
      read REQ1 REQ2 RESP1 RESP2 </tmp/$0-$$
      REQ1=$(( $REQ1 % 256 ))
      REQ2=$(( $REQ2 % 1500 ))
      echo $REQ1,$RESP1 $REQ2,$RESP2
      # It is important to have at least 20 seconds duration (-l),
      # otherwise some of the processes will hang on recv*() call
      # waiting for packet from netserver which has already exited.
      ./netperf -t UDP_RR -H $DST -l 20 -P 0 -- -r $REQ1,$RESP1 &
      ./netperf -t UDP_RR -H $DST -l 20 -P 0 -- -r $RESP2,$REQ2 &
      #./netperf -t TCP_CRR -H $DST -l 1 -P 0 -- -r $REQ2,$RESP2 &
      #./netperf -t TCP_CRR -H $DST -l 1 -P 0 -- -r $RESP1,$REQ1 &
    done
    wait
    ITER=$(( $ITER - 1 ))
done
rm /tmp/$0-$$

# close hole
#iptables -D INPUT 1
#iptables -D OUTPUT 1
