unbound_dhcpd.py 5.18 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#!/usr/local/bin/python2.7

"""
    Copyright (c) 2016 Ad Schellevis
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.

    THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
    AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
    AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.

    --------------------------------------------------------------------------------------
    watch dhcp lease file and build include file for unbound
"""
import os
import sys
33

34
sys.path.insert(0, "/usr/local/opnsense/site-python")
35
import subprocess
36
import time
37
import tempfile
38 39 40 41
from daemonize import Daemonize
import watchers.dhcpd
import params

42

43 44 45 46 47 48 49
def unbound_control(commands, output_stream=None):
    """ execute (chrooted) unbound-control command
        :param commands: command list (parameters)
        :param output_stream: (optional)output stream
        :return: None
    """
    output_stream = open(os.devnull, 'w')
50 51
    subprocess.check_call(['/usr/sbin/chroot', '-u', 'unbound', '-g', 'unbound', '/',
                           '/usr/local/sbin/unbound-control', '-c', '/var/unbound/unbound.conf'] + commands,
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
                          stdout=output_stream, stderr=subprocess.STDOUT)
    output_stream.seek(0)


def unbound_known_addresses():
    """ fetch known addresses
        :return: list
    """
    result = list()
    with tempfile.NamedTemporaryFile() as output_stream:
        unbound_control(['list_local_data'], output_stream)
        for line in output_stream.read().split('\n'):
            parts = line.split()
            if len(parts) > 4 and parts[3] == 'A':
                result.append(parts[4])
    return result

69

70
# parse input params
71 72 73 74
app_params = {'pid': '/var/run/unbound_dhcpd.pid',
              'domain': 'local',
              'target': '/var/unbound/dhcpleases.conf',
              'background': '1'}
75 76
params.update_params(app_params)

77

78 79 80 81 82 83 84
def main():
    # cleanup interval (seconds)
    cleanup_interval = 60

    # initiate lease watcher and setup cache
    dhcpdleases = watchers.dhcpd.DHCPDLease()
    cached_leases = dict()
85
    known_addresses = unbound_known_addresses()
86 87 88 89 90 91 92 93 94 95 96 97 98 99

    # start watching dhcp leases
    last_cleanup = time.time()
    while True:
        dhcpd_changed = False
        for lease in dhcpdleases.watch():
            if 'ends' in lease and lease['ends'] > time.time() and 'client-hostname' in lease and 'address' in lease:
                cached_leases[lease['address']] = lease
                dhcpd_changed = True
        if time.time() - last_cleanup > cleanup_interval:
            # cleanup every x seconds
            last_cleanup = time.time()
            addresses = cached_leases.keys()
            for address in addresses:
Ad Schellevis's avatar
Ad Schellevis committed
100
                if cached_leases[address]['ends'] < time.time():
101 102 103 104 105 106 107
                    del cached_leases[address]
                    dhcpd_changed = True

        if dhcpd_changed:
            # dump dns output to target
            with open(app_params['target'], 'w') as unbound_conf:
                for address in cached_leases:
108 109 110
                    unbound_conf.write('local-data-ptr: "%s %s.%s"\n' % (address,
                                                                         cached_leases[address]['client-hostname'],
                                                                         app_params['domain']))
111 112 113
                    unbound_conf.write('local-data: "%s.%s IN A %s"\n' % (cached_leases[address]['client-hostname'],
                                                                          app_params['domain'],
                                                                          address))
114 115 116 117 118 119 120
            # signal unbound
            for address in cached_leases:
                if address not in known_addresses:
                    fqdn = '%s.%s' % (cached_leases[address]['client-hostname'], app_params['domain'])
                    unbound_control(['local_data', address, 'PTR', fqdn])
                    unbound_control(['local_data', fqdn, 'IN A', address])
                    known_addresses.append(address)
121 122 123 124

        # wait for next cycle
        time.sleep(1)

125

126 127 128 129 130 131
# startup
if app_params['background'] == '1':
    daemon = Daemonize(app="unbound_dhcpd", pid=app_params['pid'], action=main)
    daemon.start()
else:
    main()