2018-01-30 16:00:11 +00:00
#!/bin/bash
# (1) Init.
#--------------------------------------------------------#
# (1) Get current absolute dir
ROOT=$(dirname `realpath $0`);
# (2) Check argc
test $# -lt 2 && echo -e "error: too fewarguments\n\n\e[1mUSAGE\e[0m\n\tbind-input <id> <port>\n\n\e[1mARGUMENTS\e[0m\n\t<id>\tThe identifier of the input (buffer name)\n\t<port>\tTo port to listen to\n" && exit 1;
# (3) Check @PORT range #
2018-01-30 17:46:00 +00:00
MIN_PORT=1024;
MAX_PORT=49151;
2018-01-30 16:00:11 +00:00
test "$2" -gt "$MAX_PORT" -o "$2" -lt "$MIN_PORT" && echo "error: <port> must be between $MIN_PORT and $MAX_PORT" && exit 1;
# (4) Set argument explicit names #
IN_ID="$1";
IN_PT="$2";
2018-01-31 23:21:34 +00:00
# (5) Manage optional 'silent' argument #
DEBUG="";
test $# -ge 3 -a "$3" == "debug" && DEBUG="xx";
2018-01-30 16:00:11 +00:00
# (2) Prepare buffer
#--------------------------------------------------------#
# (1) Create buffer path
BUFFER="/tmp/inbuf_$IN_ID";
# (2) Create/Flush buffer
2018-01-31 23:21:34 +00:00
# test -f $BUFFER && rm $BUFFER;
echo -n "" > $BUFFER;
2018-01-30 16:00:11 +00:00
2018-01-31 23:28:32 +00:00
# (3) Remove buffer + kill loop #
on_exit(){
[[ $DEBUG ]] && echo " < closing binding port $IN_PT to $BUFFER";
rm $BUFFER 2>/dev/null && ( [[ $DEBUG ]] && echo " < $BUFFER deleted" );
kill -INT $LOOP_PID 2>/dev/null;
exit 1;
}
2018-01-30 16:00:11 +00:00
# (3) Launch INPUT server
#--------------------------------------------------------#
(
2018-01-31 23:21:34 +00:00
[[ $DEBUG ]] && echo " > binding port $IN_PT to $BUFFER";
2018-01-31 23:28:32 +00:00
trap "kill -9 $NC_PID 2>/dev/null; on_exit;" HUP INT KILL TERM;
2018-01-30 21:54:17 +00:00
2018-01-30 16:00:11 +00:00
infail=0;
# (1) kill script after 10 failures
while [ $infail -lt 10 ]; do
2018-01-30 17:46:00 +00:00
# (3) Check if port already in use
ss -tl4 "( sport = :$IN_PT )" | grep "$IN_PT" >/dev/null;
PORT_TAKEN=$?;
# (4) Manage taken port #
if [ "$PORT_TAKEN" -ne "1" ]; then
infail="`expr $infail + 1`";
2018-01-30 21:54:17 +00:00
test "$infail" -gt "1" && sleep .5;
2018-01-30 17:46:00 +00:00
continue;
fi;
# (5) Bind input
infail="0";
2018-01-31 19:54:16 +00:00
nc -lp $IN_PT >> $BUFFER 2>/dev/null&
2018-01-30 17:46:00 +00:00
NC_PID=$!;
wait $NC_PID;
2018-01-30 16:00:11 +00:00
done;
)&
LOOP_PID=$!;
2018-01-31 19:54:16 +00:00
trap "on_exit;" HUP INT KILL TERM;
2018-01-30 21:54:17 +00:00
2018-01-31 23:28:32 +00:00
echo -n "$LOOP_PID";