source: genesis/tools/gformat.py@ 10932

Last change on this file since 10932 was 10932, checked in by rick, 12 years ago

None is not a empty dict item.

  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 53.9 KB
Line 
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.
19import sys
20import os
21import re
22sys.path.append(os.path.dirname(__file__))
23
24import cgi
25import cgitb
26import copy
27import glob
28import socket
29import string
30import subprocess
31import time
32import rdnap
33import math
34import make_network_kml
35from pprint import pprint
36from collections import defaultdict
37try:
38 import yaml
39except ImportError, e:
40 print e
41 print "[ERROR] Please install the python-yaml or devel/py-yaml package"
42 exit(1)
43
44try:
45 from yaml import CLoader as Loader
46 from yaml import CDumper as Dumper
47except ImportError:
48 from yaml import Loader, Dumper
49
50from jinja2 import Environment, Template
51def yesorno(value):
52 return "YES" if bool(value) else "NO"
53env = Environment()
54env.filters['yesorno'] = yesorno
55def 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
67import logging
68logging.basicConfig(format='# %(levelname)s: %(message)s' )
69logger = logging.getLogger()
70logger.setLevel(logging.DEBUG)
71
72
73if os.environ.has_key('CONFIGROOT'):
74 NODE_DIR = os.environ['CONFIGROOT']
75else:
76 NODE_DIR = os.path.abspath(os.path.dirname(__file__)) + '/../nodes'
77__version__ = '$Id: gformat.py 10932 2012-05-20 00:04:23Z rick $'
78
79files = [
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
92OK = 10
93DOWN = 20
94UNKNOWN = 90
95
96datadump_cache = {}
97
98NO_DHCP = 0
99DHCP_CLIENT = 10
100DHCP_SERVER = 20
101def 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
117def 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
188def 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
200def 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
210def 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
231def valid_addr(addr):
232 """ Show which address is valid in which are not """
233 return str(addr).startswith('172.')
234
235def 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
238get_hybridlist = lambda: get_system_list("Hybrid")
239get_nodelist = lambda: get_system_list("CNode")
240get_proxylist = lambda: get_system_list("Proxy")
241
242def get_hostlist():
243 """ Combined hosts and proxy list"""
244 return get_nodelist() + get_proxylist() + get_hybridlist()
245
246def 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
258def 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
289def 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
303def 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
350def generate_node(node):
351 """ Print overview of all files available for node """
352 return "\n".join(files)
353
354def 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
386def 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
396def 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
406def 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
411def 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
422def cidr2netmask(netmask):
423 """ Given a 'netmask' return corresponding CIDR """
424 return showaddr(0xffffffff & (0xffffffff << (32 - int(netmask))))
425
426def get_network(addr, mask):
427 return showaddr(parseaddr(addr) & ~((1 << (32 - int(mask))) - 1))
428
429
430def 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...
435option domain-name "dhcp.{{ autogen_fqdn }}";
436
437default-lease-time 600;
438max-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.
445authoritative;
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).
449log-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
490def 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
495dhcp-authoritative
496dhcp-fqdn
497domain=dhcp.{{ autogen_fqdn }}
498domain-needed
499expand-hosts
500log-async=100
501
502# Low memory footprint
503cache-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
528interface_list_cache = {}
529def 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
608ileiden_proxies = []
609normal_proxies = []
610rc_conf_local_cache = {}
611def 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, """\
647hostname='{{ autogen_fqdn }}'
648location='{{ location }}'
649nodetype="{{ nodetype }}"
650
651#
652# Configured listings
653#
654captive_portal_whitelist=""
655{% if nodetype == "Proxy" %}
656#
657# Proxy Configuration
658#
659{% if gateway -%}
660defaultrouter="{{ gateway }}"
661{% else -%}
662#defaultrouter="NOTSET"
663{% endif -%}
664internalif="{{ internalif }}"
665ileiden_enable="{{ autogen_ileiden_enable }}"
666gateway_enable="{{ autogen_ileiden_enable }}"
667pf_enable="yes"
668pf_rules="/etc/pf.conf"
669{% if autogen_ileiden_enable -%}
670pf_flags="-D ext_if={{ externalif }} -D int_if={{ internalif }} -D publicnat={80,443}"
671lvrouted_enable="{{ autogen_ileiden_enable }}"
672lvrouted_flags="-u -s s00p3rs3kr3t -m 28"
673{% else -%}
674pf_flags="-D ext_if={{ externalif }} -D int_if={{ internalif }} -D publicnat={0}"
675{% endif -%}
676{% if internalroute -%}
677static_routes="wleiden"
678route_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 pf_rules="/etc/pf.node.conf"
722 pf_flags=""
723 lvrouted_flags="$lvrouted_flags -z `make_list "$list_ileiden_proxies" ","`"
724 {% endif %}
725
726 {% if service_proxy_normal %}
727 tinyproxy_enable="yes"
728 {% else %}
729 pen_wrapper_enable="yes"
730 {% endif %}
731
732 {% if service_accesspoint %}
733 pf_flags="$pf_flags -D captive_portal_interfaces=$captive_portal_interfaces"
734 {% endif %}
735
736 {% if board == "ALIX2" %}
737 #
738 # ''Fat'' configuration, board has 256MB RAM
739 #
740 dnsmasq_enable="NO"
741 named_enable="YES"
742 {% if autogen_dhcp_interfaces -%}
743 dhcpd_enable="YES"
744 dhcpd_flags="$dhcpd_flags {{ autogen_dhcp_interfaces|join(' ') }}"
745 {% endif -%}
746 {% endif -%}
747
748 {% if gateway %}
749 defaultrouter="{{ gateway }}"
750 {% endif %}
751{% elif nodetype == "CNode" %}
752#
753# NODE iLeiden Configuration
754#
755
756# iLeiden Proxies {{ autogen_ileiden_proxies_names }}
757list_ileiden_proxies="{{ autogen_ileiden_proxies_ips }}"
758# normal Proxies {{ autogen_normal_proxies_names }}
759list_normal_proxies="{{ autogen_normal_proxies_ips }}"
760
761captive_portal_interfaces="{{ autogen_dhcp_interfaces|join(',') }}"
762
763lvrouted_flags="-u -s s00p3rs3kr3t -m 28 -z $list_ileiden_proxies"
764{% endif %}
765
766#
767# Interface definitions
768#\n
769""")
770
771 (addrs_list, dhclient_if, extra_ouput) = make_interface_list(datadump)
772 output += extra_ouput
773
774 # Print IP address which needs to be assigned over here
775 output += "\n"
776 for iface,addrs in sorted(addrs_list.iteritems()):
777 for addr, comment in sorted(addrs,key=lambda x: parseaddr(x[0].split('/')[0])):
778 output += "# %s || %s || %s\n" % (iface, addr, comment)
779
780 # Write DHCLIENT entry
781 if dhclient_if[iface]:
782 output += "ifconfig_%s='SYNCDHCP'\n\n" % (iface)
783 else:
784 # Make sure the external address is always first as this is needed in the
785 # firewall setup
786 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))
787 output += "ipv4_addrs_%s='%s'\n\n" % (iface, " ".join([x[0] for x in addrs]))
788
789 rc_conf_local_cache[datadump['autogen_item']] = output
790 return output
791
792
793
794
795def get_all_configs():
796 """ Get dict with key 'host' with all configs present """
797 configs = dict()
798 for host in get_hostlist():
799 datadump = get_yaml(host)
800 configs[host] = datadump
801 return configs
802
803
804def get_interface_keys(config):
805 """ Quick hack to get all interface keys, later stage convert this to a iterator """
806 return sorted([elem for elem in config.keys() if (elem.startswith('iface_') and not "lo0" in elem)])
807
808
809def get_used_ips(configs):
810 """ Return array of all IPs used in config files"""
811 ip_list = []
812 for config in configs:
813 ip_list.append(config['masterip'])
814 for iface_key in get_interface_keys(config):
815 l = config[iface_key]['ip']
816 addr, mask = l.split('/')
817 # Special case do not process
818 if valid_addr(addr):
819 ip_list.append(addr)
820 else:
821 logger.error("## IP '%s' in '%s' not valid" % (addr, config['nodename']))
822 return sorted(ip_list)
823
824
825
826def generate_resolv_conf(datadump):
827 """ Generate configuration file '/etc/resolv.conf' """
828 # XXX: This should properly going to be an datastructure soon
829 datadump['autogen_header'] = generate_header(datadump, "#")
830 datadump['autogen_edge_nameservers'] = ''
831 for host in get_proxylist():
832 hostdump = get_yaml(host)
833 datadump['autogen_edge_nameservers'] += "nameserver %(masterip)-15s # %(autogen_realname)s\n" % hostdump
834 for host in get_hybridlist():
835 hostdump = get_yaml(host)
836 if hostdump['service_proxy_ileiden'] or hostdump['service_proxy_normal']:
837 datadump['autogen_edge_nameservers'] += "nameserver %(masterip)-15s # %(autogen_realname)s\n" % hostdump
838
839 return Template("""\
840{{ autogen_header }}
841search wleiden.net
842
843# Try local (cache) first
844nameserver 127.0.0.1
845
846{% if service_proxy_normal or service_proxy_ileiden or nodetype == 'Proxy' -%}
847nameserver 8.8.8.8 # Google Public NameServer
848nameserver 8.8.4.4 # Google Public NameServer
849{% else -%}
850# START DYNAMIC LIST - updated by /tools/nameserver-shuffle
851{{ autogen_edge_nameservers }}
852{% endif -%}
853""").render(datadump)
854
855
856
857def generate_ntp_conf(datadump):
858 """ Generate configuration file '/etc/ntp.conf' """
859 # XXX: This should properly going to be an datastructure soon
860
861 datadump['autogen_header'] = generate_header(datadump, "#")
862 datadump['autogen_ntp_servers'] = ''
863 for host in get_proxylist():
864 hostdump = get_yaml(host)
865 datadump['autogen_ntp_servers'] += "server %(masterip)-15s iburst maxpoll 9 # %(autogen_realname)s\n" % hostdump
866 for host in get_hybridlist():
867 hostdump = get_yaml(host)
868 if hostdump['service_proxy_ileiden'] or hostdump['service_proxy_normal']:
869 datadump['autogen_ntp_servers'] += "server %(masterip)-15s iburst maxpoll 9 # %(autogen_realname)s\n" % hostdump
870
871 return Template("""\
872{{ autogen_header }}
873
874{% if service_proxy_normal or service_proxy_ileiden or nodetype == 'Proxy' -%}
875# Machine hooked to internet.
876server 0.nl.pool.ntp.org iburst maxpoll 9
877server 1.nl.pool.ntp.org iburst maxpoll 9
878server 2.nl.pool.ntp.org iburst maxpoll 9
879server 3.nl.pool.ntp.org iburst maxpoll 9
880{% else -%}
881# Local Wireless Leiden NTP Servers.
882server 0.pool.ntp.wleiden.net iburst maxpoll 9
883server 1.pool.ntp.wleiden.net iburst maxpoll 9
884server 2.pool.ntp.wleiden.net iburst maxpoll 9
885server 3.pool.ntp.wleiden.net iburst maxpoll 9
886
887# All the configured NTP servers
888{{ autogen_ntp_servers }}
889{% endif %}
890
891# If a server loses sync with all upstream servers, NTP clients
892# no longer follow that server. The local clock can be configured
893# to provide a time source when this happens, but it should usually
894# be configured on just one server on a network. For more details see
895# http://support.ntp.org/bin/view/Support/UndisciplinedLocalClock
896# The use of Orphan Mode may be preferable.
897#
898server 127.127.1.0
899fudge 127.127.1.0 stratum 10
900""").render(datadump)
901
902
903def generate_pf_hybrid_conf_local(datadump):
904 """ Generate configuration file '/etc/pf.hybrid.conf.local' """
905 datadump['autogen_header'] = generate_header(datadump, "#")
906 return Template("""\
907{{ autogen_header }}
908
909# Redirect some internal facing services outside (7)
910# INFO: {{ rdr_rules|count }} rdr_rules (outside to internal redirect rules) defined.
911{% for protocol, src_port,dest_ip,dest_port in rdr_rules -%}
912rdr on $ext_if inet proto {{ protocol }} from any to $ext_if port {{ src_port }} tag SRV -> {{ dest_ip }} port {{ dest_port }}
913{% endfor -%}
914""").render(datadump)
915
916def generate_motd(datadump):
917 """ Generate configuration file '/etc/motd' """
918 output = Template("""\
919FreeBSD run ``service motd onestart'' to make me look normal
920
921 WWW: {{ autogen_fqdn }} - http://www.wirelessleiden.nl
922 Loc: {{ location }}
923
924Services:
925{% if board == "ALIX2" -%}
926{{" -"}} Core Node ({{ board }})
927{% else -%}
928{{" -"}} Hulp Node ({{ board }})
929{% endif -%}
930{% if service_proxy_normal -%}
931{{" -"}} Normal Proxy
932{% endif -%}
933{% if service_proxy_ileiden -%}
934{{" -"}} iLeiden Proxy
935{% endif -%}
936{% if service_incoming_rdr -%}
937{{" -"}} Incoming port redirects
938{% endif %}
939Interlinks:\n
940""").render(datadump)
941
942 (addrs_list, dhclient_if, extra_ouput) = make_interface_list(datadump)
943 # Just nasty hack to make the formatting looks nice
944 iface_len = max(map(len,addrs_list.keys()))
945 addr_len = max(map(len,[x[0] for x in [x[0] for x in addrs_list.values()]]))
946 for iface,addrs in sorted(addrs_list.iteritems()):
947 if iface in ['lo0']:
948 continue
949 for addr, comment in sorted(addrs,key=lambda x: parseaddr(x[0].split('/')[0])):
950 output += " - %s || %s || %s\n" % (iface.ljust(iface_len), addr.ljust(addr_len), comment)
951
952 output += '\n'
953 output += """\
954Attached bridges:
955"""
956 has_item = False
957 for iface_key in datadump['autogen_iface_keys']:
958 ifacedump = datadump[iface_key]
959 if ifacedump.has_key('ns_ip'):
960 has_item = True
961 output += " - %(autogen_ifname)s || %(mode)s || %(ns_ip)s\n" % ifacedump
962 if not has_item:
963 output += " - none\n"
964
965 return output
966
967
968def format_yaml_value(value):
969 """ Get yaml value in right syntax for outputting """
970 if isinstance(value,str):
971 output = '"%s"' % value
972 else:
973 output = value
974 return output
975
976
977
978def format_wleiden_yaml(datadump):
979 """ Special formatting to ensure it is editable"""
980 output = "# Genesis config yaml style\n"
981 output += "# vim:ts=2:et:sw=2:ai\n"
982 output += "#\n"
983 iface_keys = [elem for elem in datadump.keys() if elem.startswith('iface_')]
984 for key in sorted(set(datadump.keys()) - set(iface_keys)):
985 if key == 'rdr_rules':
986 output += '%-10s:\n' % 'rdr_rules'
987 for rdr_rule in datadump[key]:
988 output += '- %s\n' % rdr_rule
989 else:
990 output += "%-10s: %s\n" % (key, format_yaml_value(datadump[key]))
991
992 output += "\n\n"
993
994 # Format (key, required)
995 key_order = (
996 ('comment', True),
997 ('ip', True),
998 ('desc', True),
999 ('sdesc', True),
1000 ('mode', True),
1001 ('type', True),
1002 ('extra_type', False),
1003 ('channel', False),
1004 ('ssid', False),
1005 ('dhcp', True),
1006 ('compass', False),
1007 ('distance', False),
1008 ('ns_ip', False),
1009 ('bullet2_ip', False),
1010 ('ns_mac', False),
1011 ('bullet2_mac', False),
1012 ('ns_type', False),
1013 ('bridge_type', False),
1014 ('status', True),
1015 )
1016
1017 for iface_key in sorted(iface_keys):
1018 try:
1019 remainder = set(datadump[iface_key].keys()) - set([x[0] for x in key_order])
1020 if remainder:
1021 raise KeyError("invalid keys: %s" % remainder)
1022
1023 output += "%s:\n" % iface_key
1024 for key,required in key_order:
1025 if datadump[iface_key].has_key(key):
1026 output += " %-11s: %s\n" % (key, format_yaml_value(datadump[iface_key][key]))
1027 output += "\n\n"
1028 except Exception as e:
1029 print "# Error while processing interface %s" % iface_key
1030 raise
1031
1032 return output
1033
1034
1035
1036def generate_wleiden_yaml(datadump, header=True):
1037 """ Generate (petty) version of wleiden.yaml"""
1038 output = generate_header(datadump, "#") if header else ''
1039
1040 for key in datadump.keys():
1041 if key.startswith('autogen_'):
1042 del datadump[key]
1043 # Interface autogen cleanups
1044 elif type(datadump[key]) == dict:
1045 for key2 in datadump[key].keys():
1046 if key2.startswith('autogen_'):
1047 del datadump[key][key2]
1048
1049 output += format_wleiden_yaml(datadump)
1050 return output
1051
1052
1053def generate_yaml(datadump):
1054 return generate_config(datadump['nodename'], "wleiden.yaml", datadump)
1055
1056
1057
1058def generate_config(node, config, datadump=None):
1059 """ Print configuration file 'config' of 'node' """
1060 output = ""
1061 try:
1062 # Load config file
1063 if datadump == None:
1064 datadump = get_yaml(node)
1065
1066 if config == 'wleiden.yaml':
1067 output += generate_wleiden_yaml(datadump)
1068 elif config == 'authorized_keys':
1069 f = open(os.path.join(NODE_DIR,"global_keys"), 'r')
1070 output += f.read()
1071 f.close()
1072 elif config == 'dnsmasq.conf':
1073 output += generate_dnsmasq_conf(datadump)
1074 elif config == 'dhcpd.conf':
1075 output += generate_dhcpd_conf(datadump)
1076 elif config == 'rc.conf.local':
1077 output += generate_rc_conf_local(datadump)
1078 elif config == 'resolv.conf':
1079 output += generate_resolv_conf(datadump)
1080 elif config == 'ntp.conf':
1081 output += generate_ntp_conf(datadump)
1082 elif config == 'motd':
1083 output += generate_motd(datadump)
1084 elif config == 'pf.hybrid.conf.local':
1085 output += generate_pf_hybrid_conf_local(datadump)
1086 else:
1087 assert False, "Config not found!"
1088 except IOError, e:
1089 output += "[ERROR] Config file not found"
1090 return output
1091
1092
1093
1094def process_cgi_request():
1095 """ When calling from CGI """
1096 # Update repository if requested
1097 form = cgi.FieldStorage()
1098 if form.getvalue("action") == "update":
1099 print "Refresh: 5; url=."
1100 print "Content-type:text/plain\r\n\r\n",
1101 print "[INFO] Updating subverion, please wait..."
1102 print subprocess.Popen(['svn', 'cleanup', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0],
1103 print subprocess.Popen(['svn', 'up', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0],
1104 print "[INFO] All done, redirecting in 5 seconds"
1105 sys.exit(0)
1106
1107
1108 base_uri = os.environ['PATH_INFO']
1109 uri = base_uri.strip('/').split('/')
1110
1111 output = "Template Holder"
1112 content_type='text/plain'
1113 if base_uri.endswith('/create/network.kml'):
1114 content_type='application/vnd.google-earth.kml+xml'
1115 output = make_network_kml.make_graph()
1116 elif not uri[0]:
1117 if is_text_request():
1118 content_type = 'text/plain'
1119 output = '\n'.join(get_hostlist())
1120 else:
1121 content_type = 'text/html'
1122 output = generate_title(get_hostlist())
1123 elif len(uri) == 1:
1124 if is_text_request():
1125 content_type = 'text/plain'
1126 output = generate_node(uri[0])
1127 else:
1128 content_type = 'text/html'
1129 output = generate_node_overview(uri[0])
1130 elif len(uri) == 2:
1131 content_type = 'text/plain'
1132 output = generate_config(uri[0], uri[1])
1133 else:
1134 assert False, "Invalid option"
1135
1136 print "Content-Type: %s" % content_type
1137 print "Content-Length: %s" % len(output)
1138 print ""
1139 print output
1140
1141def get_realname(datadump):
1142 # Proxy naming convention is special, as the proxy name is also included in
1143 # the nodename, when it comes to the numbered proxies.
1144 if datadump['nodetype'] == 'Proxy':
1145 realname = datadump['nodetype'] + datadump['nodename'].replace('proxy','')
1146 else:
1147 # By default the full name is listed and also a shortname CNAME for easy use.
1148 realname = datadump['nodetype'] + datadump['nodename']
1149 return(realname)
1150
1151
1152
1153def make_dns(output_dir = 'dns', external = False):
1154 items = dict()
1155
1156 # hostname is key, IP is value
1157 wleiden_zone = defaultdict(list)
1158 wleiden_cname = dict()
1159
1160 pool = dict()
1161 for node in get_hostlist():
1162 datadump = get_yaml(node)
1163
1164 # Proxy naming convention is special
1165 fqdn = datadump['autogen_realname']
1166 if datadump['nodetype'] in ['CNode', 'Hybrid']:
1167 wleiden_cname[datadump['nodename']] = fqdn
1168
1169 if datadump.has_key('rdr_host'):
1170 remote_target = datadump['rdr_host']
1171 elif datadump.has_key('remote_access') and datadump['remote_access']:
1172 remote_target = datadump['remote_access'].split(':')[0]
1173 else:
1174 remote_target = None
1175
1176 if remote_target:
1177 try:
1178 parseaddr(remote_target)
1179 wleiden_zone[datadump['nodename'] + '.gw'].append((remote_target, False))
1180 except (IndexError, ValueError):
1181 wleiden_cname[datadump['nodename'] + '.gw'] = remote_target + '.'
1182
1183
1184 wleiden_zone[fqdn].append((datadump['masterip'], True))
1185
1186 # Hacking to get proper DHCP IPs and hostnames
1187 for iface_key in get_interface_keys(datadump):
1188 iface_name = iface_key.replace('_','-')
1189 (ip, cidr) = datadump[iface_key]['ip'].split('/')
1190 try:
1191 (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
1192 datadump[iface_key]['autogen_netmask'] = cidr2netmask(cidr)
1193 dhcp_part = ".".join(ip.split('.')[0:3])
1194 if ip != datadump['masterip']:
1195 wleiden_zone["dhcp-gateway-%s.%s" % (iface_name, fqdn)].append((ip, False))
1196 for i in range(int(dhcp_start), int(dhcp_stop) + 1):
1197 wleiden_zone["dhcp-%s-%s.%s" % (i, iface_name, fqdn)].append(("%s.%s" % (dhcp_part, i), True))
1198 except (AttributeError, ValueError, KeyError):
1199 # First push it into a pool, to indentify the counter-part later on
1200 addr = parseaddr(ip)
1201 cidr = int(cidr)
1202 addr = addr & ~((1 << (32 - cidr)) - 1)
1203 if pool.has_key(addr):
1204 pool[addr] += [(iface_name, fqdn, ip)]
1205 else:
1206 pool[addr] = [(iface_name, fqdn, ip)]
1207 continue
1208
1209
1210
1211 # WL uses an /29 to configure an interface. IP's are ordered like this:
1212 # MasterA (.1) -- DeviceA (.2) <<>> DeviceB (.3) --- SlaveB (.4)
1213
1214 sn = lambda x: re.sub(r'(?i)^cnode','',x)
1215
1216 # Automatic naming convention of interlinks namely 2 + remote.lower()
1217 for (key,value) in pool.iteritems():
1218 # Make sure they are sorted from low-ip to high-ip
1219 value = sorted(value, key=lambda x: parseaddr(x[2]))
1220
1221 if len(value) == 1:
1222 (iface_name, fqdn, ip) = value[0]
1223 wleiden_zone["2unused-%s.%s" % (iface_name, fqdn)].append((ip, True))
1224
1225 # Device DNS names
1226 if 'cnode' in fqdn.lower():
1227 wleiden_zone["d-at-%s.%s" % (iface_name, fqdn)].append((showaddr(parseaddr(ip) + 1), False))
1228 wleiden_cname["d-at-%s.%s" % (iface_name,sn(fqdn))] = "d-at-%s.%s" % ((iface_name, fqdn))
1229
1230 elif len(value) == 2:
1231 (a_iface_name, a_fqdn, a_ip) = value[0]
1232 (b_iface_name, b_fqdn, b_ip) = value[1]
1233 wleiden_zone["2%s.%s" % (b_fqdn,a_fqdn)].append((a_ip, True))
1234 wleiden_zone["2%s.%s" % (a_fqdn,b_fqdn)].append((b_ip, True))
1235
1236 # Device DNS names
1237 if 'cnode' in a_fqdn.lower() and 'cnode' in b_fqdn.lower():
1238 wleiden_zone["d-at-%s.%s" % (a_iface_name, a_fqdn)].append((showaddr(parseaddr(a_ip) + 1), False))
1239 wleiden_zone["d-at-%s.%s" % (b_iface_name, b_fqdn)].append((showaddr(parseaddr(b_ip) - 1), False))
1240 wleiden_cname["d-at-%s.%s" % (a_iface_name,sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
1241 wleiden_cname["d-at-%s.%s" % (b_iface_name,sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
1242 wleiden_cname["d2%s.%s" % (sn(b_fqdn),sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
1243 wleiden_cname["d2%s.%s" % (sn(a_fqdn),sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
1244
1245 else:
1246 pool_members = [k[1] for k in value]
1247 for item in value:
1248 (iface_name, fqdn, ip) = item
1249 wleiden_zone["2ring.%s" % (fqdn)].append((ip, True))
1250
1251 # Include static DNS entries
1252 # XXX: Should they override the autogenerated results?
1253 # XXX: Convert input to yaml more useable.
1254 # Format:
1255 ##; this is a comment
1256 ## roomburgh=CNodeRoomburgh1
1257 ## apkerk1.CNodeVosko=172.17.176.8 ;this as well
1258 dns_list = yaml.load(open(os.path.join(NODE_DIR,'../dns/staticDNS.yaml'),'r'))
1259
1260 # Hack to allow special entries, for development
1261 wleiden_raw = {}
1262
1263 for line in dns_list:
1264 reverse = False
1265 k, items = line.items()[0]
1266 if type(items) == dict:
1267 if items.has_key('reverse'):
1268 reverse = items['reverse']
1269 items = items['a']
1270 else:
1271 items = items['cname']
1272 items = [items] if type(items) != list else items
1273 for item in items:
1274 if item.startswith('IN '):
1275 wleiden_raw[k] = item
1276 elif valid_addr(item):
1277 wleiden_zone[k].append((item, reverse))
1278 else:
1279 wleiden_cname[k] = item
1280
1281 details = dict()
1282 # 24 updates a day allowed
1283 details['serial'] = time.strftime('%Y%m%d%H')
1284
1285 if external:
1286 dns_masters = ['siteview.wirelessleiden.nl', 'ns1.vanderzwet.net']
1287 else:
1288 dns_masters = ['sunny.wleiden.net']
1289
1290 details['master'] = dns_masters[0]
1291 details['ns_servers'] = '\n'.join(['\tNS\t%s.' % x for x in dns_masters])
1292
1293 dns_header = '''
1294$TTL 3h
1295%(zone)s. SOA %(master)s. beheer.lijst.wirelessleiden.nl. ( %(serial)s 1d 12h 1w 60s )
1296 ; Serial, Refresh, Retry, Expire, Neg. cache TTL
1297
1298%(ns_servers)s
1299 \n'''
1300
1301
1302 if not os.path.isdir(output_dir):
1303 os.makedirs(output_dir)
1304 details['zone'] = 'wleiden.net'
1305 f = open(os.path.join(output_dir,"db." + details['zone']), "w")
1306 f.write(dns_header % details)
1307
1308 for host,items in wleiden_zone.iteritems():
1309 for ip,reverse in items:
1310 if ip not in ['0.0.0.0']:
1311 f.write("%s.wleiden.net. IN A %s \n" % (host.lower(), ip))
1312 for source,dest in wleiden_cname.iteritems():
1313 dest = dest if dest.endswith('.') else dest + ".wleiden.net."
1314 f.write("%s.wleiden.net. IN CNAME %s\n" % (source.lower(), dest.lower()))
1315 for source, dest in wleiden_raw.iteritems():
1316 f.write("%s.wleiden.net. %s\n" % (source, dest))
1317 f.close()
1318
1319 # Create whole bunch of specific sub arpa zones. To keep it compliant
1320 for s in range(16,32):
1321 details['zone'] = '%i.172.in-addr.arpa' % s
1322 f = open(os.path.join(output_dir,"db." + details['zone']), "w")
1323 f.write(dns_header % details)
1324
1325 #XXX: Not effient, fix to proper data structure and do checks at other
1326 # stages
1327 for host,items in wleiden_zone.iteritems():
1328 for ip,reverse in items:
1329 if not reverse:
1330 continue
1331 if valid_addr(ip):
1332 if valid_addr(ip):
1333 if int(ip.split('.')[1]) == s:
1334 rev_ip = '.'.join(reversed(ip.split('.')))
1335 f.write("%s.in-addr.arpa. IN PTR %s.wleiden.net.\n" % (rev_ip.lower(), host.lower()))
1336 f.close()
1337
1338
1339def usage():
1340 print """Usage: %(prog)s <argument>
1341Argument:
1342\tstandalone [port] = Run configurator webserver [8000]
1343\tdns [outputdir] = Generate BIND compliant zone files in dns [./dns]
1344\tfull-export = Generate yaml export script for heatmap.
1345\tstatic [outputdir] = Generate all config files and store on disk
1346\t with format ./<outputdir>/%%NODE%%/%%FILE%% [./static]
1347\ttest <node> [<file>] = Receive output for certain node [all files].
1348\ttest-cgi <node> <file> = Receive output of CGI script [all files].
1349\tlist <status> <items> = List systems which have certain status
1350
1351Arguments:
1352\t<node> = NodeName (example: HybridRick)
1353\t<file> = %(files)s
1354\t<status> = all|up|down|planned
1355\t<items> = systems|nodes|proxies
1356
1357NOTE FOR DEVELOPERS; you can test your changes like this:
1358 BEFORE any changes in this code:
1359 $ ./gformat.py static /tmp/pre
1360 AFTER the changes:
1361 $ ./gformat.py static /tmp/post
1362 VIEW differences and VERIFY all are OK:
1363 $ diff -urI 'Generated' -r /tmp/pre /tmp/post
1364""" % { 'prog' : sys.argv[0], 'files' : '|'.join(files) }
1365 exit(0)
1366
1367
1368def is_text_request():
1369 """ Find out whether we are calling from the CLI or any text based CLI utility """
1370 try:
1371 return os.environ['HTTP_USER_AGENT'].split()[0] in ['curl', 'fetch', 'wget']
1372 except KeyError:
1373 return True
1374
1375def switchFormat(setting):
1376 if setting:
1377 return "YES"
1378 else:
1379 return "NO"
1380
1381def rlinput(prompt, prefill=''):
1382 import readline
1383 readline.set_startup_hook(lambda: readline.insert_text(prefill))
1384 try:
1385 return raw_input(prompt)
1386 finally:
1387 readline.set_startup_hook()
1388
1389def fix_conflict(left, right, default='i'):
1390 while True:
1391 print "## %-30s | %-30s" % (left, right)
1392 c = raw_input("## Solve Conflict (h for help) <l|r|e|i|> [%s]: " % default)
1393 if not c:
1394 c = default
1395
1396 if c in ['l','1']:
1397 return left
1398 elif c in ['r','2']:
1399 return right
1400 elif c in ['e', '3']:
1401 return rlinput("Edit: ", "%30s | %30s" % (left, right))
1402 elif c in ['i', '4']:
1403 return None
1404 else:
1405 print "#ERROR: '%s' is invalid input (left, right, edit or ignore)!" % c
1406
1407def main():
1408 """Hard working sub"""
1409 # Allow easy hacking using the CLI
1410 if not os.environ.has_key('PATH_INFO'):
1411 if len(sys.argv) < 2:
1412 usage()
1413
1414 if sys.argv[1] == "standalone":
1415 import SocketServer
1416 import CGIHTTPServer
1417 # Hop to the right working directory.
1418 os.chdir(os.path.dirname(__file__))
1419 try:
1420 PORT = int(sys.argv[2])
1421 except (IndexError,ValueError):
1422 PORT = 8000
1423
1424 class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
1425 """ Serve this CGI from the root of the webserver """
1426 def is_cgi(self):
1427 if "favicon" in self.path:
1428 return False
1429
1430 self.cgi_info = (os.path.basename(__file__), self.path)
1431 self.path = ''
1432 return True
1433 handler = MyCGIHTTPRequestHandler
1434 SocketServer.TCPServer.allow_reuse_address = True
1435 httpd = SocketServer.TCPServer(("", PORT), handler)
1436 httpd.server_name = 'localhost'
1437 httpd.server_port = PORT
1438
1439 logger.info("serving at port %s", PORT)
1440 try:
1441 httpd.serve_forever()
1442 except KeyboardInterrupt:
1443 httpd.shutdown()
1444 logger.info("All done goodbye")
1445 elif sys.argv[1] == "test":
1446 # Basic argument validation
1447 try:
1448 node = sys.argv[2]
1449 datadump = get_yaml(node)
1450 except IndexError:
1451 print "Invalid argument"
1452 exit(1)
1453 except IOError as e:
1454 print e
1455 exit(1)
1456
1457
1458 # Get files to generate
1459 gen_files = sys.argv[3:] if len(sys.argv) > 3 else files
1460
1461 # Actual config generation
1462 for config in gen_files:
1463 logger.info("## Generating %s %s", node, config)
1464 print generate_config(node, config, datadump)
1465 elif sys.argv[1] == "test-cgi":
1466 os.environ['PATH_INFO'] = "/".join(sys.argv[2:])
1467 os.environ['SCRIPT_NAME'] = __file__
1468 process_cgi_request()
1469 elif sys.argv[1] == "static":
1470 items = dict()
1471 items['output_dir'] = sys.argv[2] if len(sys.argv) > 2 else "./static"
1472 for node in get_hostlist():
1473 items['node'] = node
1474 items['wdir'] = "%(output_dir)s/%(node)s" % items
1475 if not os.path.isdir(items['wdir']):
1476 os.makedirs(items['wdir'])
1477 datadump = get_yaml(node)
1478 for config in files:
1479 items['config'] = config
1480 logger.info("## Generating %(node)s %(config)s" % items)
1481 f = open("%(wdir)s/%(config)s" % items, "w")
1482 f.write(generate_config(node, config, datadump))
1483 f.close()
1484 elif sys.argv[1] == "wind-export":
1485 items = dict()
1486 for node in get_hostlist():
1487 datadump = get_yaml(node)
1488 sql = """INSERT IGNORE INTO nodes (name, name_ns, longitude, latitude)
1489 VALUES ('%(nodename)s', '%(nodename)s', %(latitude)s, %(longitude)s);""" % datadump;
1490 sql = """INSERT IGNORE INTO users_nodes (user_id, node_id, owner)
1491 VALUES (
1492 (SELECT id FROM users WHERE username = 'rvdzwet'),
1493 (SELECT id FROM nodes WHERE name = '%(nodename)s'),
1494 'Y');""" % datadump
1495 #for config in files:
1496 # items['config'] = config
1497 # print "## Generating %(node)s %(config)s" % items
1498 # f = open("%(wdir)s/%(config)s" % items, "w")
1499 # f.write(generate_config(node, config, datadump))
1500 # f.close()
1501 for node in get_hostlist():
1502 datadump = get_yaml(node)
1503 for iface_key in sorted([elem for elem in datadump.keys() if elem.startswith('iface_')]):
1504 ifacedump = datadump[iface_key]
1505 if ifacedump.has_key('mode') and ifacedump['mode'] == 'ap-wds':
1506 ifacedump['nodename'] = datadump['nodename']
1507 if not ifacedump.has_key('channel') or not ifacedump['channel']:
1508 ifacedump['channel'] = 0
1509 sql = """INSERT INTO links (node_id, type, ssid, protocol, channel, status)
1510 VALUES ((SELECT id FROM nodes WHERE name = '%(nodename)s'), 'ap',
1511 '%(ssid)s', 'IEEE 802.11b', %(channel)s, 'active');""" % ifacedump
1512 elif sys.argv[1] == "full-export":
1513 hosts = {}
1514 for node in get_hostlist():
1515 datadump = get_yaml(node)
1516 hosts[datadump['nodename']] = datadump
1517 print yaml.dump(hosts)
1518
1519 elif sys.argv[1] == "dns":
1520 make_dns(sys.argv[2] if len(sys.argv) > 2 else 'dns', 'external' in sys.argv)
1521 elif sys.argv[1] == "cleanup":
1522 # First generate all datadumps
1523 datadumps = dict()
1524 ssid_to_node = dict()
1525 for host in get_hostlist():
1526 logger.info("# Processing: %s", host)
1527 # Set some boring default values
1528 datadump = { 'board' : 'UNKNOWN' }
1529 datadump.update(get_yaml(host))
1530 datadumps[datadump['autogen_realname']] = datadump
1531
1532 (poel, errors) = make_relations(datadumps)
1533 print "\n".join(["# WARNING: %s" % x for x in errors])
1534
1535 for host,datadump in datadumps.iteritems():
1536 try:
1537 # Convert all yes and no to boolean values
1538 def fix_boolean(dump):
1539 for key in dump.keys():
1540 if type(dump[key]) == dict:
1541 dump[key] = fix_boolean(dump[key])
1542 elif str(dump[key]).lower() in ["yes", "true"]:
1543 dump[key] = True
1544 elif str(dump[key]).lower() in ["no", "false"]:
1545 # Compass richting no (Noord Oost) is valid input
1546 if key != "compass": dump[key] = False
1547 return dump
1548 datadump = fix_boolean(datadump)
1549
1550 if datadump['rdnap_x'] and datadump['rdnap_y']:
1551 datadump['latitude'], datadump['longitude'] = rdnap.rd2etrs(datadump['rdnap_x'], datadump['rdnap_y'])
1552 elif datadump['latitude'] and datadump['longitude']:
1553 datadump['rdnap_x'], datadump['rdnap_y'] = rdnap.etrs2rd(datadump['latitude'], datadump['longitude'])
1554
1555 if datadump['nodename'].startswith('Proxy'):
1556 datadump['nodename'] = datadump['nodename'].lower()
1557
1558 for iface_key in datadump['autogen_iface_keys']:
1559 try:
1560 # All our normal wireless cards are normal APs now
1561 if datadump[iface_key]['type'] in ['11a', '11b', '11g', 'wireless']:
1562 datadump[iface_key]['mode'] = 'ap'
1563 # Wireless Leiden SSID have an consistent lowercase/uppercase
1564 if datadump[iface_key].has_key('ssid'):
1565 ssid = datadump[iface_key]['ssid']
1566 prefix = 'ap-WirelessLeiden-'
1567 if ssid.lower().startswith(prefix.lower()):
1568 datadump[iface_key]['ssid'] = prefix + ssid[len(prefix)].upper() + ssid[len(prefix) + 1:]
1569 if datadump[iface_key].has_key('ns_ip') and not datadump[iface_key].has_key('mode'):
1570 datadump[iface_key]['mode'] = 'autogen-FIXME'
1571 if not datadump[iface_key].has_key('comment'):
1572 datadump[iface_key]['comment'] = 'autogen-FIXME'
1573
1574 if datadump[iface_key]['comment'].startswith('autogen-') and datadump[iface_key].has_key('comment'):
1575 datadump[iface_key] = datadump[iface_key]['desc']
1576
1577 x = datadump[iface_key]['comment']
1578 datadump[iface_key]['comment'] = x[0].upper() + x[1:]
1579
1580
1581 if datadump[iface_key].has_key('desc'):
1582 if datadump[iface_key]['comment'].lower() == datadump[iface_key]['desc'].lower():
1583 del datadump[iface_key]['desc']
1584 else:
1585 print "# ERROR: At %s - %s" % (datadump['nodename'], iface_key)
1586 response = fix_conflict(datadump[iface_key]['comment'], datadump[iface_key]['desc'])
1587 if response:
1588 datadump[iface_key]['comment'] = response
1589 del datadump[iface_key]['desc']
1590
1591 # Check DHCP configuration
1592 dhcp_type(datadump[iface_key])
1593
1594 # Set the compass value based on the angle between the poels
1595 if datadump[iface_key].has_key('ns_ip'):
1596 my_pool = poel[network(datadump[iface_key]['ip'])]
1597 remote_hosts = list(set([x[0] for x in my_pool]) - set([host]))
1598 if remote_hosts:
1599 compass_target = remote_hosts[0]
1600 datadump[iface_key]['compass'] = cd_between_hosts(host, compass_target, datadumps)
1601 except Exception as e:
1602 print "# Error while processing interface %s" % iface_key
1603 raise
1604 store_yaml(datadump)
1605 except Exception as e:
1606 print "# Error while processing %s" % host
1607 raise
1608 elif sys.argv[1] == "list":
1609 use_fqdn = False
1610 if len(sys.argv) < 4 or not sys.argv[2] in ["up", "down", "planned", "all"]:
1611 usage()
1612 if sys.argv[3] == "nodes":
1613 systems = get_nodelist()
1614 elif sys.argv[3] == "proxies":
1615 systems = get_proxylist()
1616 elif sys.argv[3] == "systems":
1617 systems = get_hostlist()
1618 else:
1619 usage()
1620 if len(sys.argv) > 4:
1621 if sys.argv[4] == "fqdn":
1622 use_fqdn = True
1623 else:
1624 usage()
1625
1626 for system in systems:
1627 datadump = get_yaml(system)
1628
1629 output = datadump['autogen_fqdn'] if use_fqdn else system
1630 if sys.argv[2] == "all":
1631 print output
1632 elif datadump['status'] == sys.argv[2]:
1633 print output
1634 elif sys.argv[1] == "create":
1635 if sys.argv[2] == "network.kml":
1636 print make_network_kml.make_graph()
1637 else:
1638 usage()
1639 usage()
1640 else:
1641 # Do not enable debugging for config requests as it highly clutters the output
1642 if not is_text_request():
1643 cgitb.enable()
1644 process_cgi_request()
1645
1646
1647if __name__ == "__main__":
1648 main()
Note: See TracBrowser for help on using the repository browser.