Debian Codegraph @

debian/autossh_wrapper

raw
1 #!/bin/sh
2 # little wrapper to choose a random port for autossh, falling back to $fallback_port
3
4 fallback_port="21021"
5 tcpstat="/proc/net/tcp"
6
7 # take an hex port and check whether it is in use (i.e. locally bound) in
8 # $tcpstat
9 # unix command semantics: if in use return 0 else return 1
10 port_in_use() {
11 if egrep -q "^[0-9 ]+: [0-9A-F]{8}:$1" $tcpstat ; then
12 return 0
13 else
14 return 1
15 fi
16 }
17
18 echo "$@" | egrep -q -- '-f?M ?[0-9]+' # backward compatibility, skip guess if -M is passed
19
20 if [ $? -gt 0 ] && [ -z "$AUTOSSH_PORT" ]; then
21 portguess=""
22 if [ -r "/dev/urandom" ] && [ -r "$tcpstat" ]; then
23 for t in $(seq 1 42); do
24 # get a random hex
25 randport=$( od -x -N2 -An /dev/urandom | tr -d ' ' )
26
27 # increase it a little "bit"
28 randport=$( /usr/bin/printf "%04x" $(( 0x$randport | 0x8000 )) )
29 randport_1=$( /usr/bin/printf "%04x" $(( 0x$randport + 1 )) )
30
31 # check if port is in use, possibile race condition between here
32 # and the exec
33 if ! port_in_use $randport && ! port_in_use $randport_1; then
34 portguess=$(( 0x$randport ))
35 break
36 fi
37 done
38 fi
39
40 if [ -z "$portguess" ]; then
41 fallback=$( /usr/bin/printf "%04x" $fallback_port )
42 fallback_1=$( /usr/bin/printf "%04x" $(( 0x$fallback + 1 )) )
43 if ! port_in_use $fallback && ! port_in_use $fallback_1; then
44 portguess=$fallback_port
45 else
46 echo "unable to find a suitable tunnel port"
47 exit 1
48 fi
49 fi
50
51 export AUTOSSH_PORT="$portguess"
52 fi
53
54 exec /usr/lib/autossh/autossh "$@"