blob: 431414d64dbeb046ae58cc61408c9f8fcc007d54 [file] [log] [blame]
Simon Kelleyc72daea2012-01-05 21:33:27 +00001#!/bin/bash
2#
3# Script to update the resolver list for dnsmasq
4#
5# N.B. Resolvconf may run us even if dnsmasq is not running.
6# If dnsmasq is installed then we go ahead and update
7# the resolver list in case dnsmasq is started later.
8#
9# Assumption: On entry, PWD contains the resolv.conf-type files
10#
11# Requires bash because it uses a non-POSIX printf extension.
12#
13# Licensed under the GNU GPL. See /usr/share/common-licenses/GPL.
14#
15
16set -e
17
18RUN_DIR="/var/run/dnsmasq"
19RSLVRLIST_FILE="${RUN_DIR}/resolv.conf"
20TMP_FILE="${RSLVRLIST_FILE}_new.$$"
21
22[ -x /usr/sbin/dnsmasq ] || exit 0
23[ -x /lib/resolvconf/list-records ] || exit 1
24
25PATH=/bin:/sbin
26
27report_err() { echo "$0: Error: $*" >&2 ; }
28
29# Stores arguments (minus duplicates) in RSLT, separated by spaces
30# Doesn't work properly if an argument itself contain whitespace
31uniquify()
32{
33 RSLT=""
34 while [ "$1" ] ; do
35 for E in $RSLT ; do
36 [ "$1" = "$E" ] && { shift ; continue 2 ; }
37 done
38 RSLT="${RSLT:+$RSLT }$1"
39 shift
40 done
41}
42
43if [ ! -d "$RUN_DIR" ] && ! mkdir --parents --mode=0755 "$RUN_DIR" ; then
44 report_err "Failed trying to create directory $RUN_DIR"
45 exit 1
46fi
47
48RSLVCNFFILES="$(/lib/resolvconf/list-records | sed -e '/^lo.dnsmasq$/d')"
49
50NMSRVRS=""
51if [ "$RSLVCNFFILES" ] ; then
52 uniquify $(sed -n -e 's/^[[:space:]]*nameserver[[:space:]]\+//p' $RSLVCNFFILES)
53 NMSRVRS="$RSLT"
54fi
55
56# Dnsmasq uses the mtime of $RSLVRLIST_FILE, with a resolution of one second,
57# to detect changes in the file. This means that if a resolvconf update occurs
58# within one second of the previous one then dnsmasq may fail to notice the
59# more recent change. To work around this problem we sleep here to ensure
60# that the new mtime is different.
61if [ -f "$RSLVRLIST_FILE" ] && [ "$(ls -go --time-style='+%s' "$RSLVRLIST_FILE" | { read p h s t n ; echo "$t" ; })" = "$(date +%s)" ] ; then
62 sleep 1
63fi
64
65clean_up() { rm -f "$TMP_FILE" ; }
66trap clean_up EXIT
67: >| "$TMP_FILE"
68for N in $NMSRVRS ; do echo "nameserver $N" >> "$TMP_FILE" ; done
69mv -f "$TMP_FILE" "$RSLVRLIST_FILE"
70