]>
git.ipfire.org Git - ipfire-2.x.git/blob - config/unbound/unbound-dhcp-leases-bridge
2 ###############################################################################
4 # IPFire.org - A linux based firewall #
5 # Copyright (C) 2016 Michael Tremer #
7 # This program is free software: you can redistribute it and/or modify #
8 # it under the terms of the GNU General Public License as published by #
9 # the Free Software Foundation, either version 3 of the License, or #
10 # (at your option) any later version. #
12 # This program is distributed in the hope that it will be useful, #
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
15 # GNU General Public License for more details. #
17 # You should have received a copy of the GNU General Public License #
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. #
20 ###############################################################################
26 import logging
.handlers
31 import inotify
.adapters
33 def setup_logging(loglevel
=logging
.INFO
):
34 log
= logging
.getLogger("dhcp")
35 log
.setLevel(loglevel
)
37 handler
= logging
.handlers
.SysLogHandler(address
="/dev/log", facility
="daemon")
38 handler
.setLevel(loglevel
)
40 formatter
= logging
.Formatter("%(name)s[%(process)d]: %(message)s")
41 handler
.setFormatter(formatter
)
43 log
.addHandler(handler
)
47 log
= logging
.getLogger("dhcp")
49 class UnboundDHCPLeasesBridge(object):
50 def __init__(self
, dhcp_leases_file
, unbound_leases_file
):
51 self
.leases_file
= dhcp_leases_file
53 self
.unbound
= UnboundConfigWriter(unbound_leases_file
)
57 log
.info("Unbound DHCP Leases Bridge started on %s" % self
.leases_file
)
60 # Initially read leases file
61 self
.update_dhcp_leases()
63 i
= inotify
.adapters
.Inotify([self
.leases_file
])
65 for event
in i
.event_gen():
66 # End if we are requested to terminate
73 header
, type_names
, watch_path
, filename
= event
75 # Update leases after leases file has been modified
76 if "IN_MODIFY" in type_names
:
77 self
.update_dhcp_leases()
79 log
.info("Unbound DHCP Leases Bridge terminated")
81 def update_dhcp_leases(self
):
82 log
.info("Reading DHCP leases from %s" % self
.leases_file
)
84 leases
= DHCPLeases(self
.leases_file
)
85 self
.unbound
.update_dhcp_leases(leases
)
91 class DHCPLeases(object):
92 regex_leaseblock
= re
.compile(r
"lease (?P<ipaddr>\d+\.\d+\.\d+\.\d+) {(?P<config>[\s\S]+?)\n}")
94 def __init__(self
, path
):
97 self
._leases
= self
._parse
()
100 return iter(self
._leases
)
105 with
open(self
.path
) as f
:
106 # Read entire leases file
109 for match
in self
.regex_leaseblock
.finditer(data
):
110 block
= match
.groupdict()
112 ipaddr
= block
.get("ipaddr")
113 config
= block
.get("config")
115 properties
= self
._parse
_block
(config
)
117 # Skip any abandoned leases
118 if not "hardware" in properties
:
121 lease
= Lease(ipaddr
, properties
)
123 # Check if a lease for this Ethernet address already
124 # exists in the list of known leases. If so replace
125 # if with the most recent lease
126 for i
, l
in enumerate(leases
):
127 if l
.hwaddr
== lease
.hwaddr
:
128 leases
[i
] = max(lease
, l
)
136 def _parse_block(self
, block
):
139 for line
in block
.splitlines():
143 # Remove trailing ; from line
144 if line
.endswith(";"):
147 # Invalid line if it doesn't end with ;
151 # Remove any leading whitespace
154 # We skip all options and sets
155 if line
.startswith("option") or line
.startswith("set"):
158 # Split by first space
159 key
, val
= line
.split(" ", 1)
160 properties
[key
] = val
166 def __init__(self
, ipaddr
, properties
):
168 self
._properties
= properties
171 return "<%s %s for %s (%s)>" % (self
.__class
__.__name
__,
172 self
.ipaddr
, self
.hwaddr
, self
.hostname
)
174 def __eq__(self
, other
):
175 return self
.ipaddr
== other
.ipaddr
and self
.hwaddr
== other
.hwaddr
177 def __gt__(self
, other
):
178 if not self
.ipaddr
== other
.ipaddr
:
181 if not self
.hwaddr
== other
.hwaddr
:
184 return self
.time_starts
> other
.time_starts
187 def binding_state(self
):
188 state
= self
._properties
.get("binding")
191 state
= state
.split(" ", 1)
196 return self
.binding_state
== "active"
200 hardware
= self
._properties
.get("hardware")
205 ethernet
, address
= hardware
.split(" ", 1)
211 hostname
= self
._properties
.get("client-hostname")
215 hostname
= hostname
.replace("\"", "")
225 return "%s.%s" % (self
.hostname
, self
.domain
)
229 return datetime
.datetime
.strptime(s
, "%w %Y/%m/%d %H:%M:%S")
232 def time_starts(self
):
233 starts
= self
._properties
.get("starts")
236 return self
._parse
_time
(starts
)
240 ends
= self
._properties
.get("ends")
242 if not ends
or ends
== "never":
245 return self
._parse
_time
(ends
)
249 if not self
.time_ends
:
250 return self
.time_starts
> datetime
.datetime
.utcnow()
252 return self
.time_starts
> datetime
.datetime
.utcnow() > self
.time_ends
258 (self
.fqdn
, "IN A", self
.ipaddr
),
261 (self
.ipaddr
, "IN PTR", self
.fqdn
),
265 class UnboundConfigWriter(object):
266 def __init__(self
, path
):
269 self
._cached
_leases
= []
271 def update_dhcp_leases(self
, leases
):
272 # Strip all non-active or expired leases
273 leases
= [l
for l
in leases
if l
.active
and not l
.expired
]
275 # Find any leases that have expired or do not exist any more
276 removed_leases
= [l
for l
in self
._cached
_leases
if l
.expired
or l
not in leases
]
278 # Find any leases that have been added
279 new_leases
= [l
for l
in leases
if l
not in self
._cached
_leases
]
281 # End here if nothing has changed
282 if not new_leases
and not removed_leases
:
285 self
._cached
_leases
= leases
287 # Write out all leases
288 self
.write_dhcp_leases(leases
)
290 # Update unbound about changes
291 for l
in removed_leases
:
292 self
._control
("local_data_remove", l
.fqdn
)
296 self
._control
("local_data", *rr
)
299 def write_dhcp_leases(self
, leases
):
300 with
open(self
.path
, "w") as f
:
303 f
.write("local-data: \"%s\"\n" % " ".join(rr
))
305 def _control(self
, *args
):
306 command
= ["unbound-control", "-q"]
310 subprocess
.check_call(command
)
313 except subprocess
.CalledProcessError
as e
:
314 log
.critical("Could not run %s, error code: %s: %s" % (
315 " ".join(command
), e
.returncode
, e
.output
))
318 if __name__
== "__main__":
319 parser
= argparse
.ArgumentParser(description
="Bridge for DHCP Leases and Unbound DNS")
322 parser
.add_argument("--daemon", "-d", action
="store_true",
323 help="Launch as daemon in background")
324 parser
.add_argument("--verbose", "-v", action
="count", help="Be more verbose")
327 parser
.add_argument("--dhcp-leases", default
="/var/state/dhcp/dhcpd.leases",
328 metavar
="PATH", help="Path to the DHCPd leases file")
329 parser
.add_argument("--unbound-leases", default
="/etc/unbound/dhcp-leases.conf",
330 metavar
="PATH", help="Path to the unbound configuration file")
332 # Parse command line arguments
333 args
= parser
.parse_args()
336 if args
.verbose
== 1:
337 loglevel
= logging
.INFO
338 elif args
.verbose
>= 2:
339 loglevel
= logging
.DEBUG
341 loglevel
= logging
.WARN
343 setup_logging(loglevel
)
345 bridge
= UnboundDHCPLeasesBridge(args
.dhcp_leases
, args
.unbound_leases
)
347 ctx
= daemon
.DaemonContext(detach_process
=args
.daemon
)
349 signal
.SIGHUP
: bridge
.update_dhcp_leases
,
350 signal
.SIGTERM
: bridge
.terminate
,