source: genesis/tools/gformat.py@ 10240

Last change on this file since 10240 was 10238, checked in by richardvm, 13 years ago

firewall needs be on at all time

  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 32.7 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
33from pprint import pprint
34try:
35 import yaml
36except ImportError, e:
37 print e
38 print "[ERROR] Please install the python-yaml or devel/py-yaml package"
39 exit(1)
40
41try:
42 from yaml import CLoader as Loader
43 from yaml import CDumper as Dumper
44except ImportError:
45 from yaml import Loader, Dumper
46
47from jinja2 import Template
48
49import logging
50logging.basicConfig(format='# %(levelname)s: %(message)s' )
51logger = logging.getLogger()
52logger.setLevel(logging.DEBUG)
53
54
55if os.environ.has_key('CONFIGROOT'):
56 NODE_DIR = os.environ['CONFIGROOT']
57else:
58 NODE_DIR = os.path.abspath(os.path.dirname(__file__)) + '/../nodes'
59__version__ = '$Id: gformat.py 10238 2012-03-18 21:01:29Z richardvm $'
60
61
62files = [
63 'authorized_keys',
64 'dnsmasq.conf',
65 'rc.conf.local',
66 'resolv.conf',
67 'motd',
68 'wleiden.yaml',
69 ]
70
71# Global variables uses
72OK = 10
73DOWN = 20
74UNKNOWN = 90
75
76
77def get_proxylist():
78 """Get all available proxies proxyX sorting based on X number"""
79 proxylist = sorted([os.path.basename(x) for x in glob.glob("%s/proxy*" % NODE_DIR)],
80 key=lambda name: int(''.join([c for c in name if c in string.digits])),
81 cmp=lambda x,y: x - y)
82 return proxylist
83
84def get_hybridlist():
85 """Get all available proxies hybridX sorting based on X number"""
86 hybridlist = sorted([os.path.basename(x) for x in glob.glob("%s/hybrid*" % NODE_DIR)],
87 key=lambda name: int(''.join([c for c in name if c in string.digits])),
88 cmp=lambda x,y: x - y)
89 return hybridlist
90
91
92def valid_addr(addr):
93 """ Show which address is valid in which are not """
94 return str(addr).startswith('172.')
95
96
97def get_nodelist():
98 """ Get all available nodes - sorted """
99 nodelist = sorted([os.path.basename(x) for x in glob.glob("%s/CNode*" % NODE_DIR)])
100 return nodelist
101
102def get_hostlist():
103 """ Combined hosts and proxy list"""
104 return get_nodelist() + get_proxylist() + get_hybridlist()
105
106def angle_between_points(lat1,lat2,long1,long2):
107 """
108 Return Angle in radians between two GPS coordinates
109 See: http://stackoverflow.com/questions/3809179/angle-between-2-gps-coordinates
110 """
111 dy = lat2 - lat1
112 dx = math.cos(math.pi/180*lat1)*(long2 - long1)
113 angle = math.atan2(dy,dx)
114 return angle
115
116def angle_to_cd(angle):
117 """ Return Dutch Cardinal Direction estimation in 'one digit' of radian angle """
118
119 # For easy conversion get positive degree
120 degrees = math.degrees(angle)
121 if degrees < 0:
122 360 - abs(degrees)
123
124 # Numbers can be confusing calculate from the 4 main directions
125 p = 22.5
126 if degrees < p:
127 return "n"
128 elif degrees < (90 - p):
129 return "no"
130 elif degrees < (90 + p):
131 return "o"
132 elif degrees < (180 - p):
133 return "zo"
134 elif degrees < (180 + p):
135 return "z"
136 elif degrees < (270 - p):
137 return "zw"
138 elif degrees < (270 + p):
139 return "w"
140 elif degrees < (360 - p):
141 return "nw"
142 else:
143 return "n"
144
145
146def generate_title(nodelist):
147 """ Main overview page """
148 items = {'root' : "." }
149 output = """
150<html>
151 <head>
152 <title>Wireless leiden Configurator - GFormat</title>
153 <style type="text/css">
154 th {background-color: #999999}
155 tr:nth-child(odd) {background-color: #cccccc}
156 tr:nth-child(even) {background-color: #ffffff}
157 th, td {padding: 0.1em 1em}
158 </style>
159 </head>
160 <body>
161 <center>
162 <form type="GET" action="%(root)s">
163 <input type="hidden" name="action" value="update">
164 <input type="submit" value="Update Configuration Database (SVN)">
165 </form>
166 <table>
167 <caption><h3>Wireless Leiden Configurator</h3></caption>
168 """ % items
169
170 for node in nodelist:
171 items['node'] = node
172 output += '<tr><td><a href="%(root)s/%(node)s">%(node)s</a></td>' % items
173 for config in files:
174 items['config'] = config
175 output += '<td><a href="%(root)s/%(node)s/%(config)s">%(config)s</a></td>' % items
176 output += "</tr>"
177 output += """
178 </table>
179 <hr />
180 <em>%s</em>
181 </center>
182 </body>
183</html>
184 """ % __version__
185
186 return output
187
188
189
190def generate_node(node):
191 """ Print overview of all files available for node """
192 return "\n".join(files)
193
194
195
196def generate_header(ctag="#"):
197 return """\
198%(ctag)s
199%(ctag)s DO NOT EDIT - Automatically generated by 'gformat'
200%(ctag)s Generated at %(date)s by %(host)s
201%(ctag)s
202""" % { 'ctag' : ctag, 'date' : time.ctime(), 'host' : socket.gethostname() }
203
204
205
206def parseaddr(s):
207 """ Process IPv4 CIDR notation addr to a (binary) number """
208 f = s.split('.')
209 return (long(f[0]) << 24L) + \
210 (long(f[1]) << 16L) + \
211 (long(f[2]) << 8L) + \
212 long(f[3])
213
214
215
216def showaddr(a):
217 """ Display IPv4 addr in (dotted) CIDR notation """
218 return "%d.%d.%d.%d" % ((a >> 24) & 0xff, (a >> 16) & 0xff, (a >> 8) & 0xff, a & 0xff)
219
220
221def is_member(ip, mask, canidate):
222 """ Return True if canidate is part of ip/mask block"""
223 ip_addr = gformat.parseaddr(ip)
224 ip_canidate = gformat.parseaddr(canidate)
225 mask = int(mask)
226 ip_addr = ip_addr & ~((1 << (32 - mask)) - 1)
227 ip_canidate = ip_canidate & ~((1 << (32 - mask)) - 1)
228 return ip_addr == ip_canidate
229
230
231
232
233def netmask2subnet(netmask):
234 """ Given a 'netmask' return corresponding CIDR """
235 return showaddr(0xffffffff & (0xffffffff << (32 - int(netmask))))
236
237
238
239def generate_dnsmasq_conf(datadump):
240 """ Generate configuration file '/usr/local/etc/dnsmasq.conf' """
241 output = generate_header()
242 output += """\
243# DHCP server options
244dhcp-authoritative
245dhcp-fqdn
246domain=dhcp.%(nodename_lower)s.%(domain)s
247domain-needed
248expand-hosts
249log-async=100
250
251# Low memory footprint
252cache-size=10000
253 \n""" % datadump
254
255 for iface_key in datadump['iface_keys']:
256 if not datadump[iface_key].has_key('comment'):
257 datadump[iface_key]['comment'] = None
258 output += "## %(interface)s - %(desc)s - %(comment)s\n" % datadump[iface_key]
259
260 try:
261 (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
262 (ip, netmask) = datadump[iface_key]['ip'].split('/')
263 datadump[iface_key]['subnet'] = netmask2subnet(netmask)
264 except (AttributeError, ValueError):
265 output += "# not autoritive\n\n"
266 continue
267
268 dhcp_part = ".".join(ip.split('.')[0:3])
269 datadump[iface_key]['dhcp_start'] = dhcp_part + "." + dhcp_start
270 datadump[iface_key]['dhcp_stop'] = dhcp_part + "." + dhcp_stop
271 output += "dhcp-range=%(interface)s,%(dhcp_start)s,%(dhcp_stop)s,%(subnet)s,24h\n\n" % datadump[iface_key]
272
273 return output
274
275
276
277def generate_rc_conf_local(datadump):
278 """ Generate configuration file '/etc/rc.conf.local' """
279 datadump['autogen_ileiden_enable'] = 'yes' if datadump['ileiden'] else 'no'
280
281 ileiden_proxies = []
282 for proxy in get_proxylist():
283 proxydump = get_yaml(proxy)
284 if proxydump['ileiden']:
285 ileiden_proxies.append(proxydump)
286 datadump['autogen_ileiden_proxies'] = ','.join([x['masterip'] for x in ileiden_proxies])
287 datadump['autogen_ileiden_proxies_names'] = ','.join([x['autogen_item'] for x in ileiden_proxies])
288
289 output = generate_header("#");
290 output += Template("""\
291hostname='{{ autogen_fqdn }}.{{ domain }}'
292location='{{ location }}'
293nodetype="{{ nodetype }}"
294
295{% if tproxy -%}
296tproxy_enable='YES'
297tproxy_range='{{ tproxy }}'
298{% else -%}
299tproxy_enable='NO'
300{% endif -%}
301
302{% if nodetype == "Proxy" %}
303#
304# PROXY Configuration
305#
306
307{% if gateway -%}
308defaultrouter="{{ gateway }}"
309{% else -%}
310#defaultrouter="NOTSET"
311{% endif -%}
312
313internalif="{{ internalif }}"
314
315# PROXY iLeiden Configuration
316ileiden_enable="{{ autogen_ileiden_enable }}"
317gateway_enable="{{ autogen_ileiden_enable }}"
318pf_enable="yes"
319pf2_enable="yes"
320{% if autogen_ileiden_enable == "yes" -%}
321pf_flags="-D ext_if={{ externalif }} -D int_if={{ internalif }} -D publicnat={80,443}"
322lvrouted_enable="{{ autogen_ileiden_enable }}"
323lvrouted_flags="-u -s s00p3rs3kr3t -m 28"
324{% else -%}
325pf_flags="-D ext_if={{ externalif }} -D int_if={{ internalif }} -D publicnat={0}"
326{% if internalroute -%}
327static_routes="wleiden"
328route_wleiden="-net 172.16.0.0/12 {{ internalroute }}"
329{% endif -%}
330{% endif -%}
331
332{% endif -%}
333
334{% if nodetype == "CNode" %}
335#
336# NODE iLeiden Configuration
337#
338# iLeiden Proxies {{ autogen_ileiden_proxies_names }}
339lvrouted_flags="-u -s s00p3rs3kr3t -m 28 -z {{ autogen_ileiden_proxies }}"
340
341captive_portal_whitelist=""
342captive_portal_interfaces="{{ autogen_dhcp_interfaces }}"
343{% endif %}
344
345{% if nodetype == "Hybrid" %}
346#
347# Hybrid Node
348#
349{% if internalroute -%}
350static_routes="wleiden"
351route_wleiden="-net 172.16.0.0/12 {{ internalroute }}"
352{% endif -%}
353
354{% if gateway -%}
355defaultrouter="{{ gateway }}"
356{% else -%}
357#defaultrouter="NOTSET"
358{% endif -%}
359
360internalif="{{ internalif }}"
361{% if vpnif -%}
362 vpnif="{{ vpnif }}"\n
363{% endif -%}
364
365lvrouted_enable="{{ autogen_ileiden_enable }}"
366lvrouted_flags="-u -s s00p3rs3kr3t -m 28"
367
368gateway_enable="{{ autogen_ileiden_enable }}"
369
370ileiden_enable="{{ autogen_ileiden_enable }}"
371firewall_enable="{{ autogen_ileiden_enable }}"
372firewall_script="/etc/ipfw.sh"
373
374captive_portal_whitelist=""
375captive_portal_interfaces="{{ autogen_dhcp_interfaces }}"
376{% endif %}
377
378""").render(datadump)
379
380 # lo0 configuration:
381 # - 172.32.255.1/32 is the proxy.wleiden.net deflector
382 # - masterip is special as it needs to be assigned to at
383 # least one interface, so if not used assign to lo0
384 addrs_list = { 'lo0' : [("127.0.0.1/8", "LocalHost"), ("172.31.255.1/32","Proxy IP")] }
385 iface_map = {'lo0' : 'lo0'}
386
387 masterip_used = False
388 for iface_key in datadump['iface_keys']:
389 if datadump[iface_key]['ip'].startswith(datadump['masterip']):
390 masterip_used = True
391 break
392 if not masterip_used:
393 addrs_list['lo0'].append((datadump['masterip'] + "/32", 'Master IP Not used in interface'))
394
395 for iface_key in datadump['iface_keys']:
396 ifacedump = datadump[iface_key]
397 ifname = ifacedump['autogen_ifname']
398
399 # Add interface IP to list
400 item = (ifacedump['ip'], ifacedump['desc'])
401 if addrs_list.has_key(ifname):
402 addrs_list[ifname].append(item)
403 else:
404 addrs_list[ifname] = [item]
405
406 # Alias only needs IP assignment for now, this might change if we
407 # are going to use virtual accesspoints
408 if "alias" in iface_key:
409 continue
410
411 # XXX: Might want to deduct type directly from interface name
412 if ifacedump['type'] in ['11a', '11b', '11g', 'wireless']:
413 # Default to station (client) mode
414 ifacedump['wlanmode'] = "sta"
415 if ifacedump['mode'] in ['master', 'master-wds', 'ap', 'ap-wds']:
416 ifacedump['wlanmode'] = "ap"
417 # Default to 802.11b mode
418 ifacedump['mode'] = '11b'
419 if ifacedump['type'] in ['11a', '11b' '11g']:
420 ifacedump['mode'] = ifacedump['type']
421
422 if not ifacedump.has_key('channel'):
423 if ifacedump['type'] == '11a':
424 ifacedump['channel'] = 36
425 else:
426 ifacedump['channel'] = 1
427
428 # Allow special hacks at the back like wds and stuff
429 if not ifacedump.has_key('extra'):
430 ifacedump['extra'] = 'regdomain ETSI country NL'
431
432 output += "wlans_%(interface)s='%(autogen_ifname)s'\n" % ifacedump
433 output += ("create_args_%(autogen_ifname)s='wlanmode %(wlanmode)s mode " +\
434 "%(mode)s ssid %(ssid)s %(extra)s channel %(channel)s'\n") % ifacedump
435
436 elif ifacedump['type'] in ['ethernet', 'eth']:
437 # No special config needed besides IP
438 pass
439 else:
440 assert False, "Unknown type " + ifacedump['type']
441
442 # Print IP address which needs to be assigned over here
443 output += "\n"
444 for iface,addrs in sorted(addrs_list.iteritems()):
445 for addr, comment in sorted(addrs,key=lambda x: parseaddr(x[0].split('/')[0])):
446 output += "# %s || %s || %s\n" % (iface, addr, comment)
447 output += "ipv4_addrs_%s='%s'\n\n" % (iface, " ".join([x[0] for x in addrs]))
448
449 return output
450
451
452
453def get_yaml(item):
454 """ Get configuration yaml for 'item'"""
455 gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
456
457 f = open(gfile, 'r')
458 datadump = yaml.load(f,Loader=Loader)
459 datadump['autogen_iface_keys'] = get_interface_keys(datadump)
460
461 wlan_count=0
462 for key in datadump['autogen_iface_keys']:
463 if datadump[key]['type'] in ['11a', '11b', '11g', 'wireless']:
464 datadump[key]['autogen_ifname'] = 'wlan%i' % wlan_count
465 wlan_count += 1
466 else:
467 datadump[key]['autogen_ifname'] = datadump[key]['interface'].split(':')[0]
468
469
470 dhcp_interfaces = [datadump[key]['autogen_ifname'] for key in datadump['autogen_iface_keys'] if datadump[key]['dhcp'] != 'no']
471 datadump['autogen_dhcp_interfaces'] = ' '.join(dhcp_interfaces)
472 datadump['autogen_item'] = item
473 datadump['autogen_fqdn'] = get_fqdn(datadump)
474 f.close()
475
476 return datadump
477
478def store_yaml(datadump, header=False):
479 """ Store configuration yaml for 'item'"""
480 item = datadump['autogen_item']
481 gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
482
483 f = open(gfile, 'w')
484 f.write(generate_wleiden_yaml(datadump, header))
485 f.close()
486
487
488
489def get_all_configs():
490 """ Get dict with key 'host' with all configs present """
491 configs = dict()
492 for host in get_hostlist():
493 datadump = get_yaml(host)
494 configs[host] = datadump
495 return configs
496
497
498def get_interface_keys(config):
499 """ Quick hack to get all interface keys, later stage convert this to a iterator """
500 return sorted([elem for elem in config.keys() if (elem.startswith('iface_') and not "lo0" in elem)])
501
502
503def get_used_ips(configs):
504 """ Return array of all IPs used in config files"""
505 ip_list = []
506 for config in configs:
507 ip_list.append(config['masterip'])
508 for iface_key in get_interface_keys(config):
509 l = config[iface_key]['ip']
510 addr, mask = l.split('/')
511 # Special case do not process
512 if valid_addr(addr):
513 ip_list.append(addr)
514 else:
515 logger.error("## IP '%s' in '%s' not valid" % (addr, config['nodename']))
516 return sorted(ip_list)
517
518
519
520def generate_resolv_conf(datadump):
521 """ Generate configuration file '/etc/resolv.conf' """
522 output = generate_header("#");
523 output += """\
524search wleiden.net
525"""
526 if datadump['nodetype'] == 'Proxy':
527 output += """\
528# Try local (cache) first
529nameserver 127.0.0.1
530nameserver 8.8.8.8 # Google Public NameServer
531nameserver 8.8.4.4 # Google Public NameServer
532"""
533 elif datadump['nodetype'] == 'Hybrid':
534 for proxy in get_proxylist():
535 proxy_ip = get_yaml(proxy)['masterip']
536 output += "nameserver %-15s # %s\n" % (proxy_ip, proxy)
537 output += """\
538nameserver 8.8.8.8 # Google Public NameServer
539nameserver 8.8.4.4 # Google Public NameServer
540"""
541 else:
542 output += """\
543# Try local (cache) first
544nameserver 127.0.0.1
545
546# Proxies are recursive nameservers
547# needs to be in resolv.conf for dnsmasq as well
548""" % datadump
549 for proxy in get_proxylist():
550 proxy_ip = get_yaml(proxy)['masterip']
551 output += "nameserver %-15s # %s\n" % (proxy_ip, proxy)
552
553 return output
554
555def generate_motd(datadump):
556 """ Generate configuration file '/etc/motd' """
557 output = """\
558FreeBSD 9.0-RELEASE (kernel.wleiden) #0 r230587: Sun Jan 29 17:09:57 CET 2012
559
560 WWW: %(autogen_fqdn)s.wleiden.net - http://www.wirelessleiden.nl
561 Loc: %(location)s
562
563Interlinks:
564""" % datadump
565
566 # XXX: This is a hacky way to get the required data
567 for line in generate_rc_conf_local(datadump).split('\n'):
568 if '||' in line and not line[1:].split()[0] in ['lo0', 'ath0'] :
569 output += " - %s \n" % line[1:]
570 output += """\
571Attached bridges:
572"""
573 for iface_key in datadump['autogen_iface_keys']:
574 ifacedump = datadump[iface_key]
575 if ifacedump.has_key('ns_ip'):
576 output += " - %(interface)s || %(mode)s || %(ns_ip)s\n" % ifacedump
577
578 return output
579
580
581def format_yaml_value(value):
582 """ Get yaml value in right syntax for outputting """
583 if isinstance(value,str):
584 output = '"%s"' % value
585 else:
586 output = value
587 return output
588
589
590
591def format_wleiden_yaml(datadump):
592 """ Special formatting to ensure it is editable"""
593 output = "# Genesis config yaml style\n"
594 output += "# vim:ts=2:et:sw=2:ai\n"
595 output += "#\n"
596 iface_keys = [elem for elem in datadump.keys() if elem.startswith('iface_')]
597 for key in sorted(set(datadump.keys()) - set(iface_keys)):
598 output += "%-10s: %s\n" % (key, format_yaml_value(datadump[key]))
599
600 output += "\n\n"
601
602 key_order = [ 'comment', 'interface', 'ip', 'desc', 'sdesc', 'mode', 'type',
603 'extra_type', 'channel', 'ssid', 'dhcp' ]
604
605 for iface_key in sorted(iface_keys):
606 output += "%s:\n" % iface_key
607 for key in key_order + list(sorted(set(datadump[iface_key].keys()) - set(key_order))):
608 if datadump[iface_key].has_key(key):
609 output += " %-11s: %s\n" % (key, format_yaml_value(datadump[iface_key][key]))
610 output += "\n\n"
611
612 return output
613
614
615
616def generate_wleiden_yaml(datadump, header=True):
617 """ Generate (petty) version of wleiden.yaml"""
618 for key in datadump.keys():
619 if key.startswith('autogen_'):
620 del datadump[key]
621 # Interface autogen cleanups
622 elif type(datadump[key]) == dict:
623 for key2 in datadump[key].keys():
624 if key2.startswith('autogen_'):
625 del datadump[key][key2]
626
627 output = generate_header("#") if header else ''
628 output += format_wleiden_yaml(datadump)
629 return output
630
631
632def generate_yaml(datadump):
633 return generate_config(datadump['nodename'], "wleiden.yaml", datadump)
634
635
636
637def generate_config(node, config, datadump=None):
638 """ Print configuration file 'config' of 'node' """
639 output = ""
640 try:
641 # Load config file
642 if datadump == None:
643 datadump = get_yaml(node)
644
645 # Preformat certain needed variables for formatting and push those into special object
646 datadump_extra = copy.deepcopy(datadump)
647 if not datadump_extra.has_key('domain'):
648 datadump_extra['domain'] = 'wleiden.net'
649 datadump_extra['nodename_lower'] = datadump_extra['nodename'].lower()
650 datadump_extra['iface_keys'] = sorted([elem for elem in datadump.keys() if elem.startswith('iface_')])
651
652 if config == 'wleiden.yaml':
653 output += generate_wleiden_yaml(datadump)
654 elif config == 'authorized_keys':
655 f = open(os.path.join(NODE_DIR,"global_keys"), 'r')
656 output += f.read()
657 f.close()
658 elif config == 'dnsmasq.conf':
659 output += generate_dnsmasq_conf(datadump_extra)
660 elif config == 'rc.conf.local':
661 output += generate_rc_conf_local(datadump_extra)
662 elif config == 'resolv.conf':
663 output += generate_resolv_conf(datadump_extra)
664 elif config == 'motd':
665 output += generate_motd(datadump_extra)
666 else:
667 assert False, "Config not found!"
668 except IOError, e:
669 output += "[ERROR] Config file not found"
670 return output
671
672
673
674def process_cgi_request():
675 """ When calling from CGI """
676 # Update repository if requested
677 form = cgi.FieldStorage()
678 if form.getvalue("action") == "update":
679 print "Refresh: 5; url=."
680 print "Content-type:text/plain\r\n\r\n",
681 print "[INFO] Updating subverion, please wait..."
682 print subprocess.Popen(['svn', 'cleanup', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0],
683 print subprocess.Popen(['svn', 'up', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0],
684 print "[INFO] All done, redirecting in 5 seconds"
685 sys.exit(0)
686
687
688 uri = os.environ['PATH_INFO'].strip('/').split('/')
689 output = ""
690 if not uri[0]:
691 if is_text_request():
692 output += "Content-type:text/plain\r\n\r\n"
693 output += '\n'.join(get_hostlist())
694 else:
695 output += "Content-type:text/html\r\n\r\n"
696 output += generate_title(get_hostlist())
697 elif len(uri) == 1:
698 output += "Content-type:text/plain\r\n\r\n"
699 output += generate_node(uri[0])
700 elif len(uri) == 2:
701 output += "Content-type:text/plain\r\n\r\n"
702 output += generate_config(uri[0], uri[1])
703 else:
704 assert False, "Invalid option"
705 print output
706
707def get_fqdn(datadump):
708 # Proxy naming convention is special
709 if datadump['nodetype'] == 'Proxy':
710 fqdn = datadump['nodename']
711 else:
712 # By default the full name is listed and also a shortname CNAME for easy use.
713 fqdn = datadump['nodetype'] + datadump['nodename']
714 return(fqdn)
715
716
717
718def make_dns(output_dir = 'dns'):
719 items = dict()
720
721 # hostname is key, IP is value
722 wleiden_zone = dict()
723 wleiden_cname = dict()
724
725 pool = dict()
726 for node in get_hostlist():
727 logger.info("Processing host %s", node)
728 datadump = get_yaml(node)
729
730 # Proxy naming convention is special
731 fqdn = get_fqdn(datadump)
732 if datadump['nodetype'] == 'CNode':
733 wleiden_cname[datadump['nodename']] = fqdn
734
735 wleiden_zone[fqdn] = datadump['masterip']
736
737 # Hacking to get proper DHCP IPs and hostnames
738 for iface_key in get_interface_keys(datadump):
739 iface_name = datadump[iface_key]['interface'].replace(':',"-alias-")
740 (ip, netmask) = datadump[iface_key]['ip'].split('/')
741 try:
742 (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
743 datadump[iface_key]['subnet'] = netmask2subnet(netmask)
744 dhcp_part = ".".join(ip.split('.')[0:3])
745 if ip != datadump['masterip']:
746 wleiden_zone["dhcp-gateway-%s.%s" % (iface_name, fqdn)] = ip
747 for i in range(int(dhcp_start), int(dhcp_stop) + 1):
748 wleiden_zone["dhcp-%s-%s.%s" % (i, iface_name, fqdn)] = "%s.%s" % (dhcp_part, i)
749 except (AttributeError, ValueError):
750 # First push it into a pool, to indentify the counter-part later on
751 addr = parseaddr(ip)
752 netmask = int(netmask)
753 addr = addr & ~((1 << (32 - netmask)) - 1)
754 if pool.has_key(addr):
755 pool[addr] += [(iface_name, fqdn, ip)]
756 else:
757 pool[addr] = [(iface_name, fqdn, ip)]
758 continue
759
760
761 def pool_to_name(node, pool_members):
762 """Convert the joined name to a usable pool name"""
763
764 # Get rid of the own entry
765 pool_members = list(set(pool_members) - set([fqdn]))
766
767 target = oldname = ''
768 for node in sorted(pool_members):
769 (name, number) = re.match('^([A-Za-z]+)([0-9]*)$',node).group(1,2)
770 target += "-" + number if name == oldname else "-" + node if target else node
771 oldname = name
772
773 return target
774
775
776 # WL uses an /29 to configure an interface. IP's are ordered like this:
777 # MasterA (.1) -- DeviceA (.2) <<>> DeviceB (.3) --- SlaveB (.4)
778
779 sn = lambda x: re.sub(r'(?i)^cnode','',x)
780
781 # Automatic naming convention of interlinks namely 2 + remote.lower()
782 for (key,value) in pool.iteritems():
783 # Make sure they are sorted from low-ip to high-ip
784 value = sorted(value, key=lambda x: parseaddr(x[2]))
785
786 if len(value) == 1:
787 (iface_name, fqdn, ip) = value[0]
788 wleiden_zone["2unused-%s.%s" % (iface_name, fqdn)] = ip
789
790 # Device DNS names
791 if 'cnode' in fqdn.lower():
792 wleiden_zone["d-at-%s.%s" % (iface_name, fqdn)] = showaddr(parseaddr(ip) + 1)
793 wleiden_cname["d-at-%s.%s" % (iface_name,sn(fqdn))] = "d-at-%s.%s" % (iface_name, fqdn)
794
795 elif len(value) == 2:
796 (a_iface_name, a_fqdn, a_ip) = value[0]
797 (b_iface_name, b_fqdn, b_ip) = value[1]
798 wleiden_zone["2%s.%s" % (b_fqdn,a_fqdn)] = a_ip
799 wleiden_zone["2%s.%s" % (a_fqdn,b_fqdn)] = b_ip
800
801 # Device DNS names
802 if 'cnode' in a_fqdn.lower() and 'cnode' in b_fqdn.lower():
803 wleiden_zone["d-at-%s.%s" % (a_iface_name, a_fqdn)] = showaddr(parseaddr(a_ip) + 1)
804 wleiden_zone["d-at-%s.%s" % (b_iface_name, b_fqdn)] = showaddr(parseaddr(b_ip) - 1)
805 wleiden_cname["d-at-%s.%s" % (a_iface_name,sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
806 wleiden_cname["d-at-%s.%s" % (b_iface_name,sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
807 wleiden_cname["d2%s.%s" % (sn(b_fqdn),sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
808 wleiden_cname["d2%s.%s" % (sn(a_fqdn),sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
809
810 else:
811 pool_members = [k[1] for k in value]
812 for item in value:
813 (iface_name, fqdn, ip) = item
814 pool_name = "2pool-" + showaddr(key).replace('.','-') + "-" + pool_to_name(fqdn,pool_members)
815 wleiden_zone["%s.%s" % (pool_name, fqdn)] = ip
816
817 # Include static DNS entries
818 # XXX: Should they override the autogenerated results?
819 # XXX: Convert input to yaml more useable.
820 # Format:
821 ##; this is a comment
822 ## roomburgh=CNodeRoomburgh1
823 ## apkerk1.CNodeVosko=172.17.176.8 ;this as well
824 dns = yaml.load(open(os.path.join(NODE_DIR,'../dns/staticDNS.yaml'),'r'))
825
826 # Hack to allow special entries, for development
827 wleiden_raw = dns['raw']
828 del dns['raw']
829
830 for comment, block in dns.iteritems():
831 for k,v in block.iteritems():
832 if valid_addr(v):
833 wleiden_zone[k] = v
834 else:
835 wleiden_cname[k] = v
836
837 details = dict()
838 # 24 updates a day allowed
839 details['serial'] = time.strftime('%Y%m%d%H')
840
841 dns_header = '''
842$TTL 3h
843%(zone)s. SOA sunny.wleiden.net. beheer.lijst.wirelessleiden.nl. ( %(serial)s 1d 12h 1w 3h )
844 ; Serial, Refresh, Retry, Expire, Neg. cache TTL
845
846 NS sunny.wleiden.net.
847 \n'''
848
849
850 if not os.path.isdir('dns'):
851 os.makedirs('dns')
852 details['zone'] = 'wleiden.net'
853 f = open(os.path.join(output_dir,"db." + details['zone']), "w")
854 f.write(dns_header % details)
855
856 for host,ip in wleiden_zone.iteritems():
857 if valid_addr(ip):
858 f.write("%s.wleiden.net. IN A %s \n" % (host.lower(), ip))
859 for source,dest in wleiden_cname.iteritems():
860 f.write("%s.wleiden.net. IN CNAME %s.wleiden.net.\n" % (source.lower(), dest.lower()))
861 for source, dest in wleiden_raw.iteritems():
862 f.write("%s.wleiden.net. %s\n" % (source, dest))
863 f.close()
864
865 # Create whole bunch of specific sub arpa zones. To keep it compliant
866 for s in range(16,32):
867 details['zone'] = '%i.172.in-addr.arpa' % s
868 f = open(os.path.join(output_dir,"db." + details['zone']), "w")
869 f.write(dns_header % details)
870
871 #XXX: Not effient, fix to proper data structure and do checks at other
872 # stages
873 for host,ip in wleiden_zone.iteritems():
874 if valid_addr(ip):
875 if int(ip.split('.')[1]) == s:
876 rev_ip = '.'.join(reversed(ip.split('.')))
877 f.write("%s.in-addr.arpa. IN PTR %s.wleiden.net.\n" % (rev_ip.lower(), host.lower()))
878 f.close()
879
880
881def usage():
882 print """Usage: %s <standalone [port] |test [test arguments]|static|dns>
883Examples:
884\tdns [outputdir] = Generate BIND compliant zone files in dns.
885\tstandalone = Run configurator webserver [default port=8000]
886\twind-export = Generate SQL import scripts for WIND database
887\tfull-export = Generate yaml export script for heatmap.
888\tstatic = Generate all config files and store on disk
889\t with format ./static/%%NODE%%/%%FILE%%
890\ttest CNodeRick dnsmasq.conf = Receive output of CGI script
891\t for arguments CNodeRick/dnsmasq.conf
892\tlist <nodes|proxies> = List systems which marked up.
893"""
894 exit(0)
895
896
897def is_text_request():
898 """ Find out whether we are calling from the CLI or any text based CLI utility """
899 try:
900 return os.environ['HTTP_USER_AGENT'].split()[0] in ['curl', 'fetch', 'wget']
901 except KeyError:
902 return True
903
904def main():
905 """Hard working sub"""
906 # Allow easy hacking using the CLI
907 if not os.environ.has_key('PATH_INFO'):
908 if len(sys.argv) < 2:
909 usage()
910
911 if sys.argv[1] == "standalone":
912 import SocketServer
913 import CGIHTTPServer
914 # Hop to the right working directory.
915 os.chdir(os.path.dirname(__file__))
916 try:
917 PORT = int(sys.argv[2])
918 except (IndexError,ValueError):
919 PORT = 8000
920
921 class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
922 """ Serve this CGI from the root of the webserver """
923 def is_cgi(self):
924 if "favicon" in self.path:
925 return False
926
927 self.cgi_info = (__file__, self.path)
928 self.path = ''
929 return True
930 handler = MyCGIHTTPRequestHandler
931 SocketServer.TCPServer.allow_reuse_address = True
932 httpd = SocketServer.TCPServer(("", PORT), handler)
933 httpd.server_name = 'localhost'
934 httpd.server_port = PORT
935
936 logger.info("serving at port %s", PORT)
937 try:
938 httpd.serve_forever()
939 except KeyboardInterrupt:
940 httpd.shutdown()
941 logger.info("All done goodbye")
942 elif sys.argv[1] == "test":
943 os.environ['PATH_INFO'] = "/".join(sys.argv[2:])
944 os.environ['SCRIPT_NAME'] = __file__
945 process_cgi_request()
946 elif sys.argv[1] == "unit-test":
947 os.environ['SCRIPT_NAME'] = __file__
948 for host in get_hostlist():
949 for outfile in files:
950 os.environ['PATH_INFO'] = "/".join([host,outfile])
951 try:
952 process_cgi_request()
953 except Exception:
954 print "# ERROR: %s" % os.environ['PATH_INFO']
955 raise
956
957
958 elif sys.argv[1] == "static":
959 items = dict()
960 for node in get_hostlist():
961 items['node'] = node
962 items['wdir'] = "./static/%(node)s" % items
963 if not os.path.isdir(items['wdir']):
964 os.makedirs(items['wdir'])
965 datadump = get_yaml(node)
966 for config in files:
967 items['config'] = config
968 logger.info("## Generating %(node)s %(config)s" % items)
969 f = open("%(wdir)s/%(config)s" % items, "w")
970 f.write(generate_config(node, config, datadump))
971 f.close()
972 elif sys.argv[1] == "wind-export":
973 items = dict()
974 for node in get_hostlist():
975 datadump = get_yaml(node)
976 sql = """INSERT IGNORE INTO nodes (name, name_ns, longitude, latitude)
977 VALUES ('%(nodename)s', '%(nodename)s', %(latitude)s, %(longitude)s);""" % datadump;
978 sql = """INSERT IGNORE INTO users_nodes (user_id, node_id, owner)
979 VALUES (
980 (SELECT id FROM users WHERE username = 'rvdzwet'),
981 (SELECT id FROM nodes WHERE name = '%(nodename)s'),
982 'Y');""" % datadump
983 #for config in files:
984 # items['config'] = config
985 # print "## Generating %(node)s %(config)s" % items
986 # f = open("%(wdir)s/%(config)s" % items, "w")
987 # f.write(generate_config(node, config, datadump))
988 # f.close()
989 for node in get_hostlist():
990 datadump = get_yaml(node)
991 for iface_key in sorted([elem for elem in datadump.keys() if elem.startswith('iface_')]):
992 ifacedump = datadump[iface_key]
993 if ifacedump.has_key('mode') and ifacedump['mode'] == 'ap-wds':
994 ifacedump['nodename'] = datadump['nodename']
995 if not ifacedump.has_key('channel') or not ifacedump['channel']:
996 ifacedump['channel'] = 0
997 sql = """INSERT INTO links (node_id, type, ssid, protocol, channel, status)
998 VALUES ((SELECT id FROM nodes WHERE name = '%(nodename)s'), 'ap',
999 '%(ssid)s', 'IEEE 802.11b', %(channel)s, 'active');""" % ifacedump
1000 elif sys.argv[1] == "full-export":
1001 hosts = {}
1002 for node in get_hostlist():
1003 datadump = get_yaml(node)
1004 hosts[datadump['nodename']] = datadump
1005 print yaml.dump(hosts)
1006
1007 elif sys.argv[1] == "dns":
1008 make_dns(sys.argv[2] if len(sys.argv) > 2 else 'dns')
1009 elif sys.argv[1] == "cleanup":
1010 # First generate all datadumps
1011 datadumps = dict()
1012 for host in get_hostlist():
1013 logger.info("# Processing: %s", host)
1014 datadump = get_yaml(host)
1015 datadumps[get_fqdn(datadump)] = datadump
1016
1017 for host,datadump in datadumps.iteritems():
1018 datadump['latitude'], datadump['longitude'] = rdnap.rd2etrs(datadump['rdnap_x'], datadump['rdnap_y'])
1019 for iface_key in datadump['autogen_iface_keys']:
1020 # Wireless Leiden SSID have an consistent lowercase/uppercase
1021 if datadump[iface_key].has_key('ssid'):
1022 ssid = datadump[iface_key]['ssid']
1023 prefix = 'ap-WirelessLeiden-'
1024 if ssid.lower().startswith(prefix.lower()):
1025 datadump[iface_key]['ssid'] = prefix + ssid[len(prefix)].upper() + ssid[len(prefix) + 1:]
1026 if datadump[iface_key].has_key('ns_ip') and not datadump[iface_key].has_key('mode'):
1027 datadump[iface_key]['mode'] = 'autogen-FIXME'
1028 if not datadump[iface_key].has_key('desc'):
1029 datadump[iface_key]['desc'] = 'autogen-FIXME'
1030 store_yaml(datadump)
1031 elif sys.argv[1] == "list":
1032 if sys.argv[2] == "nodes":
1033 systems = get_nodelist()
1034 elif sys.argv[2] == "proxies":
1035 systems = get_proxylist()
1036 else:
1037 usage()
1038 for system in systems:
1039 datadump = get_yaml(system)
1040 if datadump['status'] == "up":
1041 print system
1042 else:
1043 usage()
1044 else:
1045 # Do not enable debugging for config requests as it highly clutters the output
1046 if not is_text_request():
1047 cgitb.enable()
1048 process_cgi_request()
1049
1050
1051if __name__ == "__main__":
1052 main()
Note: See TracBrowser for help on using the repository browser.