]>
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 ###############################################################################
27 import logging
.handlers
32 import inotify
.adapters
36 def setup_logging(loglevel
=logging
.INFO
):
37 log
= logging
.getLogger("dhcp")
38 log
.setLevel(loglevel
)
40 handler
= logging
.handlers
.SysLogHandler(address
="/dev/log", facility
="daemon")
41 handler
.setLevel(loglevel
)
43 formatter
= logging
.Formatter("%(name)s[%(process)d]: %(message)s")
44 handler
.setFormatter(formatter
)
46 log
.addHandler(handler
)
50 log
= logging
.getLogger("dhcp")
52 class UnboundDHCPLeasesBridge(object):
53 def __init__(self
, dhcp_leases_file
, unbound_leases_file
):
54 self
.leases_file
= dhcp_leases_file
56 self
.unbound
= UnboundConfigWriter(unbound_leases_file
)
60 log
.info("Unbound DHCP Leases Bridge started on %s" % self
.leases_file
)
63 # Initially read leases file
64 self
.update_dhcp_leases()
66 i
= inotify
.adapters
.Inotify([self
.leases_file
])
68 for event
in i
.event_gen():
69 # End if we are requested to terminate
76 header
, type_names
, watch_path
, filename
= event
78 # Update leases after leases file has been modified
79 if "IN_MODIFY" in type_names
:
80 self
.update_dhcp_leases()
82 log
.info("Unbound DHCP Leases Bridge terminated")
84 def update_dhcp_leases(self
):
85 log
.info("Reading DHCP leases from %s" % self
.leases_file
)
87 leases
= DHCPLeases(self
.leases_file
)
88 self
.unbound
.update_dhcp_leases(leases
)
94 class DHCPLeases(object):
95 regex_leaseblock
= re
.compile(r
"lease (?P<ipaddr>\d+\.\d+\.\d+\.\d+) {(?P<config>[\s\S]+?)\n}")
97 def __init__(self
, path
):
100 self
._leases
= self
._parse
()
103 return iter(self
._leases
)
108 with
open(self
.path
) as f
:
109 # Read entire leases file
112 for match
in self
.regex_leaseblock
.finditer(data
):
113 block
= match
.groupdict()
115 ipaddr
= block
.get("ipaddr")
116 config
= block
.get("config")
118 properties
= self
._parse
_block
(config
)
120 # Skip any abandoned leases
121 if not "hardware" in properties
:
124 lease
= Lease(ipaddr
, properties
)
126 # Check if a lease for this Ethernet address already
127 # exists in the list of known leases. If so replace
128 # if with the most recent lease
129 for i
, l
in enumerate(leases
):
130 if l
.hwaddr
== lease
.hwaddr
:
131 leases
[i
] = max(lease
, l
)
139 def _parse_block(self
, block
):
142 for line
in block
.splitlines():
146 # Remove trailing ; from line
147 if line
.endswith(";"):
150 # Invalid line if it doesn't end with ;
154 # Remove any leading whitespace
157 # We skip all options and sets
158 if line
.startswith("option") or line
.startswith("set"):
161 # Split by first space
162 key
, val
= line
.split(" ", 1)
163 properties
[key
] = val
169 def __init__(self
, ipaddr
, properties
):
171 self
._properties
= properties
174 return "<%s %s for %s (%s)>" % (self
.__class
__.__name
__,
175 self
.ipaddr
, self
.hwaddr
, self
.hostname
)
177 def __eq__(self
, other
):
178 return self
.ipaddr
== other
.ipaddr
and self
.hwaddr
== other
.hwaddr
180 def __gt__(self
, other
):
181 if not self
.ipaddr
== other
.ipaddr
:
184 if not self
.hwaddr
== other
.hwaddr
:
187 return self
.time_starts
> other
.time_starts
190 def binding_state(self
):
191 state
= self
._properties
.get("binding")
194 state
= state
.split(" ", 1)
199 return self
.binding_state
== "active"
203 hardware
= self
._properties
.get("hardware")
208 ethernet
, address
= hardware
.split(" ", 1)
214 hostname
= self
._properties
.get("client-hostname")
218 hostname
= hostname
.replace("\"", "")
224 # Load ethernet settings
225 ethernet_settings
= self
.read_settings("/var/ipfire/ethernet/settings")
228 dhcp_settings
= self
.read_settings("/var/ipfire/dhcp/settings")
231 for zone
in ("GREEN", "BLUE"):
232 if not dhcp_settings
.get("ENABLE_%s" % zone
) == "on":
235 netaddr
= ethernet_settings
.get("%s_NETADDRESS" % zone
)
236 submask
= ethernet_settings
.get("%s_NETMASK" % zone
)
238 subnet
= ipaddress
.ip_network("%s/%s" % (netaddr
, submask
))
239 domain
= dhcp_settings
.get("DOMAIN_NAME_%s" % zone
)
241 subnets
[subnet
] = domain
243 address
= ipaddress
.ip_address(self
.ipaddr
)
245 for subnet
, domain
in subnets
.items():
246 if address
in subnet
:
249 # Fall back to localdomain if no match could be found
253 def read_settings(filename
):
256 with
open(filename
) as f
:
257 for line
in f
.readlines():
261 k
, v
= line
.split("=", 1)
268 return "%s.%s" % (self
.hostname
, self
.domain
)
272 return datetime
.datetime
.strptime(s
, "%w %Y/%m/%d %H:%M:%S")
275 def time_starts(self
):
276 starts
= self
._properties
.get("starts")
279 return self
._parse
_time
(starts
)
283 ends
= self
._properties
.get("ends")
285 if not ends
or ends
== "never":
288 return self
._parse
_time
(ends
)
292 if not self
.time_ends
:
293 return self
.time_starts
> datetime
.datetime
.utcnow()
295 return self
.time_starts
> datetime
.datetime
.utcnow() > self
.time_ends
301 (self
.fqdn
, "%s" % LOCAL_TTL
, "IN A", self
.ipaddr
),
304 (self
.ipaddr
, "%s" % LOCAL_TTL
, "IN PTR", self
.fqdn
),
308 class UnboundConfigWriter(object):
309 def __init__(self
, path
):
313 def existing_leases(self
):
314 local_data
= self
._control
("list_local_data")
317 for line
in local_data
.splitlines():
319 hostname
, ttl
, x
, record_type
, content
= line
.split("\t")
323 # Ignore everything that is not A or PTR
324 if not record_type
in ("A", "PTR"):
327 if hostname
.endswith("."):
328 hostname
= hostname
[:-1]
330 if content
.endswith("."):
331 content
= content
[:-1]
333 if record_type
== "A":
334 ret
[hostname
] = content
335 elif record_type
== "PTR":
336 ret
[content
] = hostname
340 def update_dhcp_leases(self
, leases
):
341 # Strip all non-active or expired leases
342 leases
= [l
for l
in leases
if l
.active
and not l
.expired
]
344 # Find any leases that have expired or do not exist any more
346 for fqdn
, address
in self
.existing_leases
.items():
347 if not fqdn
in (l
.fqdn
for l
in leases
):
348 removed_leases
+= [fqdn
, address
]
350 # Find any leases that have been added
351 new_leases
= [l
for l
in leases
352 if l
.fqdn
not in self
.existing_leases
]
354 # End here if nothing has changed
355 if not new_leases
and not removed_leases
:
358 # Write out all leases
359 self
.write_dhcp_leases(leases
)
361 # Update unbound about changes
362 for hostname
in removed_leases
:
363 log
.debug("Removing all records for %s" % hostname
)
364 self
._control
("local_data_remove", hostname
)
368 log
.debug("Adding new record %s" % " ".join(rr
))
369 self
._control
("local_data", *rr
)
372 def write_dhcp_leases(self
, leases
):
373 with
open(self
.path
, "w") as f
:
376 f
.write("local-data: \"%s\"\n" % " ".join(rr
))
378 def _control(self
, *args
):
379 command
= ["unbound-control"]
383 return subprocess
.check_output(command
)
386 except subprocess
.CalledProcessError
as e
:
387 log
.critical("Could not run %s, error code: %s: %s" % (
388 " ".join(command
), e
.returncode
, e
.output
))
391 if __name__
== "__main__":
392 parser
= argparse
.ArgumentParser(description
="Bridge for DHCP Leases and Unbound DNS")
395 parser
.add_argument("--daemon", "-d", action
="store_true",
396 help="Launch as daemon in background")
397 parser
.add_argument("--verbose", "-v", action
="count", help="Be more verbose")
400 parser
.add_argument("--dhcp-leases", default
="/var/state/dhcp/dhcpd.leases",
401 metavar
="PATH", help="Path to the DHCPd leases file")
402 parser
.add_argument("--unbound-leases", default
="/etc/unbound/dhcp-leases.conf",
403 metavar
="PATH", help="Path to the unbound configuration file")
405 # Parse command line arguments
406 args
= parser
.parse_args()
409 if args
.verbose
== 1:
410 loglevel
= logging
.INFO
411 elif args
.verbose
>= 2:
412 loglevel
= logging
.DEBUG
414 loglevel
= logging
.WARN
416 setup_logging(loglevel
)
418 bridge
= UnboundDHCPLeasesBridge(args
.dhcp_leases
, args
.unbound_leases
)
420 ctx
= daemon
.DaemonContext(detach_process
=args
.daemon
)
422 signal
.SIGHUP
: bridge
.update_dhcp_leases
,
423 signal
.SIGTERM
: bridge
.terminate
,