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.
|
---|
19 | import sys
|
---|
20 | import os
|
---|
21 | import re
|
---|
22 | sys.path.append(os.path.dirname(__file__))
|
---|
23 |
|
---|
24 | import cgi
|
---|
25 | import cgitb
|
---|
26 | import copy
|
---|
27 | import glob
|
---|
28 | import socket
|
---|
29 | import string
|
---|
30 | import subprocess
|
---|
31 | import time
|
---|
32 | import rdnap
|
---|
33 | import make_network_kml
|
---|
34 | from pprint import pprint
|
---|
35 | from collections import defaultdict
|
---|
36 | try:
|
---|
37 | import yaml
|
---|
38 | except ImportError, e:
|
---|
39 | print e
|
---|
40 | print "[ERROR] Please install the python-yaml or devel/py-yaml package"
|
---|
41 | exit(1)
|
---|
42 |
|
---|
43 | try:
|
---|
44 | from yaml import CLoader as Loader
|
---|
45 | from yaml import CDumper as Dumper
|
---|
46 | except ImportError:
|
---|
47 | from yaml import Loader, Dumper
|
---|
48 |
|
---|
49 | from jinja2 import Environment, Template
|
---|
50 | def yesorno(value):
|
---|
51 | return "YES" if bool(value) else "NO"
|
---|
52 | env = Environment()
|
---|
53 | env.filters['yesorno'] = yesorno
|
---|
54 | def render_template(datadump, template):
|
---|
55 | result = env.from_string(template).render(datadump)
|
---|
56 | # Make it look pretty to the naked eye, as jinja templates are not so
|
---|
57 | # friendly when it comes to whitespace formatting
|
---|
58 | ## Remove extra whitespace at end of line lstrip() style.
|
---|
59 | result = re.sub(r'\n[\ ]+','\n', result)
|
---|
60 | ## Include only a single newline between an definition and a comment
|
---|
61 | result = re.sub(r'(["\'])\n+([a-z]|\n#\n)',r'\1\n\2', result)
|
---|
62 | ## Remove extra newlines after single comment
|
---|
63 | result = re.sub(r'(#\n)\n+([a-z])',r'\1\2', result)
|
---|
64 | return result
|
---|
65 |
|
---|
66 | import logging
|
---|
67 | logging.basicConfig(format='# %(levelname)s: %(message)s' )
|
---|
68 | logger = logging.getLogger()
|
---|
69 | logger.setLevel(logging.DEBUG)
|
---|
70 |
|
---|
71 |
|
---|
72 | if os.environ.has_key('CONFIGROOT'):
|
---|
73 | NODE_DIR = os.environ['CONFIGROOT']
|
---|
74 | else:
|
---|
75 | NODE_DIR = os.path.abspath(os.path.dirname(__file__)) + '/../nodes'
|
---|
76 | __version__ = '$Id: gformat.py 10627 2012-05-01 11:00:50Z rick $'
|
---|
77 |
|
---|
78 |
|
---|
79 | files = [
|
---|
80 | 'authorized_keys',
|
---|
81 | 'dnsmasq.conf',
|
---|
82 | 'dhcpd.conf',
|
---|
83 | 'rc.conf.local',
|
---|
84 | 'resolv.conf',
|
---|
85 | 'motd',
|
---|
86 | 'wleiden.yaml',
|
---|
87 | ]
|
---|
88 |
|
---|
89 | # Global variables uses
|
---|
90 | OK = 10
|
---|
91 | DOWN = 20
|
---|
92 | UNKNOWN = 90
|
---|
93 |
|
---|
94 | def get_yaml(item):
|
---|
95 | """ Get configuration yaml for 'item'"""
|
---|
96 | gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
|
---|
97 |
|
---|
98 | # Use some boring defaults
|
---|
99 | datadump = { 'service_proxy_normal' : False, 'service_proxy_ileiden' : False, 'service_accesspoint' : True }
|
---|
100 | f = open(gfile, 'r')
|
---|
101 | datadump.update(yaml.load(f,Loader=Loader))
|
---|
102 | f.close()
|
---|
103 |
|
---|
104 | # Preformat certain needed variables for formatting and push those into special object
|
---|
105 | datadump['autogen_iface_keys'] = get_interface_keys(datadump)
|
---|
106 |
|
---|
107 | wlan_count=0
|
---|
108 | for key in datadump['autogen_iface_keys']:
|
---|
109 | if datadump[key]['type'] in ['11a', '11b', '11g', 'wireless']:
|
---|
110 | datadump[key]['autogen_ifname'] = 'wlan%i' % wlan_count
|
---|
111 | wlan_count += 1
|
---|
112 | else:
|
---|
113 | datadump[key]['autogen_ifname'] = datadump[key]['interface'].split(':')[0]
|
---|
114 |
|
---|
115 | dhcp_interfaces = [datadump[key]['autogen_ifname'] for key in datadump['autogen_iface_keys'] if datadump[key]['dhcp']]
|
---|
116 | datadump['autogen_dhcp_interfaces'] = ','.join(dhcp_interfaces)
|
---|
117 | datadump['autogen_item'] = item
|
---|
118 |
|
---|
119 | datadump['autogen_realname'] = get_realname(datadump)
|
---|
120 | datadump['autogen_domain'] = datadump['domain'] if datadump.has_key('domain') else 'wleiden.net.'
|
---|
121 | datadump['autogen_fqdn'] = datadump['autogen_realname'] + '.' + datadump['autogen_domain']
|
---|
122 | return datadump
|
---|
123 |
|
---|
124 |
|
---|
125 | def store_yaml(datadump, header=False):
|
---|
126 | """ Store configuration yaml for 'item'"""
|
---|
127 | item = datadump['autogen_item']
|
---|
128 | gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
|
---|
129 |
|
---|
130 | f = open(gfile, 'w')
|
---|
131 | f.write(generate_wleiden_yaml(datadump, header))
|
---|
132 | f.close()
|
---|
133 |
|
---|
134 |
|
---|
135 |
|
---|
136 | def make_relations():
|
---|
137 | """ Process _ALL_ yaml files to get connection relations """
|
---|
138 | errors = ""
|
---|
139 | poel = defaultdict(list)
|
---|
140 | for host in get_hostlist():
|
---|
141 | try:
|
---|
142 | datadump = get_yaml(host)
|
---|
143 | for iface_key in datadump['autogen_iface_keys']:
|
---|
144 | l = datadump[iface_key]['ip']
|
---|
145 | addr, mask = l.split('/')
|
---|
146 |
|
---|
147 | # Not parsing of these folks please
|
---|
148 | if not valid_addr(addr):
|
---|
149 | continue
|
---|
150 |
|
---|
151 | addr = parseaddr(addr)
|
---|
152 | mask = int(mask)
|
---|
153 | network = addr & ~((1 << (32 - mask)) - 1)
|
---|
154 | poel[network] += [(host,datadump[iface_key])]
|
---|
155 | except (KeyError, ValueError), e:
|
---|
156 | errors += "[FOUT] in '%s' interface '%s'" % (host,iface_key)
|
---|
157 | errors += e
|
---|
158 | continue
|
---|
159 | return (poel, errors)
|
---|
160 |
|
---|
161 |
|
---|
162 | def get_proxylist():
|
---|
163 | """Get all available proxies proxyX sorting based on X number"""
|
---|
164 | proxylist = sorted([os.path.basename(x) for x in glob.glob("%s/proxy*" % NODE_DIR)],
|
---|
165 | key=lambda name: int(''.join([c for c in name if c in string.digits])),
|
---|
166 | cmp=lambda x,y: x - y) + sorted([os.path.basename(x) for x in glob.glob("%s/Proxy*" % NODE_DIR)])
|
---|
167 | return proxylist
|
---|
168 |
|
---|
169 | def get_hybridlist():
|
---|
170 | """Get all available hybrid nodes/proxies"""
|
---|
171 | hybridlist = sorted([os.path.basename(x) for x in glob.glob("%s/Hybrid*" % NODE_DIR)])
|
---|
172 | return hybridlist
|
---|
173 |
|
---|
174 |
|
---|
175 | def valid_addr(addr):
|
---|
176 | """ Show which address is valid in which are not """
|
---|
177 | return str(addr).startswith('172.')
|
---|
178 |
|
---|
179 |
|
---|
180 | def get_nodelist():
|
---|
181 | """ Get all available nodes - sorted """
|
---|
182 | nodelist = sorted([os.path.basename(x) for x in glob.glob("%s/CNode*" % NODE_DIR)])
|
---|
183 | return nodelist
|
---|
184 |
|
---|
185 | def get_hostlist():
|
---|
186 | """ Combined hosts and proxy list"""
|
---|
187 | return get_nodelist() + get_proxylist() + get_hybridlist()
|
---|
188 |
|
---|
189 | def angle_between_points(lat1,lat2,long1,long2):
|
---|
190 | """
|
---|
191 | Return Angle in radians between two GPS coordinates
|
---|
192 | See: http://stackoverflow.com/questions/3809179/angle-between-2-gps-coordinates
|
---|
193 | """
|
---|
194 | dy = lat2 - lat1
|
---|
195 | dx = math.cos(math.pi/180*lat1)*(long2 - long1)
|
---|
196 | angle = math.atan2(dy,dx)
|
---|
197 | return angle
|
---|
198 |
|
---|
199 | def angle_to_cd(angle):
|
---|
200 | """ Return Dutch Cardinal Direction estimation in 'one digit' of radian angle """
|
---|
201 |
|
---|
202 | # For easy conversion get positive degree
|
---|
203 | degrees = math.degrees(angle)
|
---|
204 | if degrees < 0:
|
---|
205 | 360 - abs(degrees)
|
---|
206 |
|
---|
207 | # Numbers can be confusing calculate from the 4 main directions
|
---|
208 | p = 22.5
|
---|
209 | if degrees < p:
|
---|
210 | return "n"
|
---|
211 | elif degrees < (90 - p):
|
---|
212 | return "no"
|
---|
213 | elif degrees < (90 + p):
|
---|
214 | return "o"
|
---|
215 | elif degrees < (180 - p):
|
---|
216 | return "zo"
|
---|
217 | elif degrees < (180 + p):
|
---|
218 | return "z"
|
---|
219 | elif degrees < (270 - p):
|
---|
220 | return "zw"
|
---|
221 | elif degrees < (270 + p):
|
---|
222 | return "w"
|
---|
223 | elif degrees < (360 - p):
|
---|
224 | return "nw"
|
---|
225 | else:
|
---|
226 | return "n"
|
---|
227 |
|
---|
228 |
|
---|
229 | def generate_title(nodelist):
|
---|
230 | """ Main overview page """
|
---|
231 | items = {'root' : "." }
|
---|
232 | output = """
|
---|
233 | <html>
|
---|
234 | <head>
|
---|
235 | <title>Wireless leiden Configurator - GFormat</title>
|
---|
236 | <style type="text/css">
|
---|
237 | th {background-color: #999999}
|
---|
238 | tr:nth-child(odd) {background-color: #cccccc}
|
---|
239 | tr:nth-child(even) {background-color: #ffffff}
|
---|
240 | th, td {padding: 0.1em 1em}
|
---|
241 | </style>
|
---|
242 | </head>
|
---|
243 | <body>
|
---|
244 | <center>
|
---|
245 | <form type="GET" action="%(root)s">
|
---|
246 | <input type="hidden" name="action" value="update">
|
---|
247 | <input type="submit" value="Update Configuration Database (SVN)">
|
---|
248 | </form>
|
---|
249 | <table>
|
---|
250 | <caption><h3>Wireless Leiden Configurator</h3></caption>
|
---|
251 | """ % items
|
---|
252 |
|
---|
253 | for node in nodelist:
|
---|
254 | items['node'] = node
|
---|
255 | output += '<tr><td><a href="%(root)s/%(node)s">%(node)s</a></td>' % items
|
---|
256 | for config in files:
|
---|
257 | items['config'] = config
|
---|
258 | output += '<td><a href="%(root)s/%(node)s/%(config)s">%(config)s</a></td>' % items
|
---|
259 | output += "</tr>"
|
---|
260 | output += """
|
---|
261 | </table>
|
---|
262 | <hr />
|
---|
263 | <em>%s</em>
|
---|
264 | </center>
|
---|
265 | </body>
|
---|
266 | </html>
|
---|
267 | """ % __version__
|
---|
268 |
|
---|
269 | return output
|
---|
270 |
|
---|
271 |
|
---|
272 |
|
---|
273 | def generate_node(node):
|
---|
274 | """ Print overview of all files available for node """
|
---|
275 | return "\n".join(files)
|
---|
276 |
|
---|
277 | def generate_node_overview(host):
|
---|
278 | """ Print overview of all files available for node """
|
---|
279 | datadump = get_yaml(host)
|
---|
280 | params = { 'host' : host }
|
---|
281 | output = "<em><a href='..'>Back to overview</a></em><hr />"
|
---|
282 | output += "<h2>Available files:</h2><ul>"
|
---|
283 | for cf in files:
|
---|
284 | params['cf'] = cf
|
---|
285 | output += '<li><a href="%(host)s/%(cf)s">%(cf)s</a></li>\n' % params
|
---|
286 | output += "</ul>"
|
---|
287 |
|
---|
288 | # Generate and connection listing
|
---|
289 | output += "<h2>Connected To:</h2><ul>"
|
---|
290 | (poel, errors) = make_relations()
|
---|
291 | for network, hosts in poel.iteritems():
|
---|
292 | if host in [x[0] for x in hosts]:
|
---|
293 | if len(hosts) == 1:
|
---|
294 | # Single not connected interface
|
---|
295 | continue
|
---|
296 | for remote,ifacedump in hosts:
|
---|
297 | if remote == host:
|
---|
298 | # This side of the interface
|
---|
299 | continue
|
---|
300 | params = { 'remote': remote, 'remote_ip' : ifacedump['ip'] }
|
---|
301 | output += '<li><a href="%(remote)s">%(remote)s</a> -- %(remote_ip)s</li>\n' % params
|
---|
302 | output += "</ul>"
|
---|
303 | output += "<h2>MOTD details:</h2><pre>" + generate_motd(datadump) + "</pre>"
|
---|
304 |
|
---|
305 | output += "<hr /><em><a href='..'>Back to overview</a></em>"
|
---|
306 | return output
|
---|
307 |
|
---|
308 |
|
---|
309 | def generate_header(ctag="#"):
|
---|
310 | return """\
|
---|
311 | %(ctag)s
|
---|
312 | %(ctag)s DO NOT EDIT - Automatically generated by 'gformat'
|
---|
313 | %(ctag)s Generated at %(date)s by %(host)s
|
---|
314 | %(ctag)s
|
---|
315 | """ % { 'ctag' : ctag, 'date' : time.ctime(), 'host' : socket.gethostname() }
|
---|
316 |
|
---|
317 |
|
---|
318 |
|
---|
319 | def parseaddr(s):
|
---|
320 | """ Process IPv4 CIDR notation addr to a (binary) number """
|
---|
321 | f = s.split('.')
|
---|
322 | return (long(f[0]) << 24L) + \
|
---|
323 | (long(f[1]) << 16L) + \
|
---|
324 | (long(f[2]) << 8L) + \
|
---|
325 | long(f[3])
|
---|
326 |
|
---|
327 |
|
---|
328 |
|
---|
329 | def showaddr(a):
|
---|
330 | """ Display IPv4 addr in (dotted) CIDR notation """
|
---|
331 | return "%d.%d.%d.%d" % ((a >> 24) & 0xff, (a >> 16) & 0xff, (a >> 8) & 0xff, a & 0xff)
|
---|
332 |
|
---|
333 |
|
---|
334 | def is_member(ip, mask, canidate):
|
---|
335 | """ Return True if canidate is part of ip/mask block"""
|
---|
336 | ip_addr = gformat.parseaddr(ip)
|
---|
337 | ip_canidate = gformat.parseaddr(canidate)
|
---|
338 | mask = int(mask)
|
---|
339 | ip_addr = ip_addr & ~((1 << (32 - mask)) - 1)
|
---|
340 | ip_canidate = ip_canidate & ~((1 << (32 - mask)) - 1)
|
---|
341 | return ip_addr == ip_canidate
|
---|
342 |
|
---|
343 |
|
---|
344 |
|
---|
345 | def cidr2netmask(netmask):
|
---|
346 | """ Given a 'netmask' return corresponding CIDR """
|
---|
347 | return showaddr(0xffffffff & (0xffffffff << (32 - int(netmask))))
|
---|
348 |
|
---|
349 | def get_network(addr, mask):
|
---|
350 | return showaddr(parseaddr(addr) & ~((1 << (32 - int(mask))) - 1))
|
---|
351 |
|
---|
352 |
|
---|
353 | def generate_dhcpd_conf(datadump):
|
---|
354 | """ Generate config file '/usr/local/etc/dhcpd.conf """
|
---|
355 | output = generate_header()
|
---|
356 | output += Template("""\
|
---|
357 | # option definitions common to all supported networks...
|
---|
358 | option domain-name "dhcp.{{ autogen_fqdn }}";
|
---|
359 |
|
---|
360 | default-lease-time 600;
|
---|
361 | max-lease-time 7200;
|
---|
362 |
|
---|
363 | # Use this to enble / disable dynamic dns updates globally.
|
---|
364 | #ddns-update-style none;
|
---|
365 |
|
---|
366 | # If this DHCP server is the official DHCP server for the local
|
---|
367 | # network, the authoritative directive should be uncommented.
|
---|
368 | authoritative;
|
---|
369 |
|
---|
370 | # Use this to send dhcp log messages to a different log file (you also
|
---|
371 | # have to hack syslog.conf to complete the redirection).
|
---|
372 | log-facility local7;
|
---|
373 |
|
---|
374 | #
|
---|
375 | # Interface definitions
|
---|
376 | #
|
---|
377 | \n""").render(datadump)
|
---|
378 |
|
---|
379 | for iface_key in datadump['autogen_iface_keys']:
|
---|
380 | if not datadump[iface_key].has_key('comment'):
|
---|
381 | datadump[iface_key]['comment'] = None
|
---|
382 | output += "## %(interface)s - %(desc)s - %(comment)s\n" % datadump[iface_key]
|
---|
383 |
|
---|
384 | (addr, mask) = datadump[iface_key]['ip'].split('/')
|
---|
385 | datadump[iface_key]['addr'] = addr
|
---|
386 | datadump[iface_key]['netmask'] = cidr2netmask(mask)
|
---|
387 | datadump[iface_key]['subnet'] = get_network(addr, mask)
|
---|
388 | try:
|
---|
389 | (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
|
---|
390 | except (AttributeError, ValueError):
|
---|
391 | output += "subnet %(subnet)s netmask %(netmask)s {\n ### not autoritive\n}\n\n" % datadump[iface_key]
|
---|
392 | continue
|
---|
393 |
|
---|
394 | dhcp_part = ".".join(addr.split('.')[0:3])
|
---|
395 | datadump[iface_key]['dhcp_start'] = dhcp_part + "." + dhcp_start
|
---|
396 | datadump[iface_key]['dhcp_stop'] = dhcp_part + "." + dhcp_stop
|
---|
397 | output += """\
|
---|
398 | subnet %(subnet)s netmask %(netmask)s {
|
---|
399 | range %(dhcp_start)s %(dhcp_stop)s;
|
---|
400 | option routers %(addr)s;
|
---|
401 | option domain-name-servers %(addr)s;
|
---|
402 | }
|
---|
403 | \n""" % datadump[iface_key]
|
---|
404 |
|
---|
405 | return output
|
---|
406 |
|
---|
407 |
|
---|
408 |
|
---|
409 | def generate_dnsmasq_conf(datadump):
|
---|
410 | """ Generate configuration file '/usr/local/etc/dnsmasq.conf' """
|
---|
411 | output = generate_header()
|
---|
412 | output += Template("""\
|
---|
413 | # DHCP server options
|
---|
414 | dhcp-authoritative
|
---|
415 | dhcp-fqdn
|
---|
416 | domain=dhcp.{{ autogen_fqdn }}
|
---|
417 | domain-needed
|
---|
418 | expand-hosts
|
---|
419 | log-async=100
|
---|
420 |
|
---|
421 | # Low memory footprint
|
---|
422 | cache-size=10000
|
---|
423 |
|
---|
424 | \n""").render(datadump)
|
---|
425 |
|
---|
426 | for iface_key in datadump['autogen_iface_keys']:
|
---|
427 | if not datadump[iface_key].has_key('comment'):
|
---|
428 | datadump[iface_key]['comment'] = None
|
---|
429 | output += "## %(interface)s - %(desc)s - %(comment)s\n" % datadump[iface_key]
|
---|
430 |
|
---|
431 | try:
|
---|
432 | (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
|
---|
433 | (ip, cidr) = datadump[iface_key]['ip'].split('/')
|
---|
434 | datadump[iface_key]['netmask'] = cidr2netmask(cidr)
|
---|
435 | except (AttributeError, ValueError):
|
---|
436 | output += "# not autoritive\n\n"
|
---|
437 | continue
|
---|
438 |
|
---|
439 | dhcp_part = ".".join(ip.split('.')[0:3])
|
---|
440 | datadump[iface_key]['dhcp_start'] = dhcp_part + "." + dhcp_start
|
---|
441 | datadump[iface_key]['dhcp_stop'] = dhcp_part + "." + dhcp_stop
|
---|
442 | output += "dhcp-range=%(interface)s,%(dhcp_start)s,%(dhcp_stop)s,%(netmask)s,24h\n\n" % datadump[iface_key]
|
---|
443 |
|
---|
444 | return output
|
---|
445 |
|
---|
446 |
|
---|
447 |
|
---|
448 | def generate_rc_conf_local(datadump):
|
---|
449 | """ Generate configuration file '/etc/rc.conf.local' """
|
---|
450 | if not datadump.has_key('ileiden'):
|
---|
451 | datadump['autogen_ileiden_enable'] = False
|
---|
452 | else:
|
---|
453 | datadump['autogen_ileiden_enable'] = datadump['ileiden']
|
---|
454 |
|
---|
455 | datadump['autogen_ileiden_enable'] = switchFormat(datadump['autogen_ileiden_enable'])
|
---|
456 |
|
---|
457 | ileiden_proxies = []
|
---|
458 | normal_proxies = []
|
---|
459 | for proxy in get_proxylist():
|
---|
460 | proxydump = get_yaml(proxy)
|
---|
461 | if proxydump['ileiden']:
|
---|
462 | ileiden_proxies.append(proxydump)
|
---|
463 | else:
|
---|
464 | normal_proxies.append(proxydump)
|
---|
465 | for host in get_hybridlist():
|
---|
466 | hostdump = get_yaml(host)
|
---|
467 | if hostdump['service_proxy_ileiden']:
|
---|
468 | ileiden_proxies.append(hostdump)
|
---|
469 | if hostdump['service_proxy_normal']:
|
---|
470 | normal_proxies.append(hostdump)
|
---|
471 |
|
---|
472 | datadump['autogen_ileiden_proxies'] = ileiden_proxies
|
---|
473 | datadump['autogen_normal_proxies'] = normal_proxies
|
---|
474 | datadump['autogen_ileiden_proxies_ips'] = ','.join([x['masterip'] for x in ileiden_proxies])
|
---|
475 | datadump['autogen_ileiden_proxies_names'] = ','.join([x['autogen_item'] for x in ileiden_proxies])
|
---|
476 | datadump['autogen_normal_proxies_ips'] = ','.join([x['masterip'] for x in normal_proxies])
|
---|
477 | datadump['autogen_normal_proxies_names'] = ','.join([x['autogen_item'] for x in normal_proxies])
|
---|
478 |
|
---|
479 | output = generate_header("#");
|
---|
480 | output += render_template(datadump, """\
|
---|
481 | hostname='{{ autogen_fqdn }}'
|
---|
482 | location='{{ location }}'
|
---|
483 | nodetype="{{ nodetype }}"
|
---|
484 |
|
---|
485 | #
|
---|
486 | # Configured listings
|
---|
487 | #
|
---|
488 | captive_portal_whitelist=""
|
---|
489 | {% if nodetype == "Proxy" %}
|
---|
490 | #
|
---|
491 | # Proxy Configuration
|
---|
492 | #
|
---|
493 | {% if gateway -%}
|
---|
494 | defaultrouter="{{ gateway }}"
|
---|
495 | {% else -%}
|
---|
496 | #defaultrouter="NOTSET"
|
---|
497 | {% endif -%}
|
---|
498 | internalif="{{ internalif }}"
|
---|
499 | ileiden_enable="{{ autogen_ileiden_enable }}"
|
---|
500 | gateway_enable="{{ autogen_ileiden_enable }}"
|
---|
501 | pf_enable="yes"
|
---|
502 | pf_rules="/etc/pf.conf"
|
---|
503 | {% if autogen_ileiden_enable -%}
|
---|
504 | pf_flags="-D ext_if={{ externalif }} -D int_if={{ internalif }} -D publicnat={80,443}"
|
---|
505 | lvrouted_enable="{{ autogen_ileiden_enable }}"
|
---|
506 | lvrouted_flags="-u -s s00p3rs3kr3t -m 28"
|
---|
507 | {% else -%}
|
---|
508 | pf_flags="-D ext_if={{ externalif }} -D int_if={{ internalif }} -D publicnat={0}"
|
---|
509 | {% endif -%}
|
---|
510 | {% if internalroute -%}
|
---|
511 | static_routes="wleiden"
|
---|
512 | route_wleiden="-net 172.16.0.0/12 {{ internalroute }}"
|
---|
513 | {% endif -%}
|
---|
514 |
|
---|
515 | {% elif nodetype == "Hybrid" %}
|
---|
516 | #
|
---|
517 | # Hybrid Configuration
|
---|
518 | #
|
---|
519 | list_ileiden_proxies="
|
---|
520 | {% for item in autogen_ileiden_proxies -%}
|
---|
521 | {{ "%-16s"|format(item.masterip) }} # {{ item.autogen_realname }}
|
---|
522 | {% endfor -%}
|
---|
523 | "
|
---|
524 | list_normal_proxies="
|
---|
525 | {% for item in autogen_normal_proxies -%}
|
---|
526 | {{ "%-16s"|format(item.masterip) }} # {{ item.autogen_realname }}
|
---|
527 | {% endfor -%}
|
---|
528 | "
|
---|
529 |
|
---|
530 | captive_portal_interfaces="{{ autogen_dhcp_interfaces|default('none', true) }}"
|
---|
531 | externalif="{{ externalif|default('vr0', true) }}"
|
---|
532 | masterip="{{ masterip }}"
|
---|
533 |
|
---|
534 | # Defined services
|
---|
535 | service_proxy_ileiden="{{ service_proxy_ileiden|yesorno }}"
|
---|
536 | service_proxy_normal="{{ service_proxy_normal|yesorno }}"
|
---|
537 | service_accesspoint="{{ service_accesspoint|yesorno }}"
|
---|
538 | #
|
---|
539 |
|
---|
540 | {% if service_proxy_ileiden %}
|
---|
541 | pf_rules="/etc/pf.hybrid.conf"
|
---|
542 | pf_flags="-D ext_if=$externalif -D ext_if_net=$externalif:network -D masterip=$masterip"
|
---|
543 | pf_flags="$pf_flags -D publicnat=80,443"
|
---|
544 | {% elif service_proxy_normal %}
|
---|
545 | pf_rules="/etc/pf.proxy.conf"
|
---|
546 | pf_flags="-D ext_if=$externalif -D ext_if_net=$externalif:network -D masterip=$masterip"
|
---|
547 | pf_flags="$pf_flags -D ext_if_gw=${ext_if_gw:-"{{ gateway|default('127.127.127.127') }}"}"
|
---|
548 | lvrouted_flags="$lvrouted_flags -z `make_list "$list_ileiden_proxies" ","`"
|
---|
549 | {% else %}
|
---|
550 | pf_rules="/etc/pf.node.conf"
|
---|
551 | pf_flags=""
|
---|
552 | {% endif %}
|
---|
553 |
|
---|
554 | {% if service_proxy_normal %}
|
---|
555 | tinyproxy_enable="yes"
|
---|
556 | {% else %}
|
---|
557 | pen_wrapper_enable="yes"
|
---|
558 | {% endif %}
|
---|
559 |
|
---|
560 | {% if service_accesspoint %}
|
---|
561 | pf_flags="$pf_flags -D captive_portal_interfaces=$captive_portal_interfaces"
|
---|
562 | {% endif %}
|
---|
563 |
|
---|
564 | {% if board == "ALIX2" %}
|
---|
565 | #
|
---|
566 | # ''Fat'' configuration, board has 256MB RAM
|
---|
567 | #
|
---|
568 | dnsmasq_enable="NO"
|
---|
569 | named_enable="YES"
|
---|
570 | dhcpd_enable="YES"
|
---|
571 | {% endif -%}
|
---|
572 |
|
---|
573 | {% if service_proxy_ileiden and gateway %}
|
---|
574 | defaultrouter="{{ gateway }}"
|
---|
575 | {% endif %}
|
---|
576 | {% elif nodetype == "CNode" %}
|
---|
577 | #
|
---|
578 | # NODE iLeiden Configuration
|
---|
579 | #
|
---|
580 |
|
---|
581 | # iLeiden Proxies {{ autogen_ileiden_proxies_names }}
|
---|
582 | list_ileiden_proxies="{{ autogen_ileiden_proxies_ips }}"
|
---|
583 | # normal Proxies {{ autogen_normal_proxies_names }}
|
---|
584 | list_normal_proxies="{{ autogen_normal_proxies_ips }}"
|
---|
585 |
|
---|
586 | captive_portal_interfaces="{{ autogen_dhcp_interfaces }}"
|
---|
587 |
|
---|
588 | {% if tproxy -%}
|
---|
589 | tproxy_enable='YES'
|
---|
590 | tproxy_range='{{ tproxy }}'
|
---|
591 | {% else -%}
|
---|
592 | tproxy_enable='NO'
|
---|
593 | {% endif -%}
|
---|
594 |
|
---|
595 | lvrouted_flags="-u -s s00p3rs3kr3t -m 28 -z $list_ileiden_proxies"
|
---|
596 | {% endif %}
|
---|
597 |
|
---|
598 | #
|
---|
599 | # Interface definitions
|
---|
600 | #\n
|
---|
601 | """)
|
---|
602 |
|
---|
603 | # lo0 configuration:
|
---|
604 | # - 172.32.255.1/32 is the proxy.wleiden.net deflector
|
---|
605 | # - masterip is special as it needs to be assigned to at
|
---|
606 | # least one interface, so if not used assign to lo0
|
---|
607 | addrs_list = { 'lo0' : [("127.0.0.1/8", "LocalHost"), ("172.31.255.1/32","Proxy IP")] }
|
---|
608 | iface_map = {'lo0' : 'lo0'}
|
---|
609 | dhclient_if = {'lo0' : False}
|
---|
610 |
|
---|
611 | masterip_used = False
|
---|
612 | for iface_key in datadump['autogen_iface_keys']:
|
---|
613 | if datadump[iface_key]['ip'].startswith(datadump['masterip']):
|
---|
614 | masterip_used = True
|
---|
615 | break
|
---|
616 | if not masterip_used:
|
---|
617 | addrs_list['lo0'].append((datadump['masterip'] + "/32", 'Master IP Not used in interface'))
|
---|
618 |
|
---|
619 | for iface_key in datadump['autogen_iface_keys']:
|
---|
620 | ifacedump = datadump[iface_key]
|
---|
621 | ifname = ifacedump['autogen_ifname']
|
---|
622 |
|
---|
623 | # Flag dhclient is possible
|
---|
624 | dhclient_if[ifname] = ifacedump.has_key('dhcpclient') and ifacedump['dhcpclient']
|
---|
625 |
|
---|
626 | # Add interface IP to list
|
---|
627 | item = (ifacedump['ip'], ifacedump['desc'])
|
---|
628 | if addrs_list.has_key(ifname):
|
---|
629 | addrs_list[ifname].append(item)
|
---|
630 | else:
|
---|
631 | addrs_list[ifname] = [item]
|
---|
632 |
|
---|
633 | # Alias only needs IP assignment for now, this might change if we
|
---|
634 | # are going to use virtual accesspoints
|
---|
635 | if "alias" in iface_key:
|
---|
636 | continue
|
---|
637 |
|
---|
638 | # XXX: Might want to deduct type directly from interface name
|
---|
639 | if ifacedump['type'] in ['11a', '11b', '11g', 'wireless']:
|
---|
640 | # Default to station (client) mode
|
---|
641 | ifacedump['wlanmode'] = "sta"
|
---|
642 | if ifacedump['mode'] in ['master', 'master-wds', 'ap', 'ap-wds']:
|
---|
643 | ifacedump['wlanmode'] = "ap"
|
---|
644 | # Default to 802.11b mode
|
---|
645 | ifacedump['mode'] = '11b'
|
---|
646 | if ifacedump['type'] in ['11a', '11b' '11g']:
|
---|
647 | ifacedump['mode'] = ifacedump['type']
|
---|
648 |
|
---|
649 | if not ifacedump.has_key('channel'):
|
---|
650 | if ifacedump['type'] == '11a':
|
---|
651 | ifacedump['channel'] = 36
|
---|
652 | else:
|
---|
653 | ifacedump['channel'] = 1
|
---|
654 |
|
---|
655 | # Allow special hacks at the back like wds and stuff
|
---|
656 | if not ifacedump.has_key('extra'):
|
---|
657 | ifacedump['extra'] = 'regdomain ETSI country NL'
|
---|
658 |
|
---|
659 | output += "wlans_%(interface)s='%(autogen_ifname)s'\n" % ifacedump
|
---|
660 | output += ("create_args_%(autogen_ifname)s='wlanmode %(wlanmode)s mode " +\
|
---|
661 | "%(mode)s ssid %(ssid)s %(extra)s channel %(channel)s'\n") % ifacedump
|
---|
662 |
|
---|
663 | elif ifacedump['type'] in ['ethernet', 'eth']:
|
---|
664 | # No special config needed besides IP
|
---|
665 | pass
|
---|
666 | else:
|
---|
667 | assert False, "Unknown type " + ifacedump['type']
|
---|
668 |
|
---|
669 | # Print IP address which needs to be assigned over here
|
---|
670 | output += "\n"
|
---|
671 | for iface,addrs in sorted(addrs_list.iteritems()):
|
---|
672 | for addr, comment in sorted(addrs,key=lambda x: parseaddr(x[0].split('/')[0])):
|
---|
673 | output += "# %s || %s || %s\n" % (iface, addr, comment)
|
---|
674 |
|
---|
675 | # Write DHCLIENT entry
|
---|
676 | if dhclient_if[iface]:
|
---|
677 | output += "ifconfig_%s='SYNCDHCP'\n\n" % (iface)
|
---|
678 | else:
|
---|
679 | output += "ipv4_addrs_%s='%s'\n\n" % (iface, " ".join([x[0] for x in addrs]))
|
---|
680 |
|
---|
681 | return output
|
---|
682 |
|
---|
683 |
|
---|
684 |
|
---|
685 |
|
---|
686 | def get_all_configs():
|
---|
687 | """ Get dict with key 'host' with all configs present """
|
---|
688 | configs = dict()
|
---|
689 | for host in get_hostlist():
|
---|
690 | datadump = get_yaml(host)
|
---|
691 | configs[host] = datadump
|
---|
692 | return configs
|
---|
693 |
|
---|
694 |
|
---|
695 | def get_interface_keys(config):
|
---|
696 | """ Quick hack to get all interface keys, later stage convert this to a iterator """
|
---|
697 | return sorted([elem for elem in config.keys() if (elem.startswith('iface_') and not "lo0" in elem)])
|
---|
698 |
|
---|
699 |
|
---|
700 | def get_used_ips(configs):
|
---|
701 | """ Return array of all IPs used in config files"""
|
---|
702 | ip_list = []
|
---|
703 | for config in configs:
|
---|
704 | ip_list.append(config['masterip'])
|
---|
705 | for iface_key in get_interface_keys(config):
|
---|
706 | l = config[iface_key]['ip']
|
---|
707 | addr, mask = l.split('/')
|
---|
708 | # Special case do not process
|
---|
709 | if valid_addr(addr):
|
---|
710 | ip_list.append(addr)
|
---|
711 | else:
|
---|
712 | logger.error("## IP '%s' in '%s' not valid" % (addr, config['nodename']))
|
---|
713 | return sorted(ip_list)
|
---|
714 |
|
---|
715 |
|
---|
716 |
|
---|
717 | def generate_resolv_conf(datadump):
|
---|
718 | """ Generate configuration file '/etc/resolv.conf' """
|
---|
719 | # XXX: This should properly going to be an datastructure soon
|
---|
720 | datadump['autogen_header'] = generate_header("#")
|
---|
721 | datadump['autogen_edge_nameservers'] = ''
|
---|
722 | for host in get_proxylist():
|
---|
723 | hostdump = get_yaml(host)
|
---|
724 | datadump['autogen_edge_nameservers'] += "nameserver %(masterip)-15s # %(autogen_realname)s\n" % hostdump
|
---|
725 | for host in get_hybridlist():
|
---|
726 | hostdump = get_yaml(host)
|
---|
727 | if hostdump['service_proxy_ileiden'] or hostdump['service_proxy_normal']:
|
---|
728 | datadump['autogen_edge_nameservers'] += "nameserver %(masterip)-15s # %(autogen_realname)s\n" % hostdump
|
---|
729 |
|
---|
730 | return Template("""\
|
---|
731 | {{ autogen_header }}
|
---|
732 | search wleiden.net
|
---|
733 |
|
---|
734 | # Try local (cache) first
|
---|
735 | nameserver 127.0.0.1
|
---|
736 |
|
---|
737 | {% if service_proxy_normal or service_proxy_ileiden or nodetype == 'Proxy' -%}
|
---|
738 | nameserver 8.8.8.8 # Google Public NameServer
|
---|
739 | nameserver 8.8.4.4 # Google Public NameServer
|
---|
740 | {% else -%}
|
---|
741 | {{ autogen_edge_nameservers }}
|
---|
742 | {% endif -%}
|
---|
743 | """).render(datadump)
|
---|
744 |
|
---|
745 |
|
---|
746 |
|
---|
747 | def generate_motd(datadump):
|
---|
748 | """ Generate configuration file '/etc/motd' """
|
---|
749 | output = Template("""\
|
---|
750 | FreeBSD run ``service motd onestart'' to make me look normal
|
---|
751 |
|
---|
752 | WWW: {{ autogen_fqdn }} - http://www.wirelessleiden.nl
|
---|
753 | Loc: {{ location }}
|
---|
754 |
|
---|
755 | Services:
|
---|
756 | {% if board == "ALIX2" -%}
|
---|
757 | - Core Node
|
---|
758 | {% else -%}
|
---|
759 | - Hulp Node
|
---|
760 | {% endif -%}
|
---|
761 | {% if service_proxy_normal -%}
|
---|
762 | - Normal Proxy
|
---|
763 | {% endif -%}
|
---|
764 | {% if service_proxy_ileiden -%}
|
---|
765 | - iLeiden Proxy
|
---|
766 | {% endif %}
|
---|
767 | Interlinks:\n
|
---|
768 | """).render(datadump)
|
---|
769 |
|
---|
770 | # XXX: This is a hacky way to get the required data
|
---|
771 | for line in generate_rc_conf_local(datadump).split('\n'):
|
---|
772 | if '||' in line and not line[1:].split()[0] in ['lo0', 'ath0'] :
|
---|
773 | output += " - %s \n" % line[1:]
|
---|
774 | output += """\
|
---|
775 | Attached bridges:
|
---|
776 | """
|
---|
777 | for iface_key in datadump['autogen_iface_keys']:
|
---|
778 | ifacedump = datadump[iface_key]
|
---|
779 | if ifacedump.has_key('ns_ip'):
|
---|
780 | output += " - %(interface)s || %(mode)s || %(ns_ip)s\n" % ifacedump
|
---|
781 |
|
---|
782 | return output
|
---|
783 |
|
---|
784 |
|
---|
785 | def format_yaml_value(value):
|
---|
786 | """ Get yaml value in right syntax for outputting """
|
---|
787 | if isinstance(value,str):
|
---|
788 | output = '"%s"' % value
|
---|
789 | else:
|
---|
790 | output = value
|
---|
791 | return output
|
---|
792 |
|
---|
793 |
|
---|
794 |
|
---|
795 | def format_wleiden_yaml(datadump):
|
---|
796 | """ Special formatting to ensure it is editable"""
|
---|
797 | output = "# Genesis config yaml style\n"
|
---|
798 | output += "# vim:ts=2:et:sw=2:ai\n"
|
---|
799 | output += "#\n"
|
---|
800 | iface_keys = [elem for elem in datadump.keys() if elem.startswith('iface_')]
|
---|
801 | for key in sorted(set(datadump.keys()) - set(iface_keys)):
|
---|
802 | output += "%-10s: %s\n" % (key, format_yaml_value(datadump[key]))
|
---|
803 |
|
---|
804 | output += "\n\n"
|
---|
805 |
|
---|
806 | key_order = [ 'comment', 'interface', 'ip', 'desc', 'sdesc', 'mode', 'type',
|
---|
807 | 'extra_type', 'channel', 'ssid', 'dhcp' ]
|
---|
808 |
|
---|
809 | for iface_key in sorted(iface_keys):
|
---|
810 | output += "%s:\n" % iface_key
|
---|
811 | for key in key_order + list(sorted(set(datadump[iface_key].keys()) - set(key_order))):
|
---|
812 | if datadump[iface_key].has_key(key):
|
---|
813 | output += " %-11s: %s\n" % (key, format_yaml_value(datadump[iface_key][key]))
|
---|
814 | output += "\n\n"
|
---|
815 |
|
---|
816 | return output
|
---|
817 |
|
---|
818 |
|
---|
819 |
|
---|
820 | def generate_wleiden_yaml(datadump, header=True):
|
---|
821 | """ Generate (petty) version of wleiden.yaml"""
|
---|
822 | for key in datadump.keys():
|
---|
823 | if key.startswith('autogen_'):
|
---|
824 | del datadump[key]
|
---|
825 | # Interface autogen cleanups
|
---|
826 | elif type(datadump[key]) == dict:
|
---|
827 | for key2 in datadump[key].keys():
|
---|
828 | if key2.startswith('autogen_'):
|
---|
829 | del datadump[key][key2]
|
---|
830 |
|
---|
831 | output = generate_header("#") if header else ''
|
---|
832 | output += format_wleiden_yaml(datadump)
|
---|
833 | return output
|
---|
834 |
|
---|
835 |
|
---|
836 | def generate_yaml(datadump):
|
---|
837 | return generate_config(datadump['nodename'], "wleiden.yaml", datadump)
|
---|
838 |
|
---|
839 |
|
---|
840 |
|
---|
841 | def generate_config(node, config, datadump=None):
|
---|
842 | """ Print configuration file 'config' of 'node' """
|
---|
843 | output = ""
|
---|
844 | try:
|
---|
845 | # Load config file
|
---|
846 | if datadump == None:
|
---|
847 | datadump = get_yaml(node)
|
---|
848 |
|
---|
849 | if config == 'wleiden.yaml':
|
---|
850 | output += generate_wleiden_yaml(datadump)
|
---|
851 | elif config == 'authorized_keys':
|
---|
852 | f = open(os.path.join(NODE_DIR,"global_keys"), 'r')
|
---|
853 | output += f.read()
|
---|
854 | f.close()
|
---|
855 | elif config == 'dnsmasq.conf':
|
---|
856 | output += generate_dnsmasq_conf(datadump)
|
---|
857 | elif config == 'dhcpd.conf':
|
---|
858 | output += generate_dhcpd_conf(datadump)
|
---|
859 | elif config == 'rc.conf.local':
|
---|
860 | output += generate_rc_conf_local(datadump)
|
---|
861 | elif config == 'resolv.conf':
|
---|
862 | output += generate_resolv_conf(datadump)
|
---|
863 | elif config == 'motd':
|
---|
864 | output += generate_motd(datadump)
|
---|
865 | else:
|
---|
866 | assert False, "Config not found!"
|
---|
867 | except IOError, e:
|
---|
868 | output += "[ERROR] Config file not found"
|
---|
869 | return output
|
---|
870 |
|
---|
871 |
|
---|
872 |
|
---|
873 | def process_cgi_request():
|
---|
874 | """ When calling from CGI """
|
---|
875 | # Update repository if requested
|
---|
876 | form = cgi.FieldStorage()
|
---|
877 | if form.getvalue("action") == "update":
|
---|
878 | print "Refresh: 5; url=."
|
---|
879 | print "Content-type:text/plain\r\n\r\n",
|
---|
880 | print "[INFO] Updating subverion, please wait..."
|
---|
881 | print subprocess.Popen(['svn', 'cleanup', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0],
|
---|
882 | print subprocess.Popen(['svn', 'up', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0],
|
---|
883 | print "[INFO] All done, redirecting in 5 seconds"
|
---|
884 | sys.exit(0)
|
---|
885 |
|
---|
886 |
|
---|
887 | base_uri = os.environ['PATH_INFO']
|
---|
888 | uri = base_uri.strip('/').split('/')
|
---|
889 |
|
---|
890 | output = ""
|
---|
891 | if base_uri.endswith('/create/network.kml'):
|
---|
892 | output += "Content-type:application/vnd.google-earth.kml+xml\r\n\r\n"
|
---|
893 | output += make_network_kml.make_graph()
|
---|
894 | elif not uri[0]:
|
---|
895 | if is_text_request():
|
---|
896 | output += "Content-type:text/plain\r\n\r\n"
|
---|
897 | output += '\n'.join(get_hostlist())
|
---|
898 | else:
|
---|
899 | output += "Content-type:text/html\r\n\r\n"
|
---|
900 | output += generate_title(get_hostlist())
|
---|
901 | elif len(uri) == 1:
|
---|
902 | if is_text_request():
|
---|
903 | output += "Content-type:text/plain\r\n\r\n"
|
---|
904 | output += generate_node(uri[0])
|
---|
905 | else:
|
---|
906 | output += "Content-type:text/html\r\n\r\n"
|
---|
907 | output += generate_node_overview(uri[0])
|
---|
908 | elif len(uri) == 2:
|
---|
909 | output += "Content-type:text/plain\r\n\r\n"
|
---|
910 | output += generate_config(uri[0], uri[1])
|
---|
911 | else:
|
---|
912 | assert False, "Invalid option"
|
---|
913 | print output
|
---|
914 |
|
---|
915 | def get_realname(datadump):
|
---|
916 | # Proxy naming convention is special, as the proxy name is also included in
|
---|
917 | # the nodename, when it comes to the numbered proxies.
|
---|
918 | if datadump['nodetype'] == 'Proxy':
|
---|
919 | realname = datadump['nodetype'] + datadump['nodename'].replace('proxy','')
|
---|
920 | else:
|
---|
921 | # By default the full name is listed and also a shortname CNAME for easy use.
|
---|
922 | realname = datadump['nodetype'] + datadump['nodename']
|
---|
923 | return(realname)
|
---|
924 |
|
---|
925 |
|
---|
926 |
|
---|
927 | def make_dns(output_dir = 'dns', external = False):
|
---|
928 | items = dict()
|
---|
929 |
|
---|
930 | # hostname is key, IP is value
|
---|
931 | wleiden_zone = dict()
|
---|
932 | wleiden_cname = dict()
|
---|
933 |
|
---|
934 | pool = dict()
|
---|
935 | for node in get_hostlist():
|
---|
936 | datadump = get_yaml(node)
|
---|
937 |
|
---|
938 | # Proxy naming convention is special
|
---|
939 | fqdn = datadump['autogen_realname']
|
---|
940 | if datadump['nodetype'] in ['CNode', 'Hybrid']:
|
---|
941 | wleiden_cname[datadump['nodename']] = fqdn
|
---|
942 |
|
---|
943 | wleiden_zone[fqdn] = datadump['masterip']
|
---|
944 |
|
---|
945 | # Hacking to get proper DHCP IPs and hostnames
|
---|
946 | for iface_key in get_interface_keys(datadump):
|
---|
947 | iface_name = datadump[iface_key]['interface'].replace(':',"-alias-")
|
---|
948 | (ip, cidr) = datadump[iface_key]['ip'].split('/')
|
---|
949 | try:
|
---|
950 | (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
|
---|
951 | datadump[iface_key]['netmask'] = cidr2netmask(cidr)
|
---|
952 | dhcp_part = ".".join(ip.split('.')[0:3])
|
---|
953 | if ip != datadump['masterip']:
|
---|
954 | wleiden_zone["dhcp-gateway-%s.%s" % (iface_name, fqdn)] = ip
|
---|
955 | for i in range(int(dhcp_start), int(dhcp_stop) + 1):
|
---|
956 | wleiden_zone["dhcp-%s-%s.%s" % (i, iface_name, fqdn)] = "%s.%s" % (dhcp_part, i)
|
---|
957 | except (AttributeError, ValueError):
|
---|
958 | # First push it into a pool, to indentify the counter-part later on
|
---|
959 | addr = parseaddr(ip)
|
---|
960 | cidr = int(cidr)
|
---|
961 | addr = addr & ~((1 << (32 - cidr)) - 1)
|
---|
962 | if pool.has_key(addr):
|
---|
963 | pool[addr] += [(iface_name, fqdn, ip)]
|
---|
964 | else:
|
---|
965 | pool[addr] = [(iface_name, fqdn, ip)]
|
---|
966 | continue
|
---|
967 |
|
---|
968 |
|
---|
969 | def pool_to_name(node, pool_members):
|
---|
970 | """Convert the joined name to a usable pool name"""
|
---|
971 |
|
---|
972 | # Get rid of the own entry
|
---|
973 | pool_members = list(set(pool_members) - set([fqdn]))
|
---|
974 |
|
---|
975 | target = oldname = ''
|
---|
976 | for node in sorted(pool_members):
|
---|
977 | (name, number) = re.match('^([A-Za-z]+)([0-9]*)$',node).group(1,2)
|
---|
978 | target += "-" + number if name == oldname else "-" + node if target else node
|
---|
979 | oldname = name
|
---|
980 |
|
---|
981 | return target
|
---|
982 |
|
---|
983 |
|
---|
984 | # WL uses an /29 to configure an interface. IP's are ordered like this:
|
---|
985 | # MasterA (.1) -- DeviceA (.2) <<>> DeviceB (.3) --- SlaveB (.4)
|
---|
986 |
|
---|
987 | sn = lambda x: re.sub(r'(?i)^cnode','',x)
|
---|
988 |
|
---|
989 | # Automatic naming convention of interlinks namely 2 + remote.lower()
|
---|
990 | for (key,value) in pool.iteritems():
|
---|
991 | # Make sure they are sorted from low-ip to high-ip
|
---|
992 | value = sorted(value, key=lambda x: parseaddr(x[2]))
|
---|
993 |
|
---|
994 | if len(value) == 1:
|
---|
995 | (iface_name, fqdn, ip) = value[0]
|
---|
996 | wleiden_zone["2unused-%s.%s" % (iface_name, fqdn)] = ip
|
---|
997 |
|
---|
998 | # Device DNS names
|
---|
999 | if 'cnode' in fqdn.lower():
|
---|
1000 | wleiden_zone["d-at-%s.%s" % (iface_name, fqdn)] = showaddr(parseaddr(ip) + 1)
|
---|
1001 | wleiden_cname["d-at-%s.%s" % (iface_name,sn(fqdn))] = "d-at-%s.%s" % (iface_name, fqdn)
|
---|
1002 |
|
---|
1003 | elif len(value) == 2:
|
---|
1004 | (a_iface_name, a_fqdn, a_ip) = value[0]
|
---|
1005 | (b_iface_name, b_fqdn, b_ip) = value[1]
|
---|
1006 | wleiden_zone["2%s.%s" % (b_fqdn,a_fqdn)] = a_ip
|
---|
1007 | wleiden_zone["2%s.%s" % (a_fqdn,b_fqdn)] = b_ip
|
---|
1008 |
|
---|
1009 | # Device DNS names
|
---|
1010 | if 'cnode' in a_fqdn.lower() and 'cnode' in b_fqdn.lower():
|
---|
1011 | wleiden_zone["d-at-%s.%s" % (a_iface_name, a_fqdn)] = showaddr(parseaddr(a_ip) + 1)
|
---|
1012 | wleiden_zone["d-at-%s.%s" % (b_iface_name, b_fqdn)] = showaddr(parseaddr(b_ip) - 1)
|
---|
1013 | wleiden_cname["d-at-%s.%s" % (a_iface_name,sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
|
---|
1014 | wleiden_cname["d-at-%s.%s" % (b_iface_name,sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
|
---|
1015 | wleiden_cname["d2%s.%s" % (sn(b_fqdn),sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
|
---|
1016 | wleiden_cname["d2%s.%s" % (sn(a_fqdn),sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
|
---|
1017 |
|
---|
1018 | else:
|
---|
1019 | pool_members = [k[1] for k in value]
|
---|
1020 | for item in value:
|
---|
1021 | (iface_name, fqdn, ip) = item
|
---|
1022 | pool_name = "2pool-" + showaddr(key).replace('.','-') + "-" + pool_to_name(fqdn,pool_members)
|
---|
1023 | wleiden_zone["%s.%s" % (pool_name, fqdn)] = ip
|
---|
1024 |
|
---|
1025 | # Include static DNS entries
|
---|
1026 | # XXX: Should they override the autogenerated results?
|
---|
1027 | # XXX: Convert input to yaml more useable.
|
---|
1028 | # Format:
|
---|
1029 | ##; this is a comment
|
---|
1030 | ## roomburgh=CNodeRoomburgh1
|
---|
1031 | ## apkerk1.CNodeVosko=172.17.176.8 ;this as well
|
---|
1032 | dns = yaml.load(open(os.path.join(NODE_DIR,'../dns/staticDNS.yaml'),'r'))
|
---|
1033 |
|
---|
1034 | # Hack to allow special entries, for development
|
---|
1035 | wleiden_raw = dns['raw']
|
---|
1036 | del dns['raw']
|
---|
1037 |
|
---|
1038 | for comment, block in dns.iteritems():
|
---|
1039 | for k,v in block.iteritems():
|
---|
1040 | if valid_addr(v):
|
---|
1041 | wleiden_zone[k] = v
|
---|
1042 | else:
|
---|
1043 | wleiden_cname[k] = v
|
---|
1044 |
|
---|
1045 | details = dict()
|
---|
1046 | # 24 updates a day allowed
|
---|
1047 | details['serial'] = time.strftime('%Y%m%d%H')
|
---|
1048 |
|
---|
1049 | if external:
|
---|
1050 | dns_masters = ['siteview.wirelessleiden.nl', 'ns1.vanderzwet.net']
|
---|
1051 | else:
|
---|
1052 | dns_masters = ['sunny.wleiden.net']
|
---|
1053 |
|
---|
1054 | details['master'] = dns_masters[0]
|
---|
1055 | details['ns_servers'] = '\n'.join(['\tNS\t%s.' % x for x in dns_masters])
|
---|
1056 |
|
---|
1057 | dns_header = '''
|
---|
1058 | $TTL 3h
|
---|
1059 | %(zone)s. SOA %(master)s. beheer.lijst.wirelessleiden.nl. ( %(serial)s 1d 12h 1w 3h )
|
---|
1060 | ; Serial, Refresh, Retry, Expire, Neg. cache TTL
|
---|
1061 |
|
---|
1062 | %(ns_servers)s
|
---|
1063 | \n'''
|
---|
1064 |
|
---|
1065 |
|
---|
1066 | if not os.path.isdir(output_dir):
|
---|
1067 | os.makedirs(output_dir)
|
---|
1068 | details['zone'] = 'wleiden.net'
|
---|
1069 | f = open(os.path.join(output_dir,"db." + details['zone']), "w")
|
---|
1070 | f.write(dns_header % details)
|
---|
1071 |
|
---|
1072 | for host,ip in wleiden_zone.iteritems():
|
---|
1073 | if valid_addr(ip):
|
---|
1074 | f.write("%s.wleiden.net. IN A %s \n" % (host.lower(), ip))
|
---|
1075 | for source,dest in wleiden_cname.iteritems():
|
---|
1076 | f.write("%s.wleiden.net. IN CNAME %s.wleiden.net.\n" % (source.lower(), dest.lower()))
|
---|
1077 | for source, dest in wleiden_raw.iteritems():
|
---|
1078 | f.write("%s.wleiden.net. %s\n" % (source, dest))
|
---|
1079 | f.close()
|
---|
1080 |
|
---|
1081 | # Create whole bunch of specific sub arpa zones. To keep it compliant
|
---|
1082 | for s in range(16,32):
|
---|
1083 | details['zone'] = '%i.172.in-addr.arpa' % s
|
---|
1084 | f = open(os.path.join(output_dir,"db." + details['zone']), "w")
|
---|
1085 | f.write(dns_header % details)
|
---|
1086 |
|
---|
1087 | #XXX: Not effient, fix to proper data structure and do checks at other
|
---|
1088 | # stages
|
---|
1089 | for host,ip in wleiden_zone.iteritems():
|
---|
1090 | if valid_addr(ip):
|
---|
1091 | if int(ip.split('.')[1]) == s:
|
---|
1092 | rev_ip = '.'.join(reversed(ip.split('.')))
|
---|
1093 | f.write("%s.in-addr.arpa. IN PTR %s.wleiden.net.\n" % (rev_ip.lower(), host.lower()))
|
---|
1094 | f.close()
|
---|
1095 |
|
---|
1096 |
|
---|
1097 | def usage():
|
---|
1098 | print """Usage: %(prog)s <argument>
|
---|
1099 | Argument:
|
---|
1100 | \tstandalone [port] = Run configurator webserver [8000]
|
---|
1101 | \tdns [outputdir] = Generate BIND compliant zone files in dns [./dns]
|
---|
1102 | \tfull-export = Generate yaml export script for heatmap.
|
---|
1103 | \tstatic [outputdir] = Generate all config files and store on disk
|
---|
1104 | \t with format ./<outputdir>/%%NODE%%/%%FILE%% [./static]
|
---|
1105 | \ttest <node> <file> = Receive output of CGI script.
|
---|
1106 | \tlist <status> <items> = List systems which have certain status
|
---|
1107 |
|
---|
1108 | Arguments:
|
---|
1109 | \t<node> = NodeName (example: HybridRick)
|
---|
1110 | \t<file> = %(files)s
|
---|
1111 | \t<status> = all|up|down|planned
|
---|
1112 | \t<items> = systems|nodes|proxies
|
---|
1113 |
|
---|
1114 | NOTE FOR DEVELOPERS; you can test your changes like this:
|
---|
1115 | BEFORE any changes in this code:
|
---|
1116 | $ ./gformat.py static /tmp/pre
|
---|
1117 | AFTER the changes:
|
---|
1118 | $ ./gformat.py static /tmp/post
|
---|
1119 | VIEW differences and VERIFY all are OK:
|
---|
1120 | $ diff -urI 'Generated' -r /tmp/pre /tmp/post
|
---|
1121 | """ % { 'prog' : sys.argv[0], 'files' : '|'.join(files) }
|
---|
1122 | exit(0)
|
---|
1123 |
|
---|
1124 |
|
---|
1125 | def is_text_request():
|
---|
1126 | """ Find out whether we are calling from the CLI or any text based CLI utility """
|
---|
1127 | try:
|
---|
1128 | return os.environ['HTTP_USER_AGENT'].split()[0] in ['curl', 'fetch', 'wget']
|
---|
1129 | except KeyError:
|
---|
1130 | return True
|
---|
1131 |
|
---|
1132 | def switchFormat(setting):
|
---|
1133 | if setting:
|
---|
1134 | return "YES"
|
---|
1135 | else:
|
---|
1136 | return "NO"
|
---|
1137 |
|
---|
1138 | def main():
|
---|
1139 | """Hard working sub"""
|
---|
1140 | # Allow easy hacking using the CLI
|
---|
1141 | if not os.environ.has_key('PATH_INFO'):
|
---|
1142 | if len(sys.argv) < 2:
|
---|
1143 | usage()
|
---|
1144 |
|
---|
1145 | if sys.argv[1] == "standalone":
|
---|
1146 | import SocketServer
|
---|
1147 | import CGIHTTPServer
|
---|
1148 | # Hop to the right working directory.
|
---|
1149 | os.chdir(os.path.dirname(__file__))
|
---|
1150 | try:
|
---|
1151 | PORT = int(sys.argv[2])
|
---|
1152 | except (IndexError,ValueError):
|
---|
1153 | PORT = 8000
|
---|
1154 |
|
---|
1155 | class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
|
---|
1156 | """ Serve this CGI from the root of the webserver """
|
---|
1157 | def is_cgi(self):
|
---|
1158 | if "favicon" in self.path:
|
---|
1159 | return False
|
---|
1160 |
|
---|
1161 | self.cgi_info = (os.path.basename(__file__), self.path)
|
---|
1162 | self.path = ''
|
---|
1163 | return True
|
---|
1164 | handler = MyCGIHTTPRequestHandler
|
---|
1165 | SocketServer.TCPServer.allow_reuse_address = True
|
---|
1166 | httpd = SocketServer.TCPServer(("", PORT), handler)
|
---|
1167 | httpd.server_name = 'localhost'
|
---|
1168 | httpd.server_port = PORT
|
---|
1169 |
|
---|
1170 | logger.info("serving at port %s", PORT)
|
---|
1171 | try:
|
---|
1172 | httpd.serve_forever()
|
---|
1173 | except KeyboardInterrupt:
|
---|
1174 | httpd.shutdown()
|
---|
1175 | logger.info("All done goodbye")
|
---|
1176 | elif sys.argv[1] == "test":
|
---|
1177 | os.environ['PATH_INFO'] = "/".join(sys.argv[2:])
|
---|
1178 | os.environ['SCRIPT_NAME'] = __file__
|
---|
1179 | process_cgi_request()
|
---|
1180 | elif sys.argv[1] == "static":
|
---|
1181 | items = dict()
|
---|
1182 | items['output_dir'] = sys.argv[2] if len(sys.argv) > 2 else "./static"
|
---|
1183 | for node in get_hostlist():
|
---|
1184 | items['node'] = node
|
---|
1185 | items['wdir'] = "%(output_dir)s/%(node)s" % items
|
---|
1186 | if not os.path.isdir(items['wdir']):
|
---|
1187 | os.makedirs(items['wdir'])
|
---|
1188 | datadump = get_yaml(node)
|
---|
1189 | for config in files:
|
---|
1190 | items['config'] = config
|
---|
1191 | logger.info("## Generating %(node)s %(config)s" % items)
|
---|
1192 | f = open("%(wdir)s/%(config)s" % items, "w")
|
---|
1193 | f.write(generate_config(node, config, datadump))
|
---|
1194 | f.close()
|
---|
1195 | elif sys.argv[1] == "wind-export":
|
---|
1196 | items = dict()
|
---|
1197 | for node in get_hostlist():
|
---|
1198 | datadump = get_yaml(node)
|
---|
1199 | sql = """INSERT IGNORE INTO nodes (name, name_ns, longitude, latitude)
|
---|
1200 | VALUES ('%(nodename)s', '%(nodename)s', %(latitude)s, %(longitude)s);""" % datadump;
|
---|
1201 | sql = """INSERT IGNORE INTO users_nodes (user_id, node_id, owner)
|
---|
1202 | VALUES (
|
---|
1203 | (SELECT id FROM users WHERE username = 'rvdzwet'),
|
---|
1204 | (SELECT id FROM nodes WHERE name = '%(nodename)s'),
|
---|
1205 | 'Y');""" % datadump
|
---|
1206 | #for config in files:
|
---|
1207 | # items['config'] = config
|
---|
1208 | # print "## Generating %(node)s %(config)s" % items
|
---|
1209 | # f = open("%(wdir)s/%(config)s" % items, "w")
|
---|
1210 | # f.write(generate_config(node, config, datadump))
|
---|
1211 | # f.close()
|
---|
1212 | for node in get_hostlist():
|
---|
1213 | datadump = get_yaml(node)
|
---|
1214 | for iface_key in sorted([elem for elem in datadump.keys() if elem.startswith('iface_')]):
|
---|
1215 | ifacedump = datadump[iface_key]
|
---|
1216 | if ifacedump.has_key('mode') and ifacedump['mode'] == 'ap-wds':
|
---|
1217 | ifacedump['nodename'] = datadump['nodename']
|
---|
1218 | if not ifacedump.has_key('channel') or not ifacedump['channel']:
|
---|
1219 | ifacedump['channel'] = 0
|
---|
1220 | sql = """INSERT INTO links (node_id, type, ssid, protocol, channel, status)
|
---|
1221 | VALUES ((SELECT id FROM nodes WHERE name = '%(nodename)s'), 'ap',
|
---|
1222 | '%(ssid)s', 'IEEE 802.11b', %(channel)s, 'active');""" % ifacedump
|
---|
1223 | elif sys.argv[1] == "full-export":
|
---|
1224 | hosts = {}
|
---|
1225 | for node in get_hostlist():
|
---|
1226 | datadump = get_yaml(node)
|
---|
1227 | hosts[datadump['nodename']] = datadump
|
---|
1228 | print yaml.dump(hosts)
|
---|
1229 |
|
---|
1230 | elif sys.argv[1] == "dns":
|
---|
1231 | make_dns(sys.argv[2] if len(sys.argv) > 2 else 'dns', 'external' in sys.argv)
|
---|
1232 | elif sys.argv[1] == "cleanup":
|
---|
1233 | # First generate all datadumps
|
---|
1234 | datadumps = dict()
|
---|
1235 | for host in get_hostlist():
|
---|
1236 | logger.info("# Processing: %s", host)
|
---|
1237 | # Set some boring default values
|
---|
1238 | datadump = { 'board' : 'UNKNOWN' }
|
---|
1239 | datadump.update(get_yaml(host))
|
---|
1240 | datadumps[datadump['autogen_realname']] = datadump
|
---|
1241 |
|
---|
1242 |
|
---|
1243 | for host,datadump in datadumps.iteritems():
|
---|
1244 | # Convert all yes and no to boolean values
|
---|
1245 | def fix_boolean(dump):
|
---|
1246 | for key in dump.keys():
|
---|
1247 | if type(dump[key]) == dict:
|
---|
1248 | dump[key] = fix_boolean(dump[key])
|
---|
1249 | elif str(dump[key]).lower() in ["yes", "true"]:
|
---|
1250 | dump[key] = True
|
---|
1251 | elif str(dump[key]).lower() in ["no", "false"]:
|
---|
1252 | # Compass richting no (Noord Oost) is valid input
|
---|
1253 | if key != "compass": dump[key] = False
|
---|
1254 | return dump
|
---|
1255 | datadump = fix_boolean(datadump)
|
---|
1256 |
|
---|
1257 | if datadump['rdnap_x'] and datadump['rdnap_y']:
|
---|
1258 | datadump['latitude'], datadump['longitude'] = rdnap.rd2etrs(datadump['rdnap_x'], datadump['rdnap_y'])
|
---|
1259 | elif datadump['latitude'] and datadump['longitude']:
|
---|
1260 | datadump['rdnap_x'], datadump['rdnap_y'] = rdnap.etrs2rd(datadump['latitude'], datadump['longitude'])
|
---|
1261 |
|
---|
1262 | if datadump['nodename'].startswith('Proxy'):
|
---|
1263 | datadump['nodename'] = datadump['nodename'].lower()
|
---|
1264 |
|
---|
1265 | for iface_key in datadump['autogen_iface_keys']:
|
---|
1266 | # Wireless Leiden SSID have an consistent lowercase/uppercase
|
---|
1267 | if datadump[iface_key].has_key('ssid'):
|
---|
1268 | ssid = datadump[iface_key]['ssid']
|
---|
1269 | prefix = 'ap-WirelessLeiden-'
|
---|
1270 | if ssid.lower().startswith(prefix.lower()):
|
---|
1271 | datadump[iface_key]['ssid'] = prefix + ssid[len(prefix)].upper() + ssid[len(prefix) + 1:]
|
---|
1272 | if datadump[iface_key].has_key('ns_ip') and not datadump[iface_key].has_key('mode'):
|
---|
1273 | datadump[iface_key]['mode'] = 'autogen-FIXME'
|
---|
1274 | if not datadump[iface_key].has_key('desc'):
|
---|
1275 | datadump[iface_key]['desc'] = 'autogen-FIXME'
|
---|
1276 | store_yaml(datadump)
|
---|
1277 | elif sys.argv[1] == "list":
|
---|
1278 | use_fqdn = False
|
---|
1279 | if len(sys.argv) < 4 or not sys.argv[2] in ["up", "down", "planned", "all"]:
|
---|
1280 | usage()
|
---|
1281 | if sys.argv[3] == "nodes":
|
---|
1282 | systems = get_nodelist()
|
---|
1283 | elif sys.argv[3] == "proxies":
|
---|
1284 | systems = get_proxylist()
|
---|
1285 | elif sys.argv[3] == "systems":
|
---|
1286 | systems = get_hostlist()
|
---|
1287 | else:
|
---|
1288 | usage()
|
---|
1289 | if len(sys.argv) > 4:
|
---|
1290 | if sys.argv[4] == "fqdn":
|
---|
1291 | use_fqdn = True
|
---|
1292 | else:
|
---|
1293 | usage()
|
---|
1294 |
|
---|
1295 | for system in systems:
|
---|
1296 | datadump = get_yaml(system)
|
---|
1297 |
|
---|
1298 | output = datadump['autogen_fqdn'] if use_fqdn else system
|
---|
1299 | if sys.argv[2] == "all":
|
---|
1300 | print output
|
---|
1301 | elif datadump['status'] == sys.argv[2]:
|
---|
1302 | print output
|
---|
1303 | elif sys.argv[1] == "create":
|
---|
1304 | if sys.argv[2] == "network.kml":
|
---|
1305 | print make_network_kml.make_graph()
|
---|
1306 | else:
|
---|
1307 | usage()
|
---|
1308 | usage()
|
---|
1309 | else:
|
---|
1310 | # Do not enable debugging for config requests as it highly clutters the output
|
---|
1311 | if not is_text_request():
|
---|
1312 | cgitb.enable()
|
---|
1313 | process_cgi_request()
|
---|
1314 |
|
---|
1315 |
|
---|
1316 | if __name__ == "__main__":
|
---|
1317 | main()
|
---|