source: genesis/tools/gformat.py@ 10892

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

Doe een import van de bridge unit dmv een scan.

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