summaryrefslogtreecommitdiff
path: root/socat.sh
blob: c3e0e60ffe513ed73b5586c6ce8d8f00d0d84b67 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/bin/bash

UNIT=socat-dns
default_dest=149.56.44.185
default_port=53

verify_service_availability()
{
    dig . @127.0.0.1 >/dev/null 2>&1
}

service_launch_command()
{
    local dest port local_port
    dest=${1:-$default_dest}
    case "$dest" in
	'') return 1 ;;
	*:*)
	    port=${dest#*:}
	    dest=${dest%%:*}
	;;
	*)
	    port=${2:-$default_port}
	;;
    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
    do
        systemd-notify --pid="$PID" WATCHDOG=1
        sleep "$SLEEP_TIME"
    done
}

main()
{
    case "$1" in
        install)
            shift
	    COMMAND=$(service_launch_command "$@")
            if systemctl is-active "$UNIT" >/dev/null
            then
                systemctl stop "$UNIT"
            fi
            systemctl reset-failed "$UNIT" 2>/dev/null

            systemd-run \
                --unit "$UNIT" \
                --property Restart="always" \
                --property WatchdogSec="5" \
                -- \
                "$0" watchdog "$COMMAND" verify_service_availability
            ;;
        watchdog)
	    shift
            watchdog $$ "$2" &
            exec $1
            ;;
	status)
	    systemctl status "$UNIT"
	    ;;
	monitor)
	    journalctl -u "$UNIT" -f
	    ;;
        *)
            echo "Usage: $0 install [destination [destination port [local port]]]" >&2
            echo "       $0 status" >&2
            exit 1
            ;;
    esac
}

main "$@"