From 0822c8328c1d41382c18c03bd8d0deb899269052 Mon Sep 17 00:00:00 2001 From: root Date: Mon, 24 Apr 2023 12:39:41 -0400 Subject: improve factoring and add makefile --- Makefile | 6 ++++++ socat.sh | 46 ++++++++++++++++++++++++++++++++++++---------- 2 files changed, 42 insertions(+), 10 deletions(-) create mode 100644 Makefile diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..09918b8 --- /dev/null +++ b/Makefile @@ -0,0 +1,6 @@ + +all: + +status install: + ./socat.sh $@ + diff --git a/socat.sh b/socat.sh index e7ae9f6..1afb4a4 100755 --- a/socat.sh +++ b/socat.sh @@ -1,4 +1,5 @@ #!/bin/bash + UNIT=socat-dns verify_service_availability() @@ -6,15 +7,40 @@ verify_service_availability() dig . @127.0.0.1 >/dev/null 2>&1 } +service_launch_command() +{ + local dest port local_port + dest=${1:-149.56.44.185} + case "$dest" in + '') return 1 ;; + *:*) + port=${dest#*:} + dest=${dest%%:*} + ;; + *) + port=${2:-53} + ;; + esac + local_port=${3:-$port} + + printf "socat UDP-RECVFROM:%s,fork UDP-SENDTO:%s\n" "$local_port" "$dest:$port" +} + +#### + watchdog() { PID=$1 + VERIFY=$2 + + TWO_MILLION=2000000 + SLEEP_TIME=$(( ${WATCHDOG_USEC:-$TWO_MILLION} / $TWO_MILLION )) enable -f /usr/lib/bash/sleep sleep || true - while verify_service_availability + while $VERIFY do systemd-notify --pid="$PID" WATCHDOG=1 - sleep $((${WATCHDOG_USEC:-2000000} / 2000000)) + sleep "$SLEEP_TIME" done } @@ -23,10 +49,7 @@ main() case "$1" in install) shift - DEST=${1:-149.56.44.185} - PORT=${2:-53} - LOCAL_PORT=${3:-$PORT} - COMMAND="socat UDP-RECVFROM:$LOCAL_PORT,fork UDP-SENDTO:$DEST:$PORT" + COMMAND=$(service_launch_command "$@") if systemctl is-active "$UNIT" >/dev/null then systemctl stop "$UNIT" @@ -38,16 +61,19 @@ main() --property Restart="always" \ --property WatchdogSec="5" \ -- \ - "$0" watchdog "$COMMAND" + "$0" watchdog "$COMMAND" verify_service_availability ;; watchdog) shift - COMMAND="$1" - watchdog $$ & - exec $COMMAND + watchdog $$ "$2" & + exec $1 ;; + status) + systemctl status "$UNIT" + ;; *) echo "Usage: $0 install [destination [destination port [local port]]]" >&2 + echo " $0 status" >&2 exit 1 ;; esac -- cgit v1.2.3