ctdb-scripts: Compact server-end TCP connection killing output
[samba.git] / ctdb / tests / eventscripts / stubs / ss
1 #!/bin/bash
2
3 prog="ss"
4
5 usage ()
6 {
7     cat >&2 <<EOF
8 Usage: $prog -tn state established [ '(' ip-filter ')' ] [ '(' port-filter ')' ]
9
10 A fake ss stub that prints items depending on the variables
11 FAKE_NETSTAT_TCP_ESTABLISHED and FAKE_NETSTAT_TCP_ESTABLISHED_FILE.
12
13 Note that "-tn state established" must be given.
14
15 EOF
16     exit 1
17 }
18
19 if [ "$1" != "-tn" -o "$2" != "state" -o "$3" != "established" ] ; then
20     usage
21 fi
22
23 shift 3
24
25 # Check if socket has matches in both ok_ips and ok_ports
26 filter_socket ()
27 {
28     ok_ips="$1"
29     ok_ports="$2"
30     socket="$3"
31
32     ip="${socket%:*}"
33     port="${socket##*:}"
34
35     if [ "$ok_ports" != "|" -a "${ok_ports#*|${port}|}" = "$ok_ports" ] ; then
36         return 1
37     fi
38     if [ "$ok_ips" != "|" -a "${ok_ips#*|${ip}|}" = "$ok_ips" ] ; then
39         return 1
40     fi
41
42     return 0
43 }
44
45 ss_tcp_established ()
46 {
47     echo "Recv-Q Send-Q Local Address:Port Peer Address:Port"
48
49     # Very limited implementation:
50     # We only expect to find || inside parentheses
51     # We don't expect to see && - it is implied by juxtaposition
52     # Operator for port comparison is ignored and assumed to be ==
53
54     # Build lists of source ports and source IP addresses where each
55     # entry is surrounded by '|' characters.  These lists can be
56     # easily "searched" using the POSIX prefix and suffix removal
57     # operators.
58     in_parens=false
59     sports="|"
60     srcs="|"
61
62     while [ -n "$1" ] ; do
63         case "$1" in
64             \() in_parens=true ; shift ;;
65             \)) in_parens=false ; shift ;;
66             \|\|) if ! $in_parens ; then usage ; fi ; shift ;;
67             sport) p="${3#:}" ; sports="${sports}${p}|" ; shift 3 ;;
68             src) ip="${2#\[}" ; ip="${ip%\]}" ; srcs="${srcs}${ip}|" ; shift 2 ;;
69             *) usage ;;
70         esac
71     done
72
73     for i in $FAKE_NETSTAT_TCP_ESTABLISHED ; do
74         src="${i%|*}"
75         dst="${i#*|}"
76         if filter_socket "$srcs" "$sports" "$src" ; then
77             echo 0 0 "$src" "$dst"
78         fi
79     done
80
81     if [ -z "$FAKE_NETSTAT_TCP_ESTABLISHED_FILE" ] ; then
82             return
83     fi
84     while read src dst ; do
85         if filter_socket "$srcs" "$sports" "$src" ; then
86             echo 0 0 "$src" "$dst"
87         fi
88     done <"$FAKE_NETSTAT_TCP_ESTABLISHED_FILE"
89 }
90
91 # Yes, lose the quoting so we can do a hacky parsing job
92 ss_tcp_established $*