source: genesis/tools/gformat.py@ 10904

Last change on this file since 10904 was 10904, checked in by rick, 13 years ago

Show which rev is dying.

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