Branch oldpackages for 14.07
[14.07/packages.git] / net / natpmp / files / natpmp.init
1 #!/bin/sh /etc/rc.common
2
3 START=70
4
5 SERVICE_DAEMONIZE=1
6 SERVICE_WRITE_PID=1
7
8 IP=$(which ip)
9 IPTABLES=$(which iptables)
10 NATPMP=/usr/sbin/natpmp
11 PIDFILE=/var/run/natpmp.pid
12
13 natpmp_config() {
14         local cfg="$1"
15
16         config_get PUBLIC_IF "$cfg" outbound_interface
17         config_get PRIVATE_IFS "$cfg" inbound_interfaces
18         config_get IPTABLES_CHAIN "$cfg" iptables_chain
19 }
20
21 start() {
22         config_load natpmp
23         config_foreach natpmp_config natpmp
24
25         . /lib/functions/network.sh
26
27         # Flush all the rules in the natpmp chain, or create it, if it doesn't exists.
28         $IPTABLES -t nat -F $IPTABLES_CHAIN 2>/dev/null || \
29         $IPTABLES -t nat -N $IPTABLES_CHAIN
30
31         # Handle all incoming connections in the natpmp chain.
32         $IPTABLES -t nat -D PREROUTING -j $IPTABLES_CHAIN 2>/dev/null || true
33         $IPTABLES -t nat -A PREROUTING -j $IPTABLES_CHAIN
34
35         # Iterate through the private interfaces.
36         BIND_ARGS=""
37         for IF in $PRIVATE_IFS; do
38                 local dev
39                 network_get_device dev "$IF" || dev="$IF"
40
41                 # Get the IP address of this interface.
42                 ADDR=`$IP addr show dev $dev 2>/dev/null | grep "^ *inet .* $dev\$" | cut -d " " -f 6 | cut -d / -f 1`
43                 if [ -n "$ADDR" ] ; then
44                         # Add the IP address to the argument list.
45                         BIND_ARGS="$BIND_ARGS -a $ADDR"
46                 else
47                         echo "Could not get IP address of interface $dev. Skipping." >&2
48                 fi
49         done
50
51         if [ -z "$BIND_ARGS" ] ; then
52                 echo "No IP addresses to bind to. Exiting." >&2
53                 exit 1
54         fi
55
56         local pubdev
57         network_get_device pubdev "$PUBLIC_IF" || pubdev="$PUBLIC_IF"
58
59         SERVICE_PID_FILE="$PIDFILE"
60         service_start $NATPMP -i "$pubdev" $BIND_ARGS -- "$IPTABLES_CHAIN"
61 }
62
63 stop() {
64         config_load natpmp
65         config_foreach natpmp_config natpmp
66
67         # Unlink chain
68         $IPTABLES -t nat -D PREROUTING -j $IPTABLES_CHAIN 2>/dev/null || true
69
70         # Flush all the rules in the natpmp chain
71         $IPTABLES -t nat -F $IPTABLES_CHAIN 2>/dev/null && \
72         $IPTABLES -t nat -X $IPTABLES_CHAIN
73
74         SERVICE_PID_FILE="$PIDFILE"
75         service_stop $NATPMP
76 }