3 # /usr/sbin/dnsmasq-portforward
5 # A script which gets run when the dnsmasq DHCP lease database changes.
6 # It logs to $LOGFILE, if it exists, and maintains port-forwards using
7 # IP-tables so that they always point to the correct host. See
8 # $PORTSFILE for details on configuring this. dnsmasq must be version 2.34
11 # To enable this script, add
12 # dhcp-script=/usr/sbin/dnsmasq-portforward
13 # to /etc/dnsmasq.conf
15 # To enable logging, touch $LOGFILE
18 PORTSFILE
=/etc
/portforward
19 LOGFILE
=/var
/log
/dhcp.log
20 IPTABLES
=/sbin
/iptables
25 # log what's going on.
26 if [ -f ${LOGFILE} ] ; then
27 date +"%D %T $*" >>${LOGFILE}
30 # If a lease gets stripped of a name, we see that as an "old" action
31 # with DNSMASQ_OLD_HOSTNAME set, convert it into a "del"
32 if [ ${DNSMASQ_OLD_HOSTNAME} ] && [ ${action} = old
] ; then
34 hostname
=${DNSMASQ_OLD_HOSTNAME}
37 # IPv6 leases are not our concern. no NAT there!
38 if [ ${DNSMASQ_IAID} ] ; then
42 # action init is not relevant, and will only be seen when leasefile-ro is set.
43 if [ ${action} = init
] ; then
47 # action tftp is not relevant.
48 if [ ${action} = tftp
] ; then
52 if [ ${hostname} ]; then
53 ports
=$
(sed -n -e "/^${hostname}\ .*/ s/^.* //p" ${PORTSFILE})
55 for port
in $ports; do
58 if [ ${port:0:1} = u
] ; then
64 # delete first, to avoid multiple copies of rules.
65 ${IPTABLES} -t nat
-D PREROUTING
-p $protocol --destination-port $src -j DNAT
--to-destination ${3}:$dst
66 if [ ${action} != del
] ; then
67 ${IPTABLES} -t nat
-A PREROUTING
-p $protocol --destination-port $src -j DNAT
--to-destination ${3}:$dst
70 if [ -f ${LOGFILE} ] ; then
71 echo " DNAT $protocol $src to ${3}:$dst ${verb}." >>${LOGFILE}