1#!/bin/sh
2
3. ${STREAMBOOST_CFGDIR:-/etc/appflow}/rc.appflow
4
5#
6# Environment config
7#
8BINARY="p0f"
9NAME=${BINARY}
10DISPLAY_NAME=p0f
11
12#
13# P0f config
14#
15P0F_BIN="${BINDIR}/${BINARY}"
16PIDFILE="${RUNDIR}/${BINARY}.pid"
17# server socket for client requests
18SOCKET="${RUNDIR}/${NAME}.sock"
19# monitored interface
20IFACE="$LAN_IFACE"
21# fingerprint database path
22if [ -e "${RUNDIR}/p0f.fp" ]; then
23	FINGERPRINT_FILE="${RUNDIR}/p0f.fp"
24else
25	FINGERPRINT_FILE="${CFGDIR}/p0f.fp"
26fi
27
28# if the debug file exists, policy_engine is not started at boot
29KROUTER_DEBUG_FILE=${KROUTER_DEBUG_FILE:-"/etc/krouter_debug"}
30
31# the command line parameters
32P0F_OPTIONS="-s ${SOCKET} -i ${IFACE} -f ${FINGERPRINT_FILE}"
33
34#
35# Functions
36#
37
38# p0f won't start unless $IFACE has an ip address
39# wait for the ip address here
40wait_for_iface() {
41	local checkcount
42	checkcount=0
43	while [ ${checkcount} -lt 5 ] && ! ifconfig ${IFACE} | grep "inet addr" > /dev/null
44	do
45		echo "waiting for ${IFACE}"
46		sleep 1
47		checkcount=$((checkcount+1))
48	done
49}
50
51get_netaddr() {
52	for num in $(route -n | grep ${IFACE} | awk '{ print $1 }'); do
53		first=$(echo ${num} | awk -F\. '{ print $1 }')
54		if [ "${first}" -lt "224" ]; then
55			echo ${num}
56			return
57		fi
58	done
59}
60
61get_netmask() {
62	echo $(ifconfig ${IFACE} | grep "inet addr" | awk -F' ' '{ print $4 }' | awk -F: '{ print $2 }')
63}
64
65start() {
66	local netaddr
67	local netmask
68	local filter
69
70	wait_for_iface
71
72	netaddr=`get_netaddr`
73	netmask=`get_netmask`
74	if [ "${netaddr}" != "" ]; then
75		filter="(not src net ${netaddr} mask ${netmask} or not dst net ${netaddr} mask ${netmask}) and (port 80 or ((tcp[tcpflags] & tcp-syn) == 1))"
76	fi
77
78	[ ! -d "${RUNDIR}" ] && {
79		mkdir ${RUNDIR}
80	}
81
82	[ -e "${SOCKET}" ] && {
83		rm ${SOCKET}
84	}
85
86	[ -x ${P0F_BIN} ] || {
87		echo "${BINARY} not found: ${P0F_BIN}"
88		exit 2
89	}
90
91	echo -n "Starting ${NAME}: "
92	${P0F_BIN} ${P0F_OPTIONS} "${filter}" >${P0F_FIFO} "$@" &
93	retval=$?
94	echo
95
96	# p0f doesn't write its pid to a file, neither does start-stop-daemon
97	# Sometimes we get a parent pid if we pidof too early
98	sleep 1
99	pidof p0f > ${PIDFILE}
100
101	return ${retval}
102}
103
104boot() {
105	if [ -n "${KROUTER_DEBUG_FILE}" ] && [ -e "${KROUTER_DEBUG_FILE}" ]
106	then
107		# If the debug file is present, don't start
108		echo "debug mode requested, refusing to start ${NAME}"
109	else
110		start "$@"
111	fi
112}
113
114stop() {
115	[ -f "${PIDFILE}" ] && {
116		echo -n "Stopping ${NAME}: "
117		kill -TERM $(cat ${PIDFILE})
118		retval=$?
119		echo
120		[ ${retval} -eq 0 ] && {
121			rm -f ${PIDFILE}
122			[ -e "${SOCKET}" ] && {
123				rm ${SOCKET}
124			}
125		}
126		return ${retval}
127	}
128	return 0
129}
130
131action "$@"
132exit $?
133