source: genesis/tools/gformat.py@ 11267

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

Should make an API for this kind of stuff...

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