summaryrefslogtreecommitdiff
path: root/aports/forwarding/forwarding
blob: be1fc641156c8312a98f63df861c73f60b1aa108 (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
#!/bin/sh
# shellcheck disable=SC2034,SC3043,SC3060

log() {
    local _level="$1"
    local _message="$2"

    /usr/bin/logger -p "daemon.${_level}" -t "forwarding[$$]" "${_message}"
}

capture_output() {
    local _type="$1"
    local _id="$2"

    while read -r message; do
	log "${_type}" "[${_id}] ${message}"
    done
}

_block=

terminate() {
    local _sleep

    if [ -n "${_block}" ]; then
	log info "Received signal for termination, stopping PID ${_block}."
	/bin/kill -KILL "${_block}"
	log debug "Killed: $?"
	_sleep=$(/bin/ps -o ppid,comm,pid \
		     | /bin/grep -F "1 sleep" \
		     | /usr/bin/head -1 \
		     | /bin/sed "s@[ ]*1[ ]*sleep[ ]*@@")
	log info "Stopping the orphaned sleep as PID ${_sleep}."
	/bin/kill -KILL "${_sleep}"
	log debug "Killed: $?"
    else
	log warn "Nothing is blocked, nothing to do."
    fi
}

trap terminate TERM

while read -r _line; do
    _parameters=$(echo "${_line}" | /bin/sed '/^[[:blank:]]*#/d;s/#.*//')

    [ -z "${_parameters}" ] && continue

    log info "Launching socat with parameters: [${_parameters}]"
    /usr/bin/socat ${_parameters} 2>&1 \
	| capture_output debug socat &
done < /media/etc/forwarding.conf

(while /bin/true; do /bin/sleep 365d; done) &
_block=$!

log info "Waiting for PID ${_block} to stop."
wait "${_block}"

_socats=$(/usr/bin/pgrep -P $$ socat)
log info "Stopping, own socat processes: [${_socats}]"

# shellcheck disable=SC2086
[ -n "${_socats}" ] && /bin/kill -TERM ${_socats}

log info "Finished."