1 | #!/usr/bin/env python
|
---|
2 | #
|
---|
3 | # vim:ts=2:et:sw=2:ai
|
---|
4 | # Wireless Leiden configuration generator, based on yaml files'
|
---|
5 | #
|
---|
6 | # XXX: This should be rewritten to make use of the ipaddr.py library.
|
---|
7 | #
|
---|
8 | # Sample apache configuration (mind the AcceptPathInfo!)
|
---|
9 | # ScriptAlias /wleiden/config /usr/local/www/genesis/tools/gformat.py
|
---|
10 | # <Directory /usr/local/www/genesis>
|
---|
11 | # Allow from all
|
---|
12 | # AcceptPathInfo On
|
---|
13 | # </Directory>
|
---|
14 | #
|
---|
15 | # Rick van der Zwet <info@rickvanderzwet.nl>
|
---|
16 | #
|
---|
17 |
|
---|
18 | # Hack to make the script directory is also threated as a module search path.
|
---|
19 | import sys
|
---|
20 | import os
|
---|
21 | import re
|
---|
22 | sys.path.append(os.path.dirname(__file__))
|
---|
23 |
|
---|
24 | import cgi
|
---|
25 | import cgitb
|
---|
26 | import copy
|
---|
27 | import glob
|
---|
28 | import socket
|
---|
29 | import string
|
---|
30 | import subprocess
|
---|
31 | import time
|
---|
32 | import rdnap
|
---|
33 | import math
|
---|
34 | import make_network_kml
|
---|
35 | from pprint import pprint
|
---|
36 | from collections import defaultdict
|
---|
37 | try:
|
---|
38 | import yaml
|
---|
39 | except ImportError, e:
|
---|
40 | print e
|
---|
41 | print "[ERROR] Please install the python-yaml or devel/py-yaml package"
|
---|
42 | exit(1)
|
---|
43 |
|
---|
44 | try:
|
---|
45 | from yaml import CLoader as Loader
|
---|
46 | from yaml import CDumper as Dumper
|
---|
47 | except ImportError:
|
---|
48 | from yaml import Loader, Dumper
|
---|
49 |
|
---|
50 | from jinja2 import Environment, Template
|
---|
51 | def yesorno(value):
|
---|
52 | return "YES" if bool(value) else "NO"
|
---|
53 | env = Environment()
|
---|
54 | env.filters['yesorno'] = yesorno
|
---|
55 | def render_template(datadump, template):
|
---|
56 | result = env.from_string(template).render(datadump)
|
---|
57 | # Make it look pretty to the naked eye, as jinja templates are not so
|
---|
58 | # friendly when it comes to whitespace formatting
|
---|
59 | ## Remove extra whitespace at end of line lstrip() style.
|
---|
60 | result = re.sub(r'\n[\ ]+','\n', result)
|
---|
61 | ## Include only a single newline between an definition and a comment
|
---|
62 | result = re.sub(r'(["\'])\n+([a-z]|\n#\n)',r'\1\n\2', result)
|
---|
63 | ## Remove extra newlines after single comment
|
---|
64 | result = re.sub(r'(#\n)\n+([a-z])',r'\1\2', result)
|
---|
65 | return result
|
---|
66 |
|
---|
67 | import logging
|
---|
68 | logging.basicConfig(format='# %(levelname)s: %(message)s' )
|
---|
69 | logger = logging.getLogger()
|
---|
70 | logger.setLevel(logging.DEBUG)
|
---|
71 |
|
---|
72 |
|
---|
73 | if os.environ.has_key('CONFIGROOT'):
|
---|
74 | NODE_DIR = os.environ['CONFIGROOT']
|
---|
75 | else:
|
---|
76 | NODE_DIR = os.path.abspath(os.path.dirname(__file__)) + '/../nodes'
|
---|
77 | __version__ = '$Id: gformat.py 10983 2012-05-22 21:49:55Z rick $'
|
---|
78 |
|
---|
79 | files = [
|
---|
80 | 'authorized_keys',
|
---|
81 | 'dnsmasq.conf',
|
---|
82 | 'dhcpd.conf',
|
---|
83 | 'rc.conf.local',
|
---|
84 | 'resolv.conf',
|
---|
85 | 'motd',
|
---|
86 | 'ntp.conf',
|
---|
87 | 'pf.hybrid.conf.local',
|
---|
88 | 'wleiden.yaml',
|
---|
89 | ]
|
---|
90 |
|
---|
91 | # Global variables uses
|
---|
92 | OK = 10
|
---|
93 | DOWN = 20
|
---|
94 | UNKNOWN = 90
|
---|
95 |
|
---|
96 | datadump_cache = {}
|
---|
97 |
|
---|
98 | NO_DHCP = 0
|
---|
99 | DHCP_CLIENT = 10
|
---|
100 | DHCP_SERVER = 20
|
---|
101 | def dhcp_type(item):
|
---|
102 | if not item.has_key('dhcp'):
|
---|
103 | return NO_DHCP
|
---|
104 | elif not item['dhcp']:
|
---|
105 | return NO_DHCP
|
---|
106 | elif item['dhcp'].lower() == 'client':
|
---|
107 | return DHCP_CLIENT
|
---|
108 | else:
|
---|
109 | # Validation Checks
|
---|
110 | begin,end = map(int,item['dhcp'].split('-'))
|
---|
111 | if begin >= end:
|
---|
112 | raise ValueError("DHCP Start >= DHCP End")
|
---|
113 | return DHCP_SERVER
|
---|
114 |
|
---|
115 |
|
---|
116 |
|
---|
117 | def get_yaml(item,add_version_info=True):
|
---|
118 | try:
|
---|
119 | """ Get configuration yaml for 'item'"""
|
---|
120 | if datadump_cache.has_key(item):
|
---|
121 | return datadump_cache[item].copy()
|
---|
122 |
|
---|
123 | gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
|
---|
124 |
|
---|
125 | # Default values
|
---|
126 | datadump = {
|
---|
127 | 'autogen_revision' : 'NOTFOUND',
|
---|
128 | 'autogen_gfile' : gfile,
|
---|
129 | }
|
---|
130 | f = open(gfile, 'r')
|
---|
131 | datadump.update(yaml.load(f,Loader=Loader))
|
---|
132 | if datadump['nodetype'] == 'Hybrid':
|
---|
133 | # Some values are defined implicitly
|
---|
134 | if datadump.has_key('rdr_rules') and datadump['rdr_rules'] and not datadump.has_key('service_incoming_rdr'):
|
---|
135 | datadump['service_incoming_rdr'] = True
|
---|
136 | # Use some boring defaults
|
---|
137 | defaults = {
|
---|
138 | 'service_proxy_normal' : False,
|
---|
139 | 'service_proxy_ileiden' : False,
|
---|
140 | 'service_accesspoint' : True,
|
---|
141 | 'service_incoming_rdr' : False
|
---|
142 | }
|
---|
143 | for (key,value) in defaults.iteritems():
|
---|
144 | if not datadump.has_key(key):
|
---|
145 | datadump[key] = value
|
---|
146 | f.close()
|
---|
147 |
|
---|
148 | # Sometimes getting version information is useless or harmfull, like in the pre-commit hooks
|
---|
149 | if add_version_info:
|
---|
150 | p = subprocess.Popen(['svn', 'info', datadump['autogen_gfile']], stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
|
---|
151 | for line in p.communicate()[0].split('\n'):
|
---|
152 | if line:
|
---|
153 | (key, value) = line.split(': ')
|
---|
154 | datadump["autogen_" + key.lower().replace(' ','_')] = value
|
---|
155 |
|
---|
156 | # Preformat certain needed variables for formatting and push those into special object
|
---|
157 | datadump['autogen_iface_keys'] = get_interface_keys(datadump)
|
---|
158 |
|
---|
159 | wlan_count=0
|
---|
160 | try:
|
---|
161 | for key in datadump['autogen_iface_keys']:
|
---|
162 | datadump[key]['autogen_ifbase'] = key.split('_')[1]
|
---|
163 | if datadump[key]['type'] in ['11a', '11b', '11g', 'wireless']:
|
---|
164 | datadump[key]['autogen_ifname'] = 'wlan%i' % wlan_count
|
---|
165 | wlan_count += 1
|
---|
166 | else:
|
---|
167 | datadump[key]['autogen_ifname'] = datadump[key]['autogen_ifbase']
|
---|
168 | except Exception as e:
|
---|
169 | print "# Error while processing interface %s" % key
|
---|
170 | raise
|
---|
171 |
|
---|
172 | dhcp_interfaces = [datadump[key]['autogen_ifname'] for key in datadump['autogen_iface_keys'] \
|
---|
173 | if dhcp_type(datadump[key]) == DHCP_SERVER]
|
---|
174 |
|
---|
175 | datadump['autogen_dhcp_interfaces'] = dhcp_interfaces
|
---|
176 | datadump['autogen_item'] = item
|
---|
177 |
|
---|
178 | datadump['autogen_realname'] = get_realname(datadump)
|
---|
179 | datadump['autogen_domain'] = datadump['domain'] if datadump.has_key('domain') else 'wleiden.net.'
|
---|
180 | datadump['autogen_fqdn'] = datadump['autogen_realname'] + '.' + datadump['autogen_domain']
|
---|
181 | datadump_cache[item] = datadump.copy()
|
---|
182 | except Exception as e:
|
---|
183 | print "# Error while processing %s" % item
|
---|
184 | raise
|
---|
185 | return datadump
|
---|
186 |
|
---|
187 |
|
---|
188 | def store_yaml(datadump, header=False):
|
---|
189 | """ Store configuration yaml for 'item'"""
|
---|
190 | item = datadump['autogen_item']
|
---|
191 | gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
|
---|
192 |
|
---|
193 | output = generate_wleiden_yaml(datadump, header)
|
---|
194 |
|
---|
195 | f = open(gfile, 'w')
|
---|
196 | f.write(output)
|
---|
197 | f.close()
|
---|
198 |
|
---|
199 |
|
---|
200 | def network(ip):
|
---|
201 | addr, mask = ip.split('/')
|
---|
202 | # Not parsing of these folks please
|
---|
203 | addr = parseaddr(addr)
|
---|
204 | mask = int(mask)
|
---|
205 | network = addr & ~((1 << (32 - mask)) - 1)
|
---|
206 | return network
|
---|
207 |
|
---|
208 |
|
---|
209 |
|
---|
210 | def make_relations(datadumps=dict()):
|
---|
211 | """ Process _ALL_ yaml files to get connection relations """
|
---|
212 | errors = []
|
---|
213 | poel = defaultdict(list)
|
---|
214 |
|
---|
215 | if not datadumps:
|
---|
216 | for host in get_hostlist():
|
---|
217 | datadumps[host] = get_yaml(host)
|
---|
218 |
|
---|
219 | for host, datadump in datadumps.iteritems():
|
---|
220 | try:
|
---|
221 | for iface_key in datadump['autogen_iface_keys']:
|
---|
222 | net_addr = network(datadump[iface_key]['ip'])
|
---|
223 | poel[net_addr] += [(host,datadump[iface_key])]
|
---|
224 | except (KeyError, ValueError), e:
|
---|
225 | errors.append("[FOUT] in '%s' interface '%s' (%s)" % (host,iface_key, e))
|
---|
226 | continue
|
---|
227 | return (poel, errors)
|
---|
228 |
|
---|
229 |
|
---|
230 |
|
---|
231 | def valid_addr(addr):
|
---|
232 | """ Show which address is valid in which are not """
|
---|
233 | return str(addr).startswith('172.')
|
---|
234 |
|
---|
235 | def get_system_list(prefix):
|
---|
236 | return sorted([os.path.basename(os.path.dirname(x)) for x in glob.glob("%s/%s*/wleiden.yaml" % (NODE_DIR, prefix))])
|
---|
237 |
|
---|
238 | get_hybridlist = lambda: get_system_list("Hybrid")
|
---|
239 | get_nodelist = lambda: get_system_list("CNode")
|
---|
240 | get_proxylist = lambda: get_system_list("Proxy")
|
---|
241 |
|
---|
242 | def get_hostlist():
|
---|
243 | """ Combined hosts and proxy list"""
|
---|
244 | return get_nodelist() + get_proxylist() + get_hybridlist()
|
---|
245 |
|
---|
246 | def angle_between_points(lat1,lat2,long1,long2):
|
---|
247 | """
|
---|
248 | Return Angle in radians between two GPS coordinates
|
---|
249 | See: http://stackoverflow.com/questions/3809179/angle-between-2-gps-coordinates
|
---|
250 | """
|
---|
251 | dy = lat2 - lat1
|
---|
252 | dx = math.cos(lat1)*(long2 - long1)
|
---|
253 | angle = math.atan2(dy,dx)
|
---|
254 | return angle
|
---|
255 |
|
---|
256 |
|
---|
257 |
|
---|
258 | def angle_to_cd(angle):
|
---|
259 | """ Return Dutch Cardinal Direction estimation in 'one digit' of radian angle """
|
---|
260 |
|
---|
261 | # For easy conversion get positive degree
|
---|
262 | degrees = math.degrees(angle)
|
---|
263 | abs_degrees = 360 + degrees if degrees < 0 else degrees
|
---|
264 |
|
---|
265 | # Numbers can be confusing calculate from the 4 main directions
|
---|
266 | p = 22.5
|
---|
267 | if abs_degrees < p:
|
---|
268 | cd = "n"
|
---|
269 | elif abs_degrees < (90 - p):
|
---|
270 | cd = "no"
|
---|
271 | elif abs_degrees < (90 + p):
|
---|
272 | cd = "o"
|
---|
273 | elif abs_degrees < (180 - p):
|
---|
274 | cd = "zo"
|
---|
275 | elif abs_degrees < (180 + p):
|
---|
276 | cd = "z"
|
---|
277 | elif abs_degrees < (270 - p):
|
---|
278 | cd = "zw"
|
---|
279 | elif abs_degrees < (270 + p):
|
---|
280 | cd = "w"
|
---|
281 | elif abs_degrees < (360 - p):
|
---|
282 | cd = "nw"
|
---|
283 | else:
|
---|
284 | cd = "n"
|
---|
285 | return cd
|
---|
286 |
|
---|
287 |
|
---|
288 |
|
---|
289 | def cd_between_hosts(hostA, hostB, datadumps):
|
---|
290 | # Using RDNAP coordinates
|
---|
291 | dx = float(int(datadumps[hostA]['rdnap_x']) - int(datadumps[hostB]['rdnap_x'])) * -1
|
---|
292 | dy = float(int(datadumps[hostA]['rdnap_y']) - int(datadumps[hostB]['rdnap_y'])) * -1
|
---|
293 | return angle_to_cd(math.atan2(dx,dy))
|
---|
294 |
|
---|
295 | # GPS coordinates seems to fail somehow
|
---|
296 | #latA = float(datadumps[hostA]['latitude'])
|
---|
297 | #latB = float(datadumps[hostB]['latitude'])
|
---|
298 | #lonA = float(datadumps[hostA]['longitude'])
|
---|
299 | #lonB = float(datadumps[hostB]['longitude'])
|
---|
300 | #return angle_to_cd(angle_between_points(latA, latB, lonA, lonB))
|
---|
301 |
|
---|
302 |
|
---|
303 | def generate_title(nodelist):
|
---|
304 | """ Main overview page """
|
---|
305 | items = {'root' : "." }
|
---|
306 | def fl(spaces, line):
|
---|
307 | return (' ' * spaces) + line + '\n'
|
---|
308 |
|
---|
309 | output = """
|
---|
310 | <html>
|
---|
311 | <head>
|
---|
312 | <title>Wireless leiden Configurator - GFormat</title>
|
---|
313 | <style type="text/css">
|
---|
314 | th {background-color: #999999}
|
---|
315 | tr:nth-child(odd) {background-color: #cccccc}
|
---|
316 | tr:nth-child(even) {background-color: #ffffff}
|
---|
317 | th, td {padding: 0.1em 1em}
|
---|
318 | </style>
|
---|
319 | </head>
|
---|
320 | <body>
|
---|
321 | <center>
|
---|
322 | <form type="GET" action="%(root)s">
|
---|
323 | <input type="hidden" name="action" value="update">
|
---|
324 | <input type="submit" value="Update Configuration Database (SVN)">
|
---|
325 | </form>
|
---|
326 | <table>
|
---|
327 | <caption><h3>Wireless Leiden Configurator</h3></caption>
|
---|
328 | """ % items
|
---|
329 |
|
---|
330 | for node in nodelist:
|
---|
331 | items['node'] = node
|
---|
332 | output += fl(5, '<tr>') + fl(7,'<td><a href="%(root)s/%(node)s">%(node)s</a></td>' % items)
|
---|
333 | for config in files:
|
---|
334 | items['config'] = config
|
---|
335 | output += fl(7,'<td><a href="%(root)s/%(node)s/%(config)s">%(config)s</a></td>' % items)
|
---|
336 | output += fl(5, "</tr>")
|
---|
337 | output += """
|
---|
338 | </table>
|
---|
339 | <hr />
|
---|
340 | <em>%s</em>
|
---|
341 | </center>
|
---|
342 | </body>
|
---|
343 | </html>
|
---|
344 | """ % __version__
|
---|
345 |
|
---|
346 | return output
|
---|
347 |
|
---|
348 |
|
---|
349 |
|
---|
350 | def generate_node(node):
|
---|
351 | """ Print overview of all files available for node """
|
---|
352 | return "\n".join(files)
|
---|
353 |
|
---|
354 | def generate_node_overview(host):
|
---|
355 | """ Print overview of all files available for node """
|
---|
356 | datadump = get_yaml(host)
|
---|
357 | params = { 'host' : host }
|
---|
358 | output = "<em><a href='..'>Back to overview</a></em><hr />"
|
---|
359 | output += "<h2>Available files:</h2><ul>"
|
---|
360 | for cf in files:
|
---|
361 | params['cf'] = cf
|
---|
362 | output += '<li><a href="%(host)s/%(cf)s">%(cf)s</a></li>\n' % params
|
---|
363 | output += "</ul>"
|
---|
364 |
|
---|
365 | # Generate and connection listing
|
---|
366 | output += "<h2>Connected To:</h2><ul>"
|
---|
367 | (poel, errors) = make_relations()
|
---|
368 | for network, hosts in poel.iteritems():
|
---|
369 | if host in [x[0] for x in hosts]:
|
---|
370 | if len(hosts) == 1:
|
---|
371 | # Single not connected interface
|
---|
372 | continue
|
---|
373 | for remote,ifacedump in hosts:
|
---|
374 | if remote == host:
|
---|
375 | # This side of the interface
|
---|
376 | continue
|
---|
377 | params = { 'remote': remote, 'remote_ip' : ifacedump['ip'] }
|
---|
378 | output += '<li><a href="%(remote)s">%(remote)s</a> -- %(remote_ip)s</li>\n' % params
|
---|
379 | output += "</ul>"
|
---|
380 | output += "<h2>MOTD details:</h2><pre>" + generate_motd(datadump) + "</pre>"
|
---|
381 |
|
---|
382 | output += "<hr /><em><a href='..'>Back to overview</a></em>"
|
---|
383 | return output
|
---|
384 |
|
---|
385 |
|
---|
386 | def generate_header(datadump, ctag="#"):
|
---|
387 | return """\
|
---|
388 | %(ctag)s
|
---|
389 | %(ctag)s DO NOT EDIT - Automatically generated by 'gformat'
|
---|
390 | %(ctag)s Generated at %(date)s by %(host)s from r%(revision)s
|
---|
391 | %(ctag)s
|
---|
392 | """ % { 'ctag' : ctag, 'date' : time.ctime(), 'host' : socket.gethostname(), 'revision' : datadump['autogen_revision'] }
|
---|
393 |
|
---|
394 |
|
---|
395 |
|
---|
396 | def parseaddr(s):
|
---|
397 | """ Process IPv4 CIDR notation addr to a (binary) number """
|
---|
398 | f = s.split('.')
|
---|
399 | return (long(f[0]) << 24L) + \
|
---|
400 | (long(f[1]) << 16L) + \
|
---|
401 | (long(f[2]) << 8L) + \
|
---|
402 | long(f[3])
|
---|
403 |
|
---|
404 |
|
---|
405 |
|
---|
406 | def showaddr(a):
|
---|
407 | """ Display IPv4 addr in (dotted) CIDR notation """
|
---|
408 | return "%d.%d.%d.%d" % ((a >> 24) & 0xff, (a >> 16) & 0xff, (a >> 8) & 0xff, a & 0xff)
|
---|
409 |
|
---|
410 |
|
---|
411 | def is_member(ip, mask, canidate):
|
---|
412 | """ Return True if canidate is part of ip/mask block"""
|
---|
413 | ip_addr = parseaddr(ip)
|
---|
414 | ip_canidate = parseaddr(canidate)
|
---|
415 | mask = int(mask)
|
---|
416 | ip_addr = ip_addr & ~((1 << (32 - mask)) - 1)
|
---|
417 | ip_canidate = ip_canidate & ~((1 << (32 - mask)) - 1)
|
---|
418 | return ip_addr == ip_canidate
|
---|
419 |
|
---|
420 |
|
---|
421 |
|
---|
422 | def cidr2netmask(netmask):
|
---|
423 | """ Given a 'netmask' return corresponding CIDR """
|
---|
424 | return showaddr(0xffffffff & (0xffffffff << (32 - int(netmask))))
|
---|
425 |
|
---|
426 | def get_network(addr, mask):
|
---|
427 | return showaddr(parseaddr(addr) & ~((1 << (32 - int(mask))) - 1))
|
---|
428 |
|
---|
429 |
|
---|
430 | def generate_dhcpd_conf(datadump):
|
---|
431 | """ Generate config file '/usr/local/etc/dhcpd.conf """
|
---|
432 | output = generate_header(datadump)
|
---|
433 | output += Template("""\
|
---|
434 | # option definitions common to all supported networks...
|
---|
435 | option domain-name "dhcp.{{ autogen_fqdn }}";
|
---|
436 |
|
---|
437 | default-lease-time 600;
|
---|
438 | max-lease-time 7200;
|
---|
439 |
|
---|
440 | # Use this to enble / disable dynamic dns updates globally.
|
---|
441 | #ddns-update-style none;
|
---|
442 |
|
---|
443 | # If this DHCP server is the official DHCP server for the local
|
---|
444 | # network, the authoritative directive should be uncommented.
|
---|
445 | authoritative;
|
---|
446 |
|
---|
447 | # Use this to send dhcp log messages to a different log file (you also
|
---|
448 | # have to hack syslog.conf to complete the redirection).
|
---|
449 | log-facility local7;
|
---|
450 |
|
---|
451 | #
|
---|
452 | # Interface definitions
|
---|
453 | #
|
---|
454 | \n""").render(datadump)
|
---|
455 |
|
---|
456 | dhcp_out = defaultdict(list)
|
---|
457 | for iface_key in datadump['autogen_iface_keys']:
|
---|
458 | ifname = datadump[iface_key]['autogen_ifname']
|
---|
459 | if not datadump[iface_key].has_key('comment'):
|
---|
460 | datadump[iface_key]['comment'] = None
|
---|
461 | dhcp_out[ifname].append(" ## %(autogen_ifname)s - %(comment)s\n" % datadump[iface_key])
|
---|
462 |
|
---|
463 | (addr, mask) = datadump[iface_key]['ip'].split('/')
|
---|
464 | datadump[iface_key]['autogen_addr'] = addr
|
---|
465 | datadump[iface_key]['autogen_netmask'] = cidr2netmask(mask)
|
---|
466 | datadump[iface_key]['autogen_subnet'] = get_network(addr, mask)
|
---|
467 | if dhcp_type(datadump[iface_key]) != DHCP_SERVER:
|
---|
468 | dhcp_out[ifname].append(" subnet %(autogen_subnet)s netmask %(autogen_netmask)s {\n ### not autoritive\n }\n" % \
|
---|
469 | datadump[iface_key])
|
---|
470 | continue
|
---|
471 |
|
---|
472 | (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
|
---|
473 | dhcp_part = ".".join(addr.split('.')[0:3])
|
---|
474 | datadump[iface_key]['autogen_dhcp_start'] = dhcp_part + "." + dhcp_start
|
---|
475 | datadump[iface_key]['autogen_dhcp_stop'] = dhcp_part + "." + dhcp_stop
|
---|
476 | dhcp_out[ifname].append("""\
|
---|
477 | subnet %(autogen_subnet)s netmask %(autogen_netmask)s {
|
---|
478 | range %(autogen_dhcp_start)s %(autogen_dhcp_stop)s;
|
---|
479 | option routers %(autogen_addr)s;
|
---|
480 | option domain-name-servers %(autogen_addr)s;
|
---|
481 | }
|
---|
482 | """ % datadump[iface_key])
|
---|
483 |
|
---|
484 | for ifname,value in dhcp_out.iteritems():
|
---|
485 | output += ("shared-network %s {\n" % ifname) + ''.join(value) + '}\n\n'
|
---|
486 | return output
|
---|
487 |
|
---|
488 |
|
---|
489 |
|
---|
490 | def generate_dnsmasq_conf(datadump):
|
---|
491 | """ Generate configuration file '/usr/local/etc/dnsmasq.conf' """
|
---|
492 | output = generate_header(datadump)
|
---|
493 | output += Template("""\
|
---|
494 | # DHCP server options
|
---|
495 | dhcp-authoritative
|
---|
496 | dhcp-fqdn
|
---|
497 | domain=dhcp.{{ autogen_fqdn }}
|
---|
498 | domain-needed
|
---|
499 | expand-hosts
|
---|
500 | log-async=100
|
---|
501 |
|
---|
502 | # Low memory footprint
|
---|
503 | cache-size=10000
|
---|
504 |
|
---|
505 | \n""").render(datadump)
|
---|
506 |
|
---|
507 | for iface_key in datadump['autogen_iface_keys']:
|
---|
508 | if not datadump[iface_key].has_key('comment'):
|
---|
509 | datadump[iface_key]['comment'] = None
|
---|
510 | output += "## %(autogen_ifname)s - %(comment)s\n" % datadump[iface_key]
|
---|
511 |
|
---|
512 | if dhcp_type(datadump[iface_key]) != DHCP_SERVER:
|
---|
513 | output += "# not autoritive\n\n"
|
---|
514 | continue
|
---|
515 |
|
---|
516 | (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
|
---|
517 | (ip, cidr) = datadump[iface_key]['ip'].split('/')
|
---|
518 | datadump[iface_key]['autogen_netmask'] = cidr2netmask(cidr)
|
---|
519 |
|
---|
520 | dhcp_part = ".".join(ip.split('.')[0:3])
|
---|
521 | datadump[iface_key]['autogen_dhcp_start'] = dhcp_part + "." + dhcp_start
|
---|
522 | datadump[iface_key]['autogen_dhcp_stop'] = dhcp_part + "." + dhcp_stop
|
---|
523 | output += "dhcp-range=%(autogen_ifname)s,%(autogen_dhcp_start)s,%(autogen_dhcp_stop)s,%(autogen_netmask)s,24h\n\n" % datadump[iface_key]
|
---|
524 |
|
---|
525 | return output
|
---|
526 |
|
---|
527 |
|
---|
528 | interface_list_cache = {}
|
---|
529 | def make_interface_list(datadump):
|
---|
530 | if interface_list_cache.has_key(datadump['autogen_item']):
|
---|
531 | return (interface_list_cache[datadump['autogen_item']])
|
---|
532 | # lo0 configuration:
|
---|
533 | # - 172.32.255.1/32 is the proxy.wleiden.net deflector
|
---|
534 | # - masterip is special as it needs to be assigned to at
|
---|
535 | # least one interface, so if not used assign to lo0
|
---|
536 | addrs_list = { 'lo0' : [("127.0.0.1/8", "LocalHost"), ("172.31.255.1/32","Proxy IP")] }
|
---|
537 | dhclient_if = {'lo0' : False}
|
---|
538 |
|
---|
539 | # XXX: Find some way of send this output nicely
|
---|
540 | output = ''
|
---|
541 |
|
---|
542 | masterip_used = False
|
---|
543 | for iface_key in datadump['autogen_iface_keys']:
|
---|
544 | if datadump[iface_key]['ip'].startswith(datadump['masterip']):
|
---|
545 | masterip_used = True
|
---|
546 | break
|
---|
547 | if not masterip_used:
|
---|
548 | addrs_list['lo0'].append((datadump['masterip'] + "/32", 'Master IP Not used in interface'))
|
---|
549 |
|
---|
550 | for iface_key in datadump['autogen_iface_keys']:
|
---|
551 | ifacedump = datadump[iface_key]
|
---|
552 | ifname = ifacedump['autogen_ifname']
|
---|
553 |
|
---|
554 | # Flag dhclient is possible
|
---|
555 | dhclient_if[ifname] = dhcp_type(ifacedump) == DHCP_CLIENT
|
---|
556 |
|
---|
557 | # Add interface IP to list
|
---|
558 | item = (ifacedump['ip'], ifacedump['comment'])
|
---|
559 | if addrs_list.has_key(ifname):
|
---|
560 | addrs_list[ifname].append(item)
|
---|
561 | else:
|
---|
562 | addrs_list[ifname] = [item]
|
---|
563 |
|
---|
564 | # Alias only needs IP assignment for now, this might change if we
|
---|
565 | # are going to use virtual accesspoints
|
---|
566 | if "alias" in iface_key:
|
---|
567 | continue
|
---|
568 |
|
---|
569 | # XXX: Might want to deduct type directly from interface name
|
---|
570 | if ifacedump['type'] in ['11a', '11b', '11g', 'wireless']:
|
---|
571 | # Default to station (client) mode
|
---|
572 | ifacedump['autogen_wlanmode'] = "sta"
|
---|
573 | if ifacedump['mode'] in ['master', 'master-wds', 'ap', 'ap-wds']:
|
---|
574 | ifacedump['autogen_wlanmode'] = "ap"
|
---|
575 | # Default to 802.11b mode
|
---|
576 | ifacedump['mode'] = '11b'
|
---|
577 | if ifacedump['type'] in ['11a', '11b' '11g']:
|
---|
578 | ifacedump['mode'] = ifacedump['type']
|
---|
579 |
|
---|
580 | if not ifacedump.has_key('channel'):
|
---|
581 | if ifacedump['type'] == '11a':
|
---|
582 | ifacedump['channel'] = 36
|
---|
583 | else:
|
---|
584 | ifacedump['channel'] = 1
|
---|
585 |
|
---|
586 | # Allow special hacks at the back like wds and stuff
|
---|
587 | if not ifacedump.has_key('extra'):
|
---|
588 | ifacedump['autogen_extra'] = 'regdomain ETSI country NL'
|
---|
589 | else:
|
---|
590 | ifacedump['autogen_extra'] = ifacedump['extra']
|
---|
591 |
|
---|
592 | output += "wlans_%(autogen_ifbase)s='%(autogen_ifname)s'\n" % ifacedump
|
---|
593 | output += ("create_args_%(autogen_ifname)s='wlanmode %(autogen_wlanmode)s mode " +\
|
---|
594 | "%(mode)s ssid %(ssid)s %(autogen_extra)s channel %(channel)s'\n") % ifacedump
|
---|
595 |
|
---|
596 | elif ifacedump['type'] in ['ethernet', 'eth']:
|
---|
597 | # No special config needed besides IP
|
---|
598 | pass
|
---|
599 | else:
|
---|
600 | assert False, "Unknown type " + ifacedump['type']
|
---|
601 |
|
---|
602 | store = (addrs_list, dhclient_if, output)
|
---|
603 | interface_list_cache[datadump['autogen_item']] = store
|
---|
604 | return(store)
|
---|
605 |
|
---|
606 |
|
---|
607 |
|
---|
608 | ileiden_proxies = []
|
---|
609 | normal_proxies = []
|
---|
610 | rc_conf_local_cache = {}
|
---|
611 | def generate_rc_conf_local(datadump):
|
---|
612 | """ Generate configuration file '/etc/rc.conf.local' """
|
---|
613 | item = datadump['autogen_item']
|
---|
614 | if rc_conf_local_cache.has_key(item):
|
---|
615 | return rc_conf_local_cache[item]
|
---|
616 |
|
---|
617 | if not datadump.has_key('ileiden'):
|
---|
618 | datadump['autogen_ileiden_enable'] = False
|
---|
619 | else:
|
---|
620 | datadump['autogen_ileiden_enable'] = datadump['ileiden']
|
---|
621 |
|
---|
622 | datadump['autogen_ileiden_enable'] = switchFormat(datadump['autogen_ileiden_enable'])
|
---|
623 |
|
---|
624 | if not ileiden_proxies or not normal_proxies:
|
---|
625 | for proxy in get_proxylist():
|
---|
626 | proxydump = get_yaml(proxy)
|
---|
627 | if proxydump['ileiden']:
|
---|
628 | ileiden_proxies.append(proxydump)
|
---|
629 | else:
|
---|
630 | normal_proxies.append(proxydump)
|
---|
631 | for host in get_hybridlist():
|
---|
632 | hostdump = get_yaml(host)
|
---|
633 | if hostdump['service_proxy_ileiden']:
|
---|
634 | ileiden_proxies.append(hostdump)
|
---|
635 | if hostdump['service_proxy_normal']:
|
---|
636 | normal_proxies.append(hostdump)
|
---|
637 |
|
---|
638 | datadump['autogen_ileiden_proxies'] = ileiden_proxies
|
---|
639 | datadump['autogen_normal_proxies'] = normal_proxies
|
---|
640 | datadump['autogen_ileiden_proxies_ips'] = ','.join([x['masterip'] for x in ileiden_proxies])
|
---|
641 | datadump['autogen_ileiden_proxies_names'] = ','.join([x['autogen_item'] for x in ileiden_proxies])
|
---|
642 | datadump['autogen_normal_proxies_ips'] = ','.join([x['masterip'] for x in normal_proxies])
|
---|
643 | datadump['autogen_normal_proxies_names'] = ','.join([x['autogen_item'] for x in normal_proxies])
|
---|
644 |
|
---|
645 | output = generate_header(datadump, "#");
|
---|
646 | output += render_template(datadump, """\
|
---|
647 | hostname='{{ autogen_fqdn }}'
|
---|
648 | location='{{ location }}'
|
---|
649 | nodetype="{{ nodetype }}"
|
---|
650 |
|
---|
651 | #
|
---|
652 | # Configured listings
|
---|
653 | #
|
---|
654 | captive_portal_whitelist=""
|
---|
655 | {% if nodetype == "Proxy" %}
|
---|
656 | #
|
---|
657 | # Proxy Configuration
|
---|
658 | #
|
---|
659 | {% if gateway -%}
|
---|
660 | defaultrouter="{{ gateway }}"
|
---|
661 | {% else -%}
|
---|
662 | #defaultrouter="NOTSET"
|
---|
663 | {% endif -%}
|
---|
664 | internalif="{{ internalif }}"
|
---|
665 | ileiden_enable="{{ autogen_ileiden_enable }}"
|
---|
666 | gateway_enable="{{ autogen_ileiden_enable }}"
|
---|
667 | pf_enable="yes"
|
---|
668 | pf_rules="/etc/pf.conf"
|
---|
669 | {% if autogen_ileiden_enable -%}
|
---|
670 | pf_flags="-D ext_if={{ externalif }} -D int_if={{ internalif }} -D publicnat={80,443}"
|
---|
671 | lvrouted_enable="{{ autogen_ileiden_enable }}"
|
---|
672 | lvrouted_flags="-u -s s00p3rs3kr3t -m 28"
|
---|
673 | {% else -%}
|
---|
674 | pf_flags="-D ext_if={{ externalif }} -D int_if={{ internalif }} -D publicnat={0}"
|
---|
675 | {% endif -%}
|
---|
676 | {% if internalroute -%}
|
---|
677 | static_routes="wleiden"
|
---|
678 | route_wleiden="-net 172.16.0.0/12 {{ internalroute }}"
|
---|
679 | {% endif -%}
|
---|
680 |
|
---|
681 | {% elif nodetype == "Hybrid" %}
|
---|
682 | #
|
---|
683 | # Hybrid Configuration
|
---|
684 | #
|
---|
685 | list_ileiden_proxies="
|
---|
686 | {% for item in autogen_ileiden_proxies -%}
|
---|
687 | {{ "%-16s"|format(item.masterip) }} # {{ item.autogen_realname }}
|
---|
688 | {% endfor -%}
|
---|
689 | "
|
---|
690 | list_normal_proxies="
|
---|
691 | {% for item in autogen_normal_proxies -%}
|
---|
692 | {{ "%-16s"|format(item.masterip) }} # {{ item.autogen_realname }}
|
---|
693 | {% endfor -%}
|
---|
694 | "
|
---|
695 |
|
---|
696 | captive_portal_interfaces="{{ autogen_dhcp_interfaces|join(',')|default('none', true) }}"
|
---|
697 | externalif="{{ externalif|default('vr0', true) }}"
|
---|
698 | masterip="{{ masterip }}"
|
---|
699 |
|
---|
700 | # Defined services
|
---|
701 | service_proxy_ileiden="{{ service_proxy_ileiden|yesorno }}"
|
---|
702 | service_proxy_normal="{{ service_proxy_normal|yesorno }}"
|
---|
703 | service_accesspoint="{{ service_accesspoint|yesorno }}"
|
---|
704 | service_incoming_rdr="{{ service_incoming_rdr|yesorno }}"
|
---|
705 | #
|
---|
706 |
|
---|
707 | {% if service_proxy_ileiden %}
|
---|
708 | pf_rules="/etc/pf.hybrid.conf"
|
---|
709 | pf_flags="-D ext_if=$externalif -D ext_if_net=$externalif:network -D masterip=$masterip"
|
---|
710 | pf_flags="$pf_flags -D publicnat=80,443"
|
---|
711 | {% elif service_proxy_normal or service_incoming_rdr %}
|
---|
712 | pf_rules="/etc/pf.hybrid.conf"
|
---|
713 | pf_flags="-D ext_if=$externalif -D ext_if_net=$externalif:network -D masterip=$masterip"
|
---|
714 | pf_flags="$pf_flags -D publicnat=0"
|
---|
715 | lvrouted_flags="$lvrouted_flags -z `make_list "$list_ileiden_proxies" ","`"
|
---|
716 | named_setfib="1"
|
---|
717 | tinyproxy_setfib="1"
|
---|
718 | dnsmasq_setfib="1"
|
---|
719 | sshd_setfib="1"
|
---|
720 | {% else %}
|
---|
721 | named_auto_forward_only="YES"
|
---|
722 | pf_rules="/etc/pf.node.conf"
|
---|
723 | pf_flags=""
|
---|
724 | lvrouted_flags="$lvrouted_flags -z `make_list "$list_ileiden_proxies" ","`"
|
---|
725 | {% endif %}
|
---|
726 |
|
---|
727 | {% if service_proxy_normal %}
|
---|
728 | tinyproxy_enable="yes"
|
---|
729 | {% else %}
|
---|
730 | pen_wrapper_enable="yes"
|
---|
731 | {% endif %}
|
---|
732 |
|
---|
733 | {% if service_accesspoint %}
|
---|
734 | pf_flags="$pf_flags -D captive_portal_interfaces=$captive_portal_interfaces"
|
---|
735 | {% endif %}
|
---|
736 |
|
---|
737 | {% if board == "ALIX2" %}
|
---|
738 | #
|
---|
739 | # ''Fat'' configuration, board has 256MB RAM
|
---|
740 | #
|
---|
741 | dnsmasq_enable="NO"
|
---|
742 | named_enable="YES"
|
---|
743 | {% if autogen_dhcp_interfaces -%}
|
---|
744 | dhcpd_enable="YES"
|
---|
745 | dhcpd_flags="$dhcpd_flags {{ autogen_dhcp_interfaces|join(' ') }}"
|
---|
746 | {% endif -%}
|
---|
747 | {% endif -%}
|
---|
748 |
|
---|
749 | {% if gateway %}
|
---|
750 | defaultrouter="{{ gateway }}"
|
---|
751 | {% endif %}
|
---|
752 | {% elif nodetype == "CNode" %}
|
---|
753 | #
|
---|
754 | # NODE iLeiden Configuration
|
---|
755 | #
|
---|
756 |
|
---|
757 | # iLeiden Proxies {{ autogen_ileiden_proxies_names }}
|
---|
758 | list_ileiden_proxies="{{ autogen_ileiden_proxies_ips }}"
|
---|
759 | # normal Proxies {{ autogen_normal_proxies_names }}
|
---|
760 | list_normal_proxies="{{ autogen_normal_proxies_ips }}"
|
---|
761 |
|
---|
762 | captive_portal_interfaces="{{ autogen_dhcp_interfaces|join(',') }}"
|
---|
763 |
|
---|
764 | lvrouted_flags="-u -s s00p3rs3kr3t -m 28 -z $list_ileiden_proxies"
|
---|
765 | {% endif %}
|
---|
766 |
|
---|
767 | #
|
---|
768 | # Interface definitions
|
---|
769 | #\n
|
---|
770 | """)
|
---|
771 |
|
---|
772 | (addrs_list, dhclient_if, extra_ouput) = make_interface_list(datadump)
|
---|
773 | output += extra_ouput
|
---|
774 |
|
---|
775 | # Print IP address which needs to be assigned over here
|
---|
776 | output += "\n"
|
---|
777 | for iface,addrs in sorted(addrs_list.iteritems()):
|
---|
778 | for addr, comment in sorted(addrs,key=lambda x: parseaddr(x[0].split('/')[0])):
|
---|
779 | output += "# %s || %s || %s\n" % (iface, addr, comment)
|
---|
780 |
|
---|
781 | # Write DHCLIENT entry
|
---|
782 | if dhclient_if[iface]:
|
---|
783 | output += "ifconfig_%s='SYNCDHCP'\n\n" % (iface)
|
---|
784 | else:
|
---|
785 | # Make sure the external address is always first as this is needed in the
|
---|
786 | # firewall setup
|
---|
787 | addrs = sorted(addrs,key=lambda x: x[0].split('.')[0], cmp=lambda x,y: cmp(1 if x == '172' else 0, 1 if y == '172' else 0))
|
---|
788 | output += "ipv4_addrs_%s='%s'\n\n" % (iface, " ".join([x[0] for x in addrs]))
|
---|
789 |
|
---|
790 | rc_conf_local_cache[datadump['autogen_item']] = output
|
---|
791 | return output
|
---|
792 |
|
---|
793 |
|
---|
794 |
|
---|
795 |
|
---|
796 | def get_all_configs():
|
---|
797 | """ Get dict with key 'host' with all configs present """
|
---|
798 | configs = dict()
|
---|
799 | for host in get_hostlist():
|
---|
800 | datadump = get_yaml(host)
|
---|
801 | configs[host] = datadump
|
---|
802 | return configs
|
---|
803 |
|
---|
804 |
|
---|
805 | def get_interface_keys(config):
|
---|
806 | """ Quick hack to get all interface keys, later stage convert this to a iterator """
|
---|
807 | return sorted([elem for elem in config.keys() if (elem.startswith('iface_') and not "lo0" in elem)])
|
---|
808 |
|
---|
809 |
|
---|
810 | def get_used_ips(configs):
|
---|
811 | """ Return array of all IPs used in config files"""
|
---|
812 | ip_list = []
|
---|
813 | for config in configs:
|
---|
814 | ip_list.append(config['masterip'])
|
---|
815 | for iface_key in get_interface_keys(config):
|
---|
816 | l = config[iface_key]['ip']
|
---|
817 | addr, mask = l.split('/')
|
---|
818 | # Special case do not process
|
---|
819 | if valid_addr(addr):
|
---|
820 | ip_list.append(addr)
|
---|
821 | else:
|
---|
822 | logger.error("## IP '%s' in '%s' not valid" % (addr, config['nodename']))
|
---|
823 | return sorted(ip_list)
|
---|
824 |
|
---|
825 |
|
---|
826 |
|
---|
827 | nameservers_cache = []
|
---|
828 | def get_nameservers(max_servers=None):
|
---|
829 | if nameservers_cache:
|
---|
830 | return nameservers_cache[0:max_servers]
|
---|
831 |
|
---|
832 | for host in get_hybridlist():
|
---|
833 | hostdump = get_yaml(host)
|
---|
834 | if hostdump['status'] == 'up' and (hostdump['service_proxy_ileiden'] or hostdump['service_proxy_normal']):
|
---|
835 | nameservers_cache.append((hostdump['masterip'], hostdump['autogen_realname']))
|
---|
836 | for host in get_proxylist():
|
---|
837 | hostdump = get_yaml(host)
|
---|
838 | if hostdump['status'] == 'up':
|
---|
839 | nameservers_cache.append((hostdump['masterip'], hostdump['autogen_realname']))
|
---|
840 |
|
---|
841 | return nameservers_cache[0:max_servers]
|
---|
842 |
|
---|
843 |
|
---|
844 | def generate_resolv_conf(datadump):
|
---|
845 | """ Generate configuration file '/etc/resolv.conf' """
|
---|
846 | # XXX: This should properly going to be an datastructure soon
|
---|
847 | datadump['autogen_header'] = generate_header(datadump, "#")
|
---|
848 | datadump['autogen_edge_nameservers'] = ''
|
---|
849 |
|
---|
850 |
|
---|
851 | for masterip,realname in get_nameservers():
|
---|
852 | datadump['autogen_edge_nameservers'] += "nameserver %-15s # %s\n" % (masterip, realname)
|
---|
853 |
|
---|
854 | return Template("""\
|
---|
855 | {{ autogen_header }}
|
---|
856 | search wleiden.net
|
---|
857 |
|
---|
858 | # Try local (cache) first
|
---|
859 | nameserver 127.0.0.1
|
---|
860 |
|
---|
861 | {% if service_proxy_normal or service_proxy_ileiden or nodetype == 'Proxy' -%}
|
---|
862 | nameserver 8.8.8.8 # Google Public NameServer
|
---|
863 | nameserver 8.8.4.4 # Google Public NameServer
|
---|
864 | {% else -%}
|
---|
865 | # START DYNAMIC LIST - updated by /tools/nameserver-shuffle
|
---|
866 | {{ autogen_edge_nameservers }}
|
---|
867 | {% endif -%}
|
---|
868 | """).render(datadump)
|
---|
869 |
|
---|
870 |
|
---|
871 |
|
---|
872 | def generate_ntp_conf(datadump):
|
---|
873 | """ Generate configuration file '/etc/ntp.conf' """
|
---|
874 | # XXX: This should properly going to be an datastructure soon
|
---|
875 |
|
---|
876 | datadump['autogen_header'] = generate_header(datadump, "#")
|
---|
877 | datadump['autogen_ntp_servers'] = ''
|
---|
878 | for host in get_proxylist():
|
---|
879 | hostdump = get_yaml(host)
|
---|
880 | datadump['autogen_ntp_servers'] += "server %(masterip)-15s iburst maxpoll 9 # %(autogen_realname)s\n" % hostdump
|
---|
881 | for host in get_hybridlist():
|
---|
882 | hostdump = get_yaml(host)
|
---|
883 | if hostdump['service_proxy_ileiden'] or hostdump['service_proxy_normal']:
|
---|
884 | datadump['autogen_ntp_servers'] += "server %(masterip)-15s iburst maxpoll 9 # %(autogen_realname)s\n" % hostdump
|
---|
885 |
|
---|
886 | return Template("""\
|
---|
887 | {{ autogen_header }}
|
---|
888 |
|
---|
889 | {% if service_proxy_normal or service_proxy_ileiden or nodetype == 'Proxy' -%}
|
---|
890 | # Machine hooked to internet.
|
---|
891 | server 0.nl.pool.ntp.org iburst maxpoll 9
|
---|
892 | server 1.nl.pool.ntp.org iburst maxpoll 9
|
---|
893 | server 2.nl.pool.ntp.org iburst maxpoll 9
|
---|
894 | server 3.nl.pool.ntp.org iburst maxpoll 9
|
---|
895 | {% else -%}
|
---|
896 | # Local Wireless Leiden NTP Servers.
|
---|
897 | server 0.pool.ntp.wleiden.net iburst maxpoll 9
|
---|
898 | server 1.pool.ntp.wleiden.net iburst maxpoll 9
|
---|
899 | server 2.pool.ntp.wleiden.net iburst maxpoll 9
|
---|
900 | server 3.pool.ntp.wleiden.net iburst maxpoll 9
|
---|
901 |
|
---|
902 | # All the configured NTP servers
|
---|
903 | {{ autogen_ntp_servers }}
|
---|
904 | {% endif %}
|
---|
905 |
|
---|
906 | # If a server loses sync with all upstream servers, NTP clients
|
---|
907 | # no longer follow that server. The local clock can be configured
|
---|
908 | # to provide a time source when this happens, but it should usually
|
---|
909 | # be configured on just one server on a network. For more details see
|
---|
910 | # http://support.ntp.org/bin/view/Support/UndisciplinedLocalClock
|
---|
911 | # The use of Orphan Mode may be preferable.
|
---|
912 | #
|
---|
913 | server 127.127.1.0
|
---|
914 | fudge 127.127.1.0 stratum 10
|
---|
915 | """).render(datadump)
|
---|
916 |
|
---|
917 |
|
---|
918 | def generate_pf_hybrid_conf_local(datadump):
|
---|
919 | """ Generate configuration file '/etc/pf.hybrid.conf.local' """
|
---|
920 | datadump['autogen_header'] = generate_header(datadump, "#")
|
---|
921 | return Template("""\
|
---|
922 | {{ autogen_header }}
|
---|
923 |
|
---|
924 | # Redirect some internal facing services outside (7)
|
---|
925 | # INFO: {{ rdr_rules|count }} rdr_rules (outside to internal redirect rules) defined.
|
---|
926 | {% for protocol, src_port,dest_ip,dest_port in rdr_rules -%}
|
---|
927 | rdr on $ext_if inet proto {{ protocol }} from any to $ext_if port {{ src_port }} tag SRV -> {{ dest_ip }} port {{ dest_port }}
|
---|
928 | {% endfor -%}
|
---|
929 | """).render(datadump)
|
---|
930 |
|
---|
931 | def generate_motd(datadump):
|
---|
932 | """ Generate configuration file '/etc/motd' """
|
---|
933 | output = Template("""\
|
---|
934 | FreeBSD run ``service motd onestart'' to make me look normal
|
---|
935 |
|
---|
936 | WWW: {{ autogen_fqdn }} - http://www.wirelessleiden.nl
|
---|
937 | Loc: {{ location }}
|
---|
938 |
|
---|
939 | Services:
|
---|
940 | {% if board == "ALIX2" -%}
|
---|
941 | {{" -"}} Core Node ({{ board }})
|
---|
942 | {% else -%}
|
---|
943 | {{" -"}} Hulp Node ({{ board }})
|
---|
944 | {% endif -%}
|
---|
945 | {% if service_proxy_normal -%}
|
---|
946 | {{" -"}} Normal Proxy
|
---|
947 | {% endif -%}
|
---|
948 | {% if service_proxy_ileiden -%}
|
---|
949 | {{" -"}} iLeiden Proxy
|
---|
950 | {% endif -%}
|
---|
951 | {% if service_incoming_rdr -%}
|
---|
952 | {{" -"}} Incoming port redirects
|
---|
953 | {% endif %}
|
---|
954 | Interlinks:\n
|
---|
955 | """).render(datadump)
|
---|
956 |
|
---|
957 | (addrs_list, dhclient_if, extra_ouput) = make_interface_list(datadump)
|
---|
958 | # Just nasty hack to make the formatting looks nice
|
---|
959 | iface_len = max(map(len,addrs_list.keys()))
|
---|
960 | addr_len = max(map(len,[x[0] for x in [x[0] for x in addrs_list.values()]]))
|
---|
961 | for iface,addrs in sorted(addrs_list.iteritems()):
|
---|
962 | if iface in ['lo0']:
|
---|
963 | continue
|
---|
964 | for addr, comment in sorted(addrs,key=lambda x: parseaddr(x[0].split('/')[0])):
|
---|
965 | output += " - %s || %s || %s\n" % (iface.ljust(iface_len), addr.ljust(addr_len), comment)
|
---|
966 |
|
---|
967 | output += '\n'
|
---|
968 | output += """\
|
---|
969 | Attached bridges:
|
---|
970 | """
|
---|
971 | has_item = False
|
---|
972 | for iface_key in datadump['autogen_iface_keys']:
|
---|
973 | ifacedump = datadump[iface_key]
|
---|
974 | if ifacedump.has_key('ns_ip'):
|
---|
975 | has_item = True
|
---|
976 | output += " - %(autogen_ifname)s || %(mode)s || %(ns_ip)s\n" % ifacedump
|
---|
977 | if not has_item:
|
---|
978 | output += " - none\n"
|
---|
979 |
|
---|
980 | return output
|
---|
981 |
|
---|
982 |
|
---|
983 | def format_yaml_value(value):
|
---|
984 | """ Get yaml value in right syntax for outputting """
|
---|
985 | if isinstance(value,str):
|
---|
986 | output = '"%s"' % value
|
---|
987 | else:
|
---|
988 | output = value
|
---|
989 | return output
|
---|
990 |
|
---|
991 |
|
---|
992 |
|
---|
993 | def format_wleiden_yaml(datadump):
|
---|
994 | """ Special formatting to ensure it is editable"""
|
---|
995 | output = "# Genesis config yaml style\n"
|
---|
996 | output += "# vim:ts=2:et:sw=2:ai\n"
|
---|
997 | output += "#\n"
|
---|
998 | iface_keys = [elem for elem in datadump.keys() if elem.startswith('iface_')]
|
---|
999 | for key in sorted(set(datadump.keys()) - set(iface_keys)):
|
---|
1000 | if key == 'rdr_rules':
|
---|
1001 | output += '%-10s:\n' % 'rdr_rules'
|
---|
1002 | for rdr_rule in datadump[key]:
|
---|
1003 | output += '- %s\n' % rdr_rule
|
---|
1004 | else:
|
---|
1005 | output += "%-10s: %s\n" % (key, format_yaml_value(datadump[key]))
|
---|
1006 |
|
---|
1007 | output += "\n\n"
|
---|
1008 |
|
---|
1009 | # Format (key, required)
|
---|
1010 | key_order = (
|
---|
1011 | ('comment', True),
|
---|
1012 | ('ip', True),
|
---|
1013 | ('desc', True),
|
---|
1014 | ('sdesc', True),
|
---|
1015 | ('mode', True),
|
---|
1016 | ('type', True),
|
---|
1017 | ('extra_type', False),
|
---|
1018 | ('channel', False),
|
---|
1019 | ('ssid', False),
|
---|
1020 | ('dhcp', True),
|
---|
1021 | ('compass', False),
|
---|
1022 | ('distance', False),
|
---|
1023 | ('ns_ip', False),
|
---|
1024 | ('bullet2_ip', False),
|
---|
1025 | ('ns_mac', False),
|
---|
1026 | ('bullet2_mac', False),
|
---|
1027 | ('ns_type', False),
|
---|
1028 | ('bridge_type', False),
|
---|
1029 | ('status', True),
|
---|
1030 | )
|
---|
1031 |
|
---|
1032 | for iface_key in sorted(iface_keys):
|
---|
1033 | try:
|
---|
1034 | remainder = set(datadump[iface_key].keys()) - set([x[0] for x in key_order])
|
---|
1035 | if remainder:
|
---|
1036 | raise KeyError("invalid keys: %s" % remainder)
|
---|
1037 |
|
---|
1038 | output += "%s:\n" % iface_key
|
---|
1039 | for key,required in key_order:
|
---|
1040 | if datadump[iface_key].has_key(key):
|
---|
1041 | output += " %-11s: %s\n" % (key, format_yaml_value(datadump[iface_key][key]))
|
---|
1042 | output += "\n\n"
|
---|
1043 | except Exception as e:
|
---|
1044 | print "# Error while processing interface %s" % iface_key
|
---|
1045 | raise
|
---|
1046 |
|
---|
1047 | return output
|
---|
1048 |
|
---|
1049 |
|
---|
1050 |
|
---|
1051 | def generate_wleiden_yaml(datadump, header=True):
|
---|
1052 | """ Generate (petty) version of wleiden.yaml"""
|
---|
1053 | output = generate_header(datadump, "#") if header else ''
|
---|
1054 |
|
---|
1055 | for key in datadump.keys():
|
---|
1056 | if key.startswith('autogen_'):
|
---|
1057 | del datadump[key]
|
---|
1058 | # Interface autogen cleanups
|
---|
1059 | elif type(datadump[key]) == dict:
|
---|
1060 | for key2 in datadump[key].keys():
|
---|
1061 | if key2.startswith('autogen_'):
|
---|
1062 | del datadump[key][key2]
|
---|
1063 |
|
---|
1064 | output += format_wleiden_yaml(datadump)
|
---|
1065 | return output
|
---|
1066 |
|
---|
1067 |
|
---|
1068 | def generate_yaml(datadump):
|
---|
1069 | return generate_config(datadump['nodename'], "wleiden.yaml", datadump)
|
---|
1070 |
|
---|
1071 |
|
---|
1072 |
|
---|
1073 | def generate_config(node, config, datadump=None):
|
---|
1074 | """ Print configuration file 'config' of 'node' """
|
---|
1075 | output = ""
|
---|
1076 | try:
|
---|
1077 | # Load config file
|
---|
1078 | if datadump == None:
|
---|
1079 | datadump = get_yaml(node)
|
---|
1080 |
|
---|
1081 | if config == 'wleiden.yaml':
|
---|
1082 | output += generate_wleiden_yaml(datadump)
|
---|
1083 | elif config == 'authorized_keys':
|
---|
1084 | f = open(os.path.join(NODE_DIR,"global_keys"), 'r')
|
---|
1085 | output += f.read()
|
---|
1086 | f.close()
|
---|
1087 | elif config == 'dnsmasq.conf':
|
---|
1088 | output += generate_dnsmasq_conf(datadump)
|
---|
1089 | elif config == 'dhcpd.conf':
|
---|
1090 | output += generate_dhcpd_conf(datadump)
|
---|
1091 | elif config == 'rc.conf.local':
|
---|
1092 | output += generate_rc_conf_local(datadump)
|
---|
1093 | elif config == 'resolv.conf':
|
---|
1094 | output += generate_resolv_conf(datadump)
|
---|
1095 | elif config == 'ntp.conf':
|
---|
1096 | output += generate_ntp_conf(datadump)
|
---|
1097 | elif config == 'motd':
|
---|
1098 | output += generate_motd(datadump)
|
---|
1099 | elif config == 'pf.hybrid.conf.local':
|
---|
1100 | output += generate_pf_hybrid_conf_local(datadump)
|
---|
1101 | else:
|
---|
1102 | assert False, "Config not found!"
|
---|
1103 | except IOError, e:
|
---|
1104 | output += "[ERROR] Config file not found"
|
---|
1105 | return output
|
---|
1106 |
|
---|
1107 |
|
---|
1108 |
|
---|
1109 | def process_cgi_request():
|
---|
1110 | """ When calling from CGI """
|
---|
1111 | # Update repository if requested
|
---|
1112 | form = cgi.FieldStorage()
|
---|
1113 | if form.getvalue("action") == "update":
|
---|
1114 | print "Refresh: 5; url=."
|
---|
1115 | print "Content-type:text/plain\r\n\r\n",
|
---|
1116 | print "[INFO] Updating subverion, please wait..."
|
---|
1117 | print subprocess.Popen(['svn', 'cleanup', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0],
|
---|
1118 | print subprocess.Popen(['svn', 'up', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0],
|
---|
1119 | print "[INFO] All done, redirecting in 5 seconds"
|
---|
1120 | sys.exit(0)
|
---|
1121 |
|
---|
1122 |
|
---|
1123 | base_uri = os.environ['PATH_INFO']
|
---|
1124 | uri = base_uri.strip('/').split('/')
|
---|
1125 |
|
---|
1126 | output = "Template Holder"
|
---|
1127 | content_type='text/plain'
|
---|
1128 | if base_uri.endswith('/create/network.kml'):
|
---|
1129 | content_type='application/vnd.google-earth.kml+xml'
|
---|
1130 | output = make_network_kml.make_graph()
|
---|
1131 | elif not uri[0]:
|
---|
1132 | if is_text_request():
|
---|
1133 | content_type = 'text/plain'
|
---|
1134 | output = '\n'.join(get_hostlist())
|
---|
1135 | else:
|
---|
1136 | content_type = 'text/html'
|
---|
1137 | output = generate_title(get_hostlist())
|
---|
1138 | elif len(uri) == 1:
|
---|
1139 | if is_text_request():
|
---|
1140 | content_type = 'text/plain'
|
---|
1141 | output = generate_node(uri[0])
|
---|
1142 | else:
|
---|
1143 | content_type = 'text/html'
|
---|
1144 | output = generate_node_overview(uri[0])
|
---|
1145 | elif len(uri) == 2:
|
---|
1146 | content_type = 'text/plain'
|
---|
1147 | output = generate_config(uri[0], uri[1])
|
---|
1148 | else:
|
---|
1149 | assert False, "Invalid option"
|
---|
1150 |
|
---|
1151 | print "Content-Type: %s" % content_type
|
---|
1152 | print "Content-Length: %s" % len(output)
|
---|
1153 | print ""
|
---|
1154 | print output
|
---|
1155 |
|
---|
1156 | def get_realname(datadump):
|
---|
1157 | # Proxy naming convention is special, as the proxy name is also included in
|
---|
1158 | # the nodename, when it comes to the numbered proxies.
|
---|
1159 | if datadump['nodetype'] == 'Proxy':
|
---|
1160 | realname = datadump['nodetype'] + datadump['nodename'].replace('proxy','')
|
---|
1161 | else:
|
---|
1162 | # By default the full name is listed and also a shortname CNAME for easy use.
|
---|
1163 | realname = datadump['nodetype'] + datadump['nodename']
|
---|
1164 | return(realname)
|
---|
1165 |
|
---|
1166 |
|
---|
1167 |
|
---|
1168 | def make_dns(output_dir = 'dns', external = False):
|
---|
1169 | items = dict()
|
---|
1170 |
|
---|
1171 | # hostname is key, IP is value
|
---|
1172 | wleiden_zone = defaultdict(list)
|
---|
1173 | wleiden_cname = dict()
|
---|
1174 |
|
---|
1175 | pool = dict()
|
---|
1176 | for node in get_hostlist():
|
---|
1177 | datadump = get_yaml(node)
|
---|
1178 |
|
---|
1179 | # Proxy naming convention is special
|
---|
1180 | fqdn = datadump['autogen_realname']
|
---|
1181 | if datadump['nodetype'] in ['CNode', 'Hybrid']:
|
---|
1182 | wleiden_cname[datadump['nodename']] = fqdn
|
---|
1183 |
|
---|
1184 | if datadump.has_key('rdr_host'):
|
---|
1185 | remote_target = datadump['rdr_host']
|
---|
1186 | elif datadump.has_key('remote_access') and datadump['remote_access']:
|
---|
1187 | remote_target = datadump['remote_access'].split(':')[0]
|
---|
1188 | else:
|
---|
1189 | remote_target = None
|
---|
1190 |
|
---|
1191 | if remote_target:
|
---|
1192 | try:
|
---|
1193 | parseaddr(remote_target)
|
---|
1194 | wleiden_zone[datadump['nodename'] + '.gw'].append((remote_target, False))
|
---|
1195 | except (IndexError, ValueError):
|
---|
1196 | wleiden_cname[datadump['nodename'] + '.gw'] = remote_target + '.'
|
---|
1197 |
|
---|
1198 |
|
---|
1199 | wleiden_zone[fqdn].append((datadump['masterip'], True))
|
---|
1200 |
|
---|
1201 | # Hacking to get proper DHCP IPs and hostnames
|
---|
1202 | for iface_key in get_interface_keys(datadump):
|
---|
1203 | iface_name = iface_key.replace('_','-')
|
---|
1204 | (ip, cidr) = datadump[iface_key]['ip'].split('/')
|
---|
1205 | try:
|
---|
1206 | (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
|
---|
1207 | datadump[iface_key]['autogen_netmask'] = cidr2netmask(cidr)
|
---|
1208 | dhcp_part = ".".join(ip.split('.')[0:3])
|
---|
1209 | if ip != datadump['masterip']:
|
---|
1210 | wleiden_zone["dhcp-gateway-%s.%s" % (iface_name, fqdn)].append((ip, False))
|
---|
1211 | for i in range(int(dhcp_start), int(dhcp_stop) + 1):
|
---|
1212 | wleiden_zone["dhcp-%s-%s.%s" % (i, iface_name, fqdn)].append(("%s.%s" % (dhcp_part, i), True))
|
---|
1213 | except (AttributeError, ValueError, KeyError):
|
---|
1214 | # First push it into a pool, to indentify the counter-part later on
|
---|
1215 | addr = parseaddr(ip)
|
---|
1216 | cidr = int(cidr)
|
---|
1217 | addr = addr & ~((1 << (32 - cidr)) - 1)
|
---|
1218 | if pool.has_key(addr):
|
---|
1219 | pool[addr] += [(iface_name, fqdn, ip)]
|
---|
1220 | else:
|
---|
1221 | pool[addr] = [(iface_name, fqdn, ip)]
|
---|
1222 | continue
|
---|
1223 |
|
---|
1224 |
|
---|
1225 |
|
---|
1226 | # WL uses an /29 to configure an interface. IP's are ordered like this:
|
---|
1227 | # MasterA (.1) -- DeviceA (.2) <<>> DeviceB (.3) --- SlaveB (.4)
|
---|
1228 |
|
---|
1229 | sn = lambda x: re.sub(r'(?i)^cnode','',x)
|
---|
1230 |
|
---|
1231 | # Automatic naming convention of interlinks namely 2 + remote.lower()
|
---|
1232 | for (key,value) in pool.iteritems():
|
---|
1233 | # Make sure they are sorted from low-ip to high-ip
|
---|
1234 | value = sorted(value, key=lambda x: parseaddr(x[2]))
|
---|
1235 |
|
---|
1236 | if len(value) == 1:
|
---|
1237 | (iface_name, fqdn, ip) = value[0]
|
---|
1238 | wleiden_zone["2unused-%s.%s" % (iface_name, fqdn)].append((ip, True))
|
---|
1239 |
|
---|
1240 | # Device DNS names
|
---|
1241 | if 'cnode' in fqdn.lower():
|
---|
1242 | wleiden_zone["d-at-%s.%s" % (iface_name, fqdn)].append((showaddr(parseaddr(ip) + 1), False))
|
---|
1243 | wleiden_cname["d-at-%s.%s" % (iface_name,sn(fqdn))] = "d-at-%s.%s" % ((iface_name, fqdn))
|
---|
1244 |
|
---|
1245 | elif len(value) == 2:
|
---|
1246 | (a_iface_name, a_fqdn, a_ip) = value[0]
|
---|
1247 | (b_iface_name, b_fqdn, b_ip) = value[1]
|
---|
1248 | wleiden_zone["2%s.%s" % (b_fqdn,a_fqdn)].append((a_ip, True))
|
---|
1249 | wleiden_zone["2%s.%s" % (a_fqdn,b_fqdn)].append((b_ip, True))
|
---|
1250 |
|
---|
1251 | # Device DNS names
|
---|
1252 | if 'cnode' in a_fqdn.lower() and 'cnode' in b_fqdn.lower():
|
---|
1253 | wleiden_zone["d-at-%s.%s" % (a_iface_name, a_fqdn)].append((showaddr(parseaddr(a_ip) + 1), False))
|
---|
1254 | wleiden_zone["d-at-%s.%s" % (b_iface_name, b_fqdn)].append((showaddr(parseaddr(b_ip) - 1), False))
|
---|
1255 | wleiden_cname["d-at-%s.%s" % (a_iface_name,sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
|
---|
1256 | wleiden_cname["d-at-%s.%s" % (b_iface_name,sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
|
---|
1257 | wleiden_cname["d2%s.%s" % (sn(b_fqdn),sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
|
---|
1258 | wleiden_cname["d2%s.%s" % (sn(a_fqdn),sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
|
---|
1259 |
|
---|
1260 | else:
|
---|
1261 | pool_members = [k[1] for k in value]
|
---|
1262 | for item in value:
|
---|
1263 | (iface_name, fqdn, ip) = item
|
---|
1264 | wleiden_zone["2ring.%s" % (fqdn)].append((ip, True))
|
---|
1265 |
|
---|
1266 | # Include static DNS entries
|
---|
1267 | # XXX: Should they override the autogenerated results?
|
---|
1268 | # XXX: Convert input to yaml more useable.
|
---|
1269 | # Format:
|
---|
1270 | ##; this is a comment
|
---|
1271 | ## roomburgh=CNodeRoomburgh1
|
---|
1272 | ## apkerk1.CNodeVosko=172.17.176.8 ;this as well
|
---|
1273 | dns_list = yaml.load(open(os.path.join(NODE_DIR,'../dns/staticDNS.yaml'),'r'))
|
---|
1274 |
|
---|
1275 | # Hack to allow special entries, for development
|
---|
1276 | wleiden_raw = {}
|
---|
1277 |
|
---|
1278 | for line in dns_list:
|
---|
1279 | reverse = False
|
---|
1280 | k, items = line.items()[0]
|
---|
1281 | if type(items) == dict:
|
---|
1282 | if items.has_key('reverse'):
|
---|
1283 | reverse = items['reverse']
|
---|
1284 | items = items['a']
|
---|
1285 | else:
|
---|
1286 | items = items['cname']
|
---|
1287 | items = [items] if type(items) != list else items
|
---|
1288 | for item in items:
|
---|
1289 | if item.startswith('IN '):
|
---|
1290 | wleiden_raw[k] = item
|
---|
1291 | elif valid_addr(item):
|
---|
1292 | wleiden_zone[k].append((item, reverse))
|
---|
1293 | else:
|
---|
1294 | wleiden_cname[k] = item
|
---|
1295 |
|
---|
1296 | details = dict()
|
---|
1297 | # 24 updates a day allowed
|
---|
1298 | details['serial'] = time.strftime('%Y%m%d%H')
|
---|
1299 |
|
---|
1300 | if external:
|
---|
1301 | dns_masters = ['siteview.wirelessleiden.nl', 'ns1.vanderzwet.net']
|
---|
1302 | else:
|
---|
1303 | dns_masters = ['sunny.wleiden.net'] + ["%s.wleiden.net" % x[1] for x in get_nameservers(max_servers=3)]
|
---|
1304 |
|
---|
1305 | details['master'] = dns_masters[0]
|
---|
1306 | details['ns_servers'] = '\n'.join(['\tNS\t%s.' % x for x in dns_masters])
|
---|
1307 |
|
---|
1308 | dns_header = '''
|
---|
1309 | $TTL 3h
|
---|
1310 | %(zone)s. SOA %(master)s. beheer.lijst.wirelessleiden.nl. ( %(serial)s 1d 12h 1w 60s )
|
---|
1311 | ; Serial, Refresh, Retry, Expire, Neg. cache TTL
|
---|
1312 |
|
---|
1313 | %(ns_servers)s
|
---|
1314 | \n'''
|
---|
1315 |
|
---|
1316 |
|
---|
1317 | if not os.path.isdir(output_dir):
|
---|
1318 | os.makedirs(output_dir)
|
---|
1319 | details['zone'] = 'wleiden.net'
|
---|
1320 | f = open(os.path.join(output_dir,"db." + details['zone']), "w")
|
---|
1321 | f.write(dns_header % details)
|
---|
1322 |
|
---|
1323 | for host,items in wleiden_zone.iteritems():
|
---|
1324 | for ip,reverse in items:
|
---|
1325 | if ip not in ['0.0.0.0']:
|
---|
1326 | f.write("%s.wleiden.net. IN A %s \n" % (host.lower(), ip))
|
---|
1327 | for source,dest in wleiden_cname.iteritems():
|
---|
1328 | dest = dest if dest.endswith('.') else dest + ".wleiden.net."
|
---|
1329 | f.write("%s.wleiden.net. IN CNAME %s\n" % (source.lower(), dest.lower()))
|
---|
1330 | for source, dest in wleiden_raw.iteritems():
|
---|
1331 | f.write("%s.wleiden.net. %s\n" % (source, dest))
|
---|
1332 | f.close()
|
---|
1333 |
|
---|
1334 | # Create whole bunch of specific sub arpa zones. To keep it compliant
|
---|
1335 | for s in range(16,32):
|
---|
1336 | details['zone'] = '%i.172.in-addr.arpa' % s
|
---|
1337 | f = open(os.path.join(output_dir,"db." + details['zone']), "w")
|
---|
1338 | f.write(dns_header % details)
|
---|
1339 |
|
---|
1340 | #XXX: Not effient, fix to proper data structure and do checks at other
|
---|
1341 | # stages
|
---|
1342 | for host,items in wleiden_zone.iteritems():
|
---|
1343 | for ip,reverse in items:
|
---|
1344 | if not reverse:
|
---|
1345 | continue
|
---|
1346 | if valid_addr(ip):
|
---|
1347 | if valid_addr(ip):
|
---|
1348 | if int(ip.split('.')[1]) == s:
|
---|
1349 | rev_ip = '.'.join(reversed(ip.split('.')))
|
---|
1350 | f.write("%s.in-addr.arpa. IN PTR %s.wleiden.net.\n" % (rev_ip.lower(), host.lower()))
|
---|
1351 | f.close()
|
---|
1352 |
|
---|
1353 |
|
---|
1354 | def usage():
|
---|
1355 | print """Usage: %(prog)s <argument>
|
---|
1356 | Argument:
|
---|
1357 | \tstandalone [port] = Run configurator webserver [8000]
|
---|
1358 | \tdns [outputdir] = Generate BIND compliant zone files in dns [./dns]
|
---|
1359 | \tfull-export = Generate yaml export script for heatmap.
|
---|
1360 | \tstatic [outputdir] = Generate all config files and store on disk
|
---|
1361 | \t with format ./<outputdir>/%%NODE%%/%%FILE%% [./static]
|
---|
1362 | \ttest <node> [<file>] = Receive output for certain node [all files].
|
---|
1363 | \ttest-cgi <node> <file> = Receive output of CGI script [all files].
|
---|
1364 | \tlist <status> <items> = List systems which have certain status
|
---|
1365 |
|
---|
1366 | Arguments:
|
---|
1367 | \t<node> = NodeName (example: HybridRick)
|
---|
1368 | \t<file> = %(files)s
|
---|
1369 | \t<status> = all|up|down|planned
|
---|
1370 | \t<items> = systems|nodes|proxies
|
---|
1371 |
|
---|
1372 | NOTE FOR DEVELOPERS; you can test your changes like this:
|
---|
1373 | BEFORE any changes in this code:
|
---|
1374 | $ ./gformat.py static /tmp/pre
|
---|
1375 | AFTER the changes:
|
---|
1376 | $ ./gformat.py static /tmp/post
|
---|
1377 | VIEW differences and VERIFY all are OK:
|
---|
1378 | $ diff -urI 'Generated' -r /tmp/pre /tmp/post
|
---|
1379 | """ % { 'prog' : sys.argv[0], 'files' : '|'.join(files) }
|
---|
1380 | exit(0)
|
---|
1381 |
|
---|
1382 |
|
---|
1383 | def is_text_request():
|
---|
1384 | """ Find out whether we are calling from the CLI or any text based CLI utility """
|
---|
1385 | try:
|
---|
1386 | return os.environ['HTTP_USER_AGENT'].split()[0] in ['curl', 'fetch', 'wget']
|
---|
1387 | except KeyError:
|
---|
1388 | return True
|
---|
1389 |
|
---|
1390 | def switchFormat(setting):
|
---|
1391 | if setting:
|
---|
1392 | return "YES"
|
---|
1393 | else:
|
---|
1394 | return "NO"
|
---|
1395 |
|
---|
1396 | def rlinput(prompt, prefill=''):
|
---|
1397 | import readline
|
---|
1398 | readline.set_startup_hook(lambda: readline.insert_text(prefill))
|
---|
1399 | try:
|
---|
1400 | return raw_input(prompt)
|
---|
1401 | finally:
|
---|
1402 | readline.set_startup_hook()
|
---|
1403 |
|
---|
1404 | def fix_conflict(left, right, default='i'):
|
---|
1405 | while True:
|
---|
1406 | print "## %-30s | %-30s" % (left, right)
|
---|
1407 | c = raw_input("## Solve Conflict (h for help) <l|r|e|i|> [%s]: " % default)
|
---|
1408 | if not c:
|
---|
1409 | c = default
|
---|
1410 |
|
---|
1411 | if c in ['l','1']:
|
---|
1412 | return left
|
---|
1413 | elif c in ['r','2']:
|
---|
1414 | return right
|
---|
1415 | elif c in ['e', '3']:
|
---|
1416 | return rlinput("Edit: ", "%30s | %30s" % (left, right))
|
---|
1417 | elif c in ['i', '4']:
|
---|
1418 | return None
|
---|
1419 | else:
|
---|
1420 | print "#ERROR: '%s' is invalid input (left, right, edit or ignore)!" % c
|
---|
1421 |
|
---|
1422 | def main():
|
---|
1423 | """Hard working sub"""
|
---|
1424 | # Allow easy hacking using the CLI
|
---|
1425 | if not os.environ.has_key('PATH_INFO'):
|
---|
1426 | if len(sys.argv) < 2:
|
---|
1427 | usage()
|
---|
1428 |
|
---|
1429 | if sys.argv[1] == "standalone":
|
---|
1430 | import SocketServer
|
---|
1431 | import CGIHTTPServer
|
---|
1432 | # Hop to the right working directory.
|
---|
1433 | os.chdir(os.path.dirname(__file__))
|
---|
1434 | try:
|
---|
1435 | PORT = int(sys.argv[2])
|
---|
1436 | except (IndexError,ValueError):
|
---|
1437 | PORT = 8000
|
---|
1438 |
|
---|
1439 | class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
|
---|
1440 | """ Serve this CGI from the root of the webserver """
|
---|
1441 | def is_cgi(self):
|
---|
1442 | if "favicon" in self.path:
|
---|
1443 | return False
|
---|
1444 |
|
---|
1445 | self.cgi_info = (os.path.basename(__file__), self.path)
|
---|
1446 | self.path = ''
|
---|
1447 | return True
|
---|
1448 | handler = MyCGIHTTPRequestHandler
|
---|
1449 | SocketServer.TCPServer.allow_reuse_address = True
|
---|
1450 | httpd = SocketServer.TCPServer(("", PORT), handler)
|
---|
1451 | httpd.server_name = 'localhost'
|
---|
1452 | httpd.server_port = PORT
|
---|
1453 |
|
---|
1454 | logger.info("serving at port %s", PORT)
|
---|
1455 | try:
|
---|
1456 | httpd.serve_forever()
|
---|
1457 | except KeyboardInterrupt:
|
---|
1458 | httpd.shutdown()
|
---|
1459 | logger.info("All done goodbye")
|
---|
1460 | elif sys.argv[1] == "test":
|
---|
1461 | # Basic argument validation
|
---|
1462 | try:
|
---|
1463 | node = sys.argv[2]
|
---|
1464 | datadump = get_yaml(node)
|
---|
1465 | except IndexError:
|
---|
1466 | print "Invalid argument"
|
---|
1467 | exit(1)
|
---|
1468 | except IOError as e:
|
---|
1469 | print e
|
---|
1470 | exit(1)
|
---|
1471 |
|
---|
1472 |
|
---|
1473 | # Get files to generate
|
---|
1474 | gen_files = sys.argv[3:] if len(sys.argv) > 3 else files
|
---|
1475 |
|
---|
1476 | # Actual config generation
|
---|
1477 | for config in gen_files:
|
---|
1478 | logger.info("## Generating %s %s", node, config)
|
---|
1479 | print generate_config(node, config, datadump)
|
---|
1480 | elif sys.argv[1] == "test-cgi":
|
---|
1481 | os.environ['PATH_INFO'] = "/".join(sys.argv[2:])
|
---|
1482 | os.environ['SCRIPT_NAME'] = __file__
|
---|
1483 | process_cgi_request()
|
---|
1484 | elif sys.argv[1] == "static":
|
---|
1485 | items = dict()
|
---|
1486 | items['output_dir'] = sys.argv[2] if len(sys.argv) > 2 else "./static"
|
---|
1487 | for node in get_hostlist():
|
---|
1488 | items['node'] = node
|
---|
1489 | items['wdir'] = "%(output_dir)s/%(node)s" % items
|
---|
1490 | if not os.path.isdir(items['wdir']):
|
---|
1491 | os.makedirs(items['wdir'])
|
---|
1492 | datadump = get_yaml(node)
|
---|
1493 | for config in files:
|
---|
1494 | items['config'] = config
|
---|
1495 | logger.info("## Generating %(node)s %(config)s" % items)
|
---|
1496 | f = open("%(wdir)s/%(config)s" % items, "w")
|
---|
1497 | f.write(generate_config(node, config, datadump))
|
---|
1498 | f.close()
|
---|
1499 | elif sys.argv[1] == "wind-export":
|
---|
1500 | items = dict()
|
---|
1501 | for node in get_hostlist():
|
---|
1502 | datadump = get_yaml(node)
|
---|
1503 | sql = """INSERT IGNORE INTO nodes (name, name_ns, longitude, latitude)
|
---|
1504 | VALUES ('%(nodename)s', '%(nodename)s', %(latitude)s, %(longitude)s);""" % datadump;
|
---|
1505 | sql = """INSERT IGNORE INTO users_nodes (user_id, node_id, owner)
|
---|
1506 | VALUES (
|
---|
1507 | (SELECT id FROM users WHERE username = 'rvdzwet'),
|
---|
1508 | (SELECT id FROM nodes WHERE name = '%(nodename)s'),
|
---|
1509 | 'Y');""" % datadump
|
---|
1510 | #for config in files:
|
---|
1511 | # items['config'] = config
|
---|
1512 | # print "## Generating %(node)s %(config)s" % items
|
---|
1513 | # f = open("%(wdir)s/%(config)s" % items, "w")
|
---|
1514 | # f.write(generate_config(node, config, datadump))
|
---|
1515 | # f.close()
|
---|
1516 | for node in get_hostlist():
|
---|
1517 | datadump = get_yaml(node)
|
---|
1518 | for iface_key in sorted([elem for elem in datadump.keys() if elem.startswith('iface_')]):
|
---|
1519 | ifacedump = datadump[iface_key]
|
---|
1520 | if ifacedump.has_key('mode') and ifacedump['mode'] == 'ap-wds':
|
---|
1521 | ifacedump['nodename'] = datadump['nodename']
|
---|
1522 | if not ifacedump.has_key('channel') or not ifacedump['channel']:
|
---|
1523 | ifacedump['channel'] = 0
|
---|
1524 | sql = """INSERT INTO links (node_id, type, ssid, protocol, channel, status)
|
---|
1525 | VALUES ((SELECT id FROM nodes WHERE name = '%(nodename)s'), 'ap',
|
---|
1526 | '%(ssid)s', 'IEEE 802.11b', %(channel)s, 'active');""" % ifacedump
|
---|
1527 | elif sys.argv[1] == "full-export":
|
---|
1528 | hosts = {}
|
---|
1529 | for node in get_hostlist():
|
---|
1530 | datadump = get_yaml(node)
|
---|
1531 | hosts[datadump['nodename']] = datadump
|
---|
1532 | print yaml.dump(hosts)
|
---|
1533 |
|
---|
1534 | elif sys.argv[1] == "dns":
|
---|
1535 | make_dns(sys.argv[2] if len(sys.argv) > 2 else 'dns', 'external' in sys.argv)
|
---|
1536 | elif sys.argv[1] == "cleanup":
|
---|
1537 | # First generate all datadumps
|
---|
1538 | datadumps = dict()
|
---|
1539 | ssid_to_node = dict()
|
---|
1540 | for host in get_hostlist():
|
---|
1541 | logger.info("# Processing: %s", host)
|
---|
1542 | # Set some boring default values
|
---|
1543 | datadump = { 'board' : 'UNKNOWN' }
|
---|
1544 | datadump.update(get_yaml(host))
|
---|
1545 | datadumps[datadump['autogen_realname']] = datadump
|
---|
1546 |
|
---|
1547 | (poel, errors) = make_relations(datadumps)
|
---|
1548 | print "\n".join(["# WARNING: %s" % x for x in errors])
|
---|
1549 |
|
---|
1550 | for host,datadump in datadumps.iteritems():
|
---|
1551 | try:
|
---|
1552 | # Convert all yes and no to boolean values
|
---|
1553 | def fix_boolean(dump):
|
---|
1554 | for key in dump.keys():
|
---|
1555 | if type(dump[key]) == dict:
|
---|
1556 | dump[key] = fix_boolean(dump[key])
|
---|
1557 | elif str(dump[key]).lower() in ["yes", "true"]:
|
---|
1558 | dump[key] = True
|
---|
1559 | elif str(dump[key]).lower() in ["no", "false"]:
|
---|
1560 | # Compass richting no (Noord Oost) is valid input
|
---|
1561 | if key != "compass": dump[key] = False
|
---|
1562 | return dump
|
---|
1563 | datadump = fix_boolean(datadump)
|
---|
1564 |
|
---|
1565 | if datadump['rdnap_x'] and datadump['rdnap_y']:
|
---|
1566 | datadump['latitude'], datadump['longitude'] = rdnap.rd2etrs(datadump['rdnap_x'], datadump['rdnap_y'])
|
---|
1567 | elif datadump['latitude'] and datadump['longitude']:
|
---|
1568 | datadump['rdnap_x'], datadump['rdnap_y'] = rdnap.etrs2rd(datadump['latitude'], datadump['longitude'])
|
---|
1569 |
|
---|
1570 | if datadump['nodename'].startswith('Proxy'):
|
---|
1571 | datadump['nodename'] = datadump['nodename'].lower()
|
---|
1572 |
|
---|
1573 | for iface_key in datadump['autogen_iface_keys']:
|
---|
1574 | try:
|
---|
1575 | # All our normal wireless cards are normal APs now
|
---|
1576 | if datadump[iface_key]['type'] in ['11a', '11b', '11g', 'wireless']:
|
---|
1577 | datadump[iface_key]['mode'] = 'ap'
|
---|
1578 | # Wireless Leiden SSID have an consistent lowercase/uppercase
|
---|
1579 | if datadump[iface_key].has_key('ssid'):
|
---|
1580 | ssid = datadump[iface_key]['ssid']
|
---|
1581 | prefix = 'ap-WirelessLeiden-'
|
---|
1582 | if ssid.lower().startswith(prefix.lower()):
|
---|
1583 | datadump[iface_key]['ssid'] = prefix + ssid[len(prefix)].upper() + ssid[len(prefix) + 1:]
|
---|
1584 | if datadump[iface_key].has_key('ns_ip') and not datadump[iface_key].has_key('mode'):
|
---|
1585 | datadump[iface_key]['mode'] = 'autogen-FIXME'
|
---|
1586 | if not datadump[iface_key].has_key('comment'):
|
---|
1587 | datadump[iface_key]['comment'] = 'autogen-FIXME'
|
---|
1588 |
|
---|
1589 | if datadump[iface_key]['comment'].startswith('autogen-') and datadump[iface_key].has_key('comment'):
|
---|
1590 | datadump[iface_key] = datadump[iface_key]['desc']
|
---|
1591 |
|
---|
1592 | x = datadump[iface_key]['comment']
|
---|
1593 | datadump[iface_key]['comment'] = x[0].upper() + x[1:]
|
---|
1594 |
|
---|
1595 |
|
---|
1596 | if datadump[iface_key].has_key('desc'):
|
---|
1597 | if datadump[iface_key]['comment'].lower() == datadump[iface_key]['desc'].lower():
|
---|
1598 | del datadump[iface_key]['desc']
|
---|
1599 | else:
|
---|
1600 | print "# ERROR: At %s - %s" % (datadump['nodename'], iface_key)
|
---|
1601 | response = fix_conflict(datadump[iface_key]['comment'], datadump[iface_key]['desc'])
|
---|
1602 | if response:
|
---|
1603 | datadump[iface_key]['comment'] = response
|
---|
1604 | del datadump[iface_key]['desc']
|
---|
1605 |
|
---|
1606 | # Check DHCP configuration
|
---|
1607 | dhcp_type(datadump[iface_key])
|
---|
1608 |
|
---|
1609 | # Set the compass value based on the angle between the poels
|
---|
1610 | if datadump[iface_key].has_key('ns_ip'):
|
---|
1611 | my_pool = poel[network(datadump[iface_key]['ip'])]
|
---|
1612 | remote_hosts = list(set([x[0] for x in my_pool]) - set([host]))
|
---|
1613 | if remote_hosts:
|
---|
1614 | compass_target = remote_hosts[0]
|
---|
1615 | datadump[iface_key]['compass'] = cd_between_hosts(host, compass_target, datadumps)
|
---|
1616 | except Exception as e:
|
---|
1617 | print "# Error while processing interface %s" % iface_key
|
---|
1618 | raise
|
---|
1619 | store_yaml(datadump)
|
---|
1620 | except Exception as e:
|
---|
1621 | print "# Error while processing %s" % host
|
---|
1622 | raise
|
---|
1623 | elif sys.argv[1] == "list":
|
---|
1624 | use_fqdn = False
|
---|
1625 | if len(sys.argv) < 4 or not sys.argv[2] in ["up", "down", "planned", "all"]:
|
---|
1626 | usage()
|
---|
1627 | if sys.argv[3] == "nodes":
|
---|
1628 | systems = get_nodelist()
|
---|
1629 | elif sys.argv[3] == "proxies":
|
---|
1630 | systems = get_proxylist()
|
---|
1631 | elif sys.argv[3] == "systems":
|
---|
1632 | systems = get_hostlist()
|
---|
1633 | else:
|
---|
1634 | usage()
|
---|
1635 | if len(sys.argv) > 4:
|
---|
1636 | if sys.argv[4] == "fqdn":
|
---|
1637 | use_fqdn = True
|
---|
1638 | else:
|
---|
1639 | usage()
|
---|
1640 |
|
---|
1641 | for system in systems:
|
---|
1642 | datadump = get_yaml(system)
|
---|
1643 |
|
---|
1644 | output = datadump['autogen_fqdn'] if use_fqdn else system
|
---|
1645 | if sys.argv[2] == "all":
|
---|
1646 | print output
|
---|
1647 | elif datadump['status'] == sys.argv[2]:
|
---|
1648 | print output
|
---|
1649 | elif sys.argv[1] == "create":
|
---|
1650 | if sys.argv[2] == "network.kml":
|
---|
1651 | print make_network_kml.make_graph()
|
---|
1652 | else:
|
---|
1653 | usage()
|
---|
1654 | usage()
|
---|
1655 | else:
|
---|
1656 | # Do not enable debugging for config requests as it highly clutters the output
|
---|
1657 | if not is_text_request():
|
---|
1658 | cgitb.enable()
|
---|
1659 | process_cgi_request()
|
---|
1660 |
|
---|
1661 |
|
---|
1662 | if __name__ == "__main__":
|
---|
1663 | main()
|
---|