1#!/bin/sh 2# -*-sh-basic-offset: 4-*- 3# Usage: udp_proxy_wrapper.sh [PROXY_PARAM...] -- [SERVER_PARAM...] 4 5set -u 6 7MBEDTLS_BASE="$(dirname -- "$0")/../.." 8TPXY_BIN="$MBEDTLS_BASE/programs/test/udp_proxy" 9SRV_BIN="$MBEDTLS_BASE/programs/ssl/ssl_server2" 10 11: ${VERBOSE:=0} 12 13stop_proxy() { 14 if [ -n "${tpxy_pid:-}" ]; then 15 echo 16 echo " * Killing proxy (pid $tpxy_pid) ..." 17 kill $tpxy_pid 18 fi 19} 20 21stop_server() { 22 if [ -n "${srv_pid:-}" ]; then 23 echo 24 echo " * Killing server (pid $srv_pid) ..." 25 kill $srv_pid >/dev/null 2>/dev/null 26 fi 27} 28 29cleanup() { 30 stop_server 31 stop_proxy 32 exit 129 33} 34 35trap cleanup INT TERM HUP 36 37# Extract the proxy parameters 38tpxy_cmd_snippet='"$TPXY_BIN"' 39while [ $# -ne 0 ] && [ "$1" != "--" ]; do 40 tail="$1" quoted="" 41 while [ -n "$tail" ]; do 42 case "$tail" in 43 *\'*) quoted="${quoted}${tail%%\'*}'\\''" tail="${tail#*\'}";; 44 *) quoted="${quoted}${tail}"; tail=; false;; 45 esac 46 done 47 tpxy_cmd_snippet="$tpxy_cmd_snippet '$quoted'" 48 shift 49done 50unset tail quoted 51if [ $# -eq 0 ]; then 52 echo " * No server arguments (must be preceded by \" -- \") - exit" 53 exit 3 54fi 55shift 56 57dtls_enabled= 58ipv6_in_use= 59server_port_orig= 60server_addr_orig= 61for param; do 62 case "$param" in 63 server_port=*) server_port_orig="${param#*=}";; 64 server_addr=*:*) server_addr_orig="${param#*=}"; ipv6_in_use=1;; 65 server_addr=*) server_addr_orig="${param#*=}";; 66 dtls=[!0]*) dtls_enabled=1;; 67 esac 68done 69 70if [ -z "$dtls_enabled" ] || [ -n "$ipv6_in_use" ]; then 71 echo >&2 "$0: Couldn't find DTLS enabling, or IPv6 is in use - immediate fallback to server application..." 72 if [ $VERBOSE -gt 0 ]; then 73 echo "[ $SRV_BIN $* ]" 74 fi 75 exec "$SRV_BIN" "$@" 76fi 77 78if [ -z "$server_port_orig" ]; then 79 server_port_orig=4433 80fi 81echo " * Server port: $server_port_orig" 82tpxy_cmd_snippet="$tpxy_cmd_snippet \"listen_port=\$server_port_orig\"" 83tpxy_cmd_snippet="$tpxy_cmd_snippet \"server_port=\$server_port\"" 84 85if [ -n "$server_addr_orig" ]; then 86 echo " * Server address: $server_addr_orig" 87 tpxy_cmd_snippet="$tpxy_cmd_snippet \"server_addr=\$server_addr_orig\"" 88 tpxy_cmd_snippet="$tpxy_cmd_snippet \"listen_addr=\$server_addr_orig\"" 89fi 90 91server_port=$(( server_port_orig + 1 )) 92set -- "$@" "server_port=$server_port" 93echo " * Intermediate port: $server_port" 94 95echo " * Start proxy in background ..." 96if [ $VERBOSE -gt 0 ]; then 97 echo "[ $tpxy_cmd_snippet ]" 98fi 99eval exec "$tpxy_cmd_snippet" >/dev/null 2>&1 & 100tpxy_pid=$! 101 102if [ $VERBOSE -gt 0 ]; then 103 echo " * Proxy ID: $TPXY_PID" 104fi 105 106echo " * Starting server ..." 107if [ $VERBOSE -gt 0 ]; then 108 echo "[ $SRV_BIN $* ]" 109fi 110 111exec "$SRV_BIN" "$@" >&2 & 112srv_pid=$! 113 114wait $srv_pid 115 116stop_proxy 117return 0 118