summaryrefslogtreecommitdiff
path: root/rapid-tunneling-status
blob: 31a106d5f9acb9175f8a8ab9c883702801895003 (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
#!/bin/sh

base_dir="$HOME/.rapid-tunneling"

if [ "$1" = "--help" ]; then
	echo "Usage: $0 [-p] [-r] [-s] [<pid-file>]" 1>&2
	echo "       -p: Print only pid of SSH process (if connecting or connected)." 1>&2
	echo "           Otherwise, print status" 1>&2
	echo "       Exit code: 0 if connected, 1 if connecting, 2 if not connected." 1>&2
	echo "       -s: Stop the tunnel" 1>&2
	echo "       -r: Remove the SSH keys (if not connected)" 1>&2
	exit 255
fi

remove=0
showpid=0
stop=0

if [ "$1" = "-p" ]; then
	showpid=1
	shift
elif [ "$1" = "-r" ]; then
	remove=1
	shift
elif [ "$1" = "-s" ]; then
	stop=1
	shift
fi
pidfile="$1"
[ -z "$pidfile" ] && pidfile="$base_dir/pid"

connected()
{
	[ "$showpid" = 1 ] && echo $pid || echo "Connected"
	exit 0
}

connecting()
{
	[ "$showpid" = 1 ] && echo $pid || echo "Connecting"
	exit 1
}

not_connected()
{
	[ "$showpid" = 1 ] || echo "Not connected"
	if [ "$remove" = 1 ]; then
		remove_ssh_keys
		exit 0
	fi
	exit 2
}

stop_it()
{
	kill $pid 2>/dev/null
	remove_ssh_keys
	exit 0
}

remove_ssh_keys()
{
	sed -i '/ rapid-tunneling$/d' "$HOME/.ssh/authorized_keys"
}

pid=`cat "$pidfile" 2>/dev/null`
[ "$pid" ] || not_connected
kill -s 0 $pid 2>/dev/null || not_connected
for i in /proc/$pid/fd/*; do
	socket=`readlink $i 2>/dev/null | sed -n 's/^socket:\[\(.*\)\]$/\1/p'`
	[ "$socket" ] || continue
	state=`awk '$10 == '"$socket"' {print $4}' /proc/net/tcp`
	[ "$state" ] || continue
	[ "$stop" = 1 ] && stop_it
	# A bug in sudo of centos5: does not FD for the listening socket:
	[ "$state" = "0A" ] && continue # "listening"
	[ "$state" = "01" ] && connected || connecting
done
not_connected