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 10649 2012-05-02 21:45:11Z 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.hybrid.conf"
|
---|
546 | pf_flags="-D ext_if=$externalif -D ext_if_net=$externalif:network -D masterip=$masterip"
|
---|
547 | pf_flags="$pf_flags -D publicnat=0"
|
---|
548 | lvrouted_flags="$lvrouted_flags -z `make_list "$list_ileiden_proxies" ","`"
|
---|
549 | named_setfib="1"
|
---|
550 | tinyproxy_setfib="1"
|
---|
551 | dnsmasq_setfib="1"
|
---|
552 | {% else %}
|
---|
553 | pf_rules="/etc/pf.node.conf"
|
---|
554 | pf_flags=""
|
---|
555 | {% endif %}
|
---|
556 |
|
---|
557 | {% if service_proxy_normal %}
|
---|
558 | tinyproxy_enable="yes"
|
---|
559 | {% else %}
|
---|
560 | pen_wrapper_enable="yes"
|
---|
561 | {% endif %}
|
---|
562 |
|
---|
563 | {% if service_accesspoint %}
|
---|
564 | pf_flags="$pf_flags -D captive_portal_interfaces=$captive_portal_interfaces"
|
---|
565 | {% endif %}
|
---|
566 |
|
---|
567 | {% if board == "ALIX2" %}
|
---|
568 | #
|
---|
569 | # ''Fat'' configuration, board has 256MB RAM
|
---|
570 | #
|
---|
571 | dnsmasq_enable="NO"
|
---|
572 | named_enable="YES"
|
---|
573 | dhcpd_enable="YES"
|
---|
574 | {% endif -%}
|
---|
575 |
|
---|
576 | {% if service_proxy_ileiden and gateway %}
|
---|
577 | defaultrouter="{{ gateway }}"
|
---|
578 | {% endif %}
|
---|
579 | {% elif nodetype == "CNode" %}
|
---|
580 | #
|
---|
581 | # NODE iLeiden Configuration
|
---|
582 | #
|
---|
583 |
|
---|
584 | # iLeiden Proxies {{ autogen_ileiden_proxies_names }}
|
---|
585 | list_ileiden_proxies="{{ autogen_ileiden_proxies_ips }}"
|
---|
586 | # normal Proxies {{ autogen_normal_proxies_names }}
|
---|
587 | list_normal_proxies="{{ autogen_normal_proxies_ips }}"
|
---|
588 |
|
---|
589 | captive_portal_interfaces="{{ autogen_dhcp_interfaces }}"
|
---|
590 |
|
---|
591 | {% if tproxy -%}
|
---|
592 | tproxy_enable='YES'
|
---|
593 | tproxy_range='{{ tproxy }}'
|
---|
594 | {% else -%}
|
---|
595 | tproxy_enable='NO'
|
---|
596 | {% endif -%}
|
---|
597 |
|
---|
598 | lvrouted_flags="-u -s s00p3rs3kr3t -m 28 -z $list_ileiden_proxies"
|
---|
599 | {% endif %}
|
---|
600 |
|
---|
601 | #
|
---|
602 | # Interface definitions
|
---|
603 | #\n
|
---|
604 | """)
|
---|
605 |
|
---|
606 | # lo0 configuration:
|
---|
607 | # - 172.32.255.1/32 is the proxy.wleiden.net deflector
|
---|
608 | # - masterip is special as it needs to be assigned to at
|
---|
609 | # least one interface, so if not used assign to lo0
|
---|
610 | addrs_list = { 'lo0' : [("127.0.0.1/8", "LocalHost"), ("172.31.255.1/32","Proxy IP")] }
|
---|
611 | iface_map = {'lo0' : 'lo0'}
|
---|
612 | dhclient_if = {'lo0' : False}
|
---|
613 |
|
---|
614 | masterip_used = False
|
---|
615 | for iface_key in datadump['autogen_iface_keys']:
|
---|
616 | if datadump[iface_key]['ip'].startswith(datadump['masterip']):
|
---|
617 | masterip_used = True
|
---|
618 | break
|
---|
619 | if not masterip_used:
|
---|
620 | addrs_list['lo0'].append((datadump['masterip'] + "/32", 'Master IP Not used in interface'))
|
---|
621 |
|
---|
622 | for iface_key in datadump['autogen_iface_keys']:
|
---|
623 | ifacedump = datadump[iface_key]
|
---|
624 | ifname = ifacedump['autogen_ifname']
|
---|
625 |
|
---|
626 | # Flag dhclient is possible
|
---|
627 | dhclient_if[ifname] = ifacedump.has_key('dhcpclient') and ifacedump['dhcpclient']
|
---|
628 |
|
---|
629 | # Add interface IP to list
|
---|
630 | item = (ifacedump['ip'], ifacedump['desc'])
|
---|
631 | if addrs_list.has_key(ifname):
|
---|
632 | addrs_list[ifname].append(item)
|
---|
633 | else:
|
---|
634 | addrs_list[ifname] = [item]
|
---|
635 |
|
---|
636 | # Alias only needs IP assignment for now, this might change if we
|
---|
637 | # are going to use virtual accesspoints
|
---|
638 | if "alias" in iface_key:
|
---|
639 | continue
|
---|
640 |
|
---|
641 | # XXX: Might want to deduct type directly from interface name
|
---|
642 | if ifacedump['type'] in ['11a', '11b', '11g', 'wireless']:
|
---|
643 | # Default to station (client) mode
|
---|
644 | ifacedump['wlanmode'] = "sta"
|
---|
645 | if ifacedump['mode'] in ['master', 'master-wds', 'ap', 'ap-wds']:
|
---|
646 | ifacedump['wlanmode'] = "ap"
|
---|
647 | # Default to 802.11b mode
|
---|
648 | ifacedump['mode'] = '11b'
|
---|
649 | if ifacedump['type'] in ['11a', '11b' '11g']:
|
---|
650 | ifacedump['mode'] = ifacedump['type']
|
---|
651 |
|
---|
652 | if not ifacedump.has_key('channel'):
|
---|
653 | if ifacedump['type'] == '11a':
|
---|
654 | ifacedump['channel'] = 36
|
---|
655 | else:
|
---|
656 | ifacedump['channel'] = 1
|
---|
657 |
|
---|
658 | # Allow special hacks at the back like wds and stuff
|
---|
659 | if not ifacedump.has_key('extra'):
|
---|
660 | ifacedump['extra'] = 'regdomain ETSI country NL'
|
---|
661 |
|
---|
662 | output += "wlans_%(interface)s='%(autogen_ifname)s'\n" % ifacedump
|
---|
663 | output += ("create_args_%(autogen_ifname)s='wlanmode %(wlanmode)s mode " +\
|
---|
664 | "%(mode)s ssid %(ssid)s %(extra)s channel %(channel)s'\n") % ifacedump
|
---|
665 |
|
---|
666 | elif ifacedump['type'] in ['ethernet', 'eth']:
|
---|
667 | # No special config needed besides IP
|
---|
668 | pass
|
---|
669 | else:
|
---|
670 | assert False, "Unknown type " + ifacedump['type']
|
---|
671 |
|
---|
672 | # Print IP address which needs to be assigned over here
|
---|
673 | output += "\n"
|
---|
674 | for iface,addrs in sorted(addrs_list.iteritems()):
|
---|
675 | for addr, comment in sorted(addrs,key=lambda x: parseaddr(x[0].split('/')[0])):
|
---|
676 | output += "# %s || %s || %s\n" % (iface, addr, comment)
|
---|
677 |
|
---|
678 | # Write DHCLIENT entry
|
---|
679 | if dhclient_if[iface]:
|
---|
680 | output += "ifconfig_%s='SYNCDHCP'\n\n" % (iface)
|
---|
681 | else:
|
---|
682 | output += "ipv4_addrs_%s='%s'\n\n" % (iface, " ".join([x[0] for x in addrs]))
|
---|
683 |
|
---|
684 | return output
|
---|
685 |
|
---|
686 |
|
---|
687 |
|
---|
688 |
|
---|
689 | def get_all_configs():
|
---|
690 | """ Get dict with key 'host' with all configs present """
|
---|
691 | configs = dict()
|
---|
692 | for host in get_hostlist():
|
---|
693 | datadump = get_yaml(host)
|
---|
694 | configs[host] = datadump
|
---|
695 | return configs
|
---|
696 |
|
---|
697 |
|
---|
698 | def get_interface_keys(config):
|
---|
699 | """ Quick hack to get all interface keys, later stage convert this to a iterator """
|
---|
700 | return sorted([elem for elem in config.keys() if (elem.startswith('iface_') and not "lo0" in elem)])
|
---|
701 |
|
---|
702 |
|
---|
703 | def get_used_ips(configs):
|
---|
704 | """ Return array of all IPs used in config files"""
|
---|
705 | ip_list = []
|
---|
706 | for config in configs:
|
---|
707 | ip_list.append(config['masterip'])
|
---|
708 | for iface_key in get_interface_keys(config):
|
---|
709 | l = config[iface_key]['ip']
|
---|
710 | addr, mask = l.split('/')
|
---|
711 | # Special case do not process
|
---|
712 | if valid_addr(addr):
|
---|
713 | ip_list.append(addr)
|
---|
714 | else:
|
---|
715 | logger.error("## IP '%s' in '%s' not valid" % (addr, config['nodename']))
|
---|
716 | return sorted(ip_list)
|
---|
717 |
|
---|
718 |
|
---|
719 |
|
---|
720 | def generate_resolv_conf(datadump):
|
---|
721 | """ Generate configuration file '/etc/resolv.conf' """
|
---|
722 | # XXX: This should properly going to be an datastructure soon
|
---|
723 | datadump['autogen_header'] = generate_header("#")
|
---|
724 | datadump['autogen_edge_nameservers'] = ''
|
---|
725 | for host in get_proxylist():
|
---|
726 | hostdump = get_yaml(host)
|
---|
727 | datadump['autogen_edge_nameservers'] += "nameserver %(masterip)-15s # %(autogen_realname)s\n" % hostdump
|
---|
728 | for host in get_hybridlist():
|
---|
729 | hostdump = get_yaml(host)
|
---|
730 | if hostdump['service_proxy_ileiden'] or hostdump['service_proxy_normal']:
|
---|
731 | datadump['autogen_edge_nameservers'] += "nameserver %(masterip)-15s # %(autogen_realname)s\n" % hostdump
|
---|
732 |
|
---|
733 | return Template("""\
|
---|
734 | {{ autogen_header }}
|
---|
735 | search wleiden.net
|
---|
736 |
|
---|
737 | # Try local (cache) first
|
---|
738 | nameserver 127.0.0.1
|
---|
739 |
|
---|
740 | {% if service_proxy_normal or service_proxy_ileiden or nodetype == 'Proxy' -%}
|
---|
741 | nameserver 8.8.8.8 # Google Public NameServer
|
---|
742 | nameserver 8.8.4.4 # Google Public NameServer
|
---|
743 | {% else -%}
|
---|
744 | # START DYNAMIC LIST - updated by /tools/nameserver-shuffle
|
---|
745 | {{ autogen_edge_nameservers }}
|
---|
746 | {% endif -%}
|
---|
747 | """).render(datadump)
|
---|
748 |
|
---|
749 |
|
---|
750 |
|
---|
751 | def generate_motd(datadump):
|
---|
752 | """ Generate configuration file '/etc/motd' """
|
---|
753 | output = Template("""\
|
---|
754 | FreeBSD run ``service motd onestart'' to make me look normal
|
---|
755 |
|
---|
756 | WWW: {{ autogen_fqdn }} - http://www.wirelessleiden.nl
|
---|
757 | Loc: {{ location }}
|
---|
758 |
|
---|
759 | Services:
|
---|
760 | {% if board == "ALIX2" -%}
|
---|
761 | - Core Node
|
---|
762 | {% else -%}
|
---|
763 | - Hulp Node
|
---|
764 | {% endif -%}
|
---|
765 | {% if service_proxy_normal -%}
|
---|
766 | - Normal Proxy
|
---|
767 | {% endif -%}
|
---|
768 | {% if service_proxy_ileiden -%}
|
---|
769 | - iLeiden Proxy
|
---|
770 | {% endif %}
|
---|
771 | Interlinks:\n
|
---|
772 | """).render(datadump)
|
---|
773 |
|
---|
774 | # XXX: This is a hacky way to get the required data
|
---|
775 | for line in generate_rc_conf_local(datadump).split('\n'):
|
---|
776 | if '||' in line and not line[1:].split()[0] in ['lo0', 'ath0'] :
|
---|
777 | output += " - %s \n" % line[1:]
|
---|
778 | output += """\
|
---|
779 | Attached bridges:
|
---|
780 | """
|
---|
781 | for iface_key in datadump['autogen_iface_keys']:
|
---|
782 | ifacedump = datadump[iface_key]
|
---|
783 | if ifacedump.has_key('ns_ip'):
|
---|
784 | output += " - %(interface)s || %(mode)s || %(ns_ip)s\n" % ifacedump
|
---|
785 |
|
---|
786 | return output
|
---|
787 |
|
---|
788 |
|
---|
789 | def format_yaml_value(value):
|
---|
790 | """ Get yaml value in right syntax for outputting """
|
---|
791 | if isinstance(value,str):
|
---|
792 | output = '"%s"' % value
|
---|
793 | else:
|
---|
794 | output = value
|
---|
795 | return output
|
---|
796 |
|
---|
797 |
|
---|
798 |
|
---|
799 | def format_wleiden_yaml(datadump):
|
---|
800 | """ Special formatting to ensure it is editable"""
|
---|
801 | output = "# Genesis config yaml style\n"
|
---|
802 | output += "# vim:ts=2:et:sw=2:ai\n"
|
---|
803 | output += "#\n"
|
---|
804 | iface_keys = [elem for elem in datadump.keys() if elem.startswith('iface_')]
|
---|
805 | for key in sorted(set(datadump.keys()) - set(iface_keys)):
|
---|
806 | output += "%-10s: %s\n" % (key, format_yaml_value(datadump[key]))
|
---|
807 |
|
---|
808 | output += "\n\n"
|
---|
809 |
|
---|
810 | key_order = [ 'comment', 'interface', 'ip', 'desc', 'sdesc', 'mode', 'type',
|
---|
811 | 'extra_type', 'channel', 'ssid', 'dhcp' ]
|
---|
812 |
|
---|
813 | for iface_key in sorted(iface_keys):
|
---|
814 | output += "%s:\n" % iface_key
|
---|
815 | for key in key_order + list(sorted(set(datadump[iface_key].keys()) - set(key_order))):
|
---|
816 | if datadump[iface_key].has_key(key):
|
---|
817 | output += " %-11s: %s\n" % (key, format_yaml_value(datadump[iface_key][key]))
|
---|
818 | output += "\n\n"
|
---|
819 |
|
---|
820 | return output
|
---|
821 |
|
---|
822 |
|
---|
823 |
|
---|
824 | def generate_wleiden_yaml(datadump, header=True):
|
---|
825 | """ Generate (petty) version of wleiden.yaml"""
|
---|
826 | for key in datadump.keys():
|
---|
827 | if key.startswith('autogen_'):
|
---|
828 | del datadump[key]
|
---|
829 | # Interface autogen cleanups
|
---|
830 | elif type(datadump[key]) == dict:
|
---|
831 | for key2 in datadump[key].keys():
|
---|
832 | if key2.startswith('autogen_'):
|
---|
833 | del datadump[key][key2]
|
---|
834 |
|
---|
835 | output = generate_header("#") if header else ''
|
---|
836 | output += format_wleiden_yaml(datadump)
|
---|
837 | return output
|
---|
838 |
|
---|
839 |
|
---|
840 | def generate_yaml(datadump):
|
---|
841 | return generate_config(datadump['nodename'], "wleiden.yaml", datadump)
|
---|
842 |
|
---|
843 |
|
---|
844 |
|
---|
845 | def generate_config(node, config, datadump=None):
|
---|
846 | """ Print configuration file 'config' of 'node' """
|
---|
847 | output = ""
|
---|
848 | try:
|
---|
849 | # Load config file
|
---|
850 | if datadump == None:
|
---|
851 | datadump = get_yaml(node)
|
---|
852 |
|
---|
853 | if config == 'wleiden.yaml':
|
---|
854 | output += generate_wleiden_yaml(datadump)
|
---|
855 | elif config == 'authorized_keys':
|
---|
856 | f = open(os.path.join(NODE_DIR,"global_keys"), 'r')
|
---|
857 | output += f.read()
|
---|
858 | f.close()
|
---|
859 | elif config == 'dnsmasq.conf':
|
---|
860 | output += generate_dnsmasq_conf(datadump)
|
---|
861 | elif config == 'dhcpd.conf':
|
---|
862 | output += generate_dhcpd_conf(datadump)
|
---|
863 | elif config == 'rc.conf.local':
|
---|
864 | output += generate_rc_conf_local(datadump)
|
---|
865 | elif config == 'resolv.conf':
|
---|
866 | output += generate_resolv_conf(datadump)
|
---|
867 | elif config == 'motd':
|
---|
868 | output += generate_motd(datadump)
|
---|
869 | else:
|
---|
870 | assert False, "Config not found!"
|
---|
871 | except IOError, e:
|
---|
872 | output += "[ERROR] Config file not found"
|
---|
873 | return output
|
---|
874 |
|
---|
875 |
|
---|
876 |
|
---|
877 | def process_cgi_request():
|
---|
878 | """ When calling from CGI """
|
---|
879 | # Update repository if requested
|
---|
880 | form = cgi.FieldStorage()
|
---|
881 | if form.getvalue("action") == "update":
|
---|
882 | print "Refresh: 5; url=."
|
---|
883 | print "Content-type:text/plain\r\n\r\n",
|
---|
884 | print "[INFO] Updating subverion, please wait..."
|
---|
885 | print subprocess.Popen(['svn', 'cleanup', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0],
|
---|
886 | print subprocess.Popen(['svn', 'up', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0],
|
---|
887 | print "[INFO] All done, redirecting in 5 seconds"
|
---|
888 | sys.exit(0)
|
---|
889 |
|
---|
890 |
|
---|
891 | base_uri = os.environ['PATH_INFO']
|
---|
892 | uri = base_uri.strip('/').split('/')
|
---|
893 |
|
---|
894 | output = ""
|
---|
895 | if base_uri.endswith('/create/network.kml'):
|
---|
896 | output += "Content-type:application/vnd.google-earth.kml+xml\r\n\r\n"
|
---|
897 | output += make_network_kml.make_graph()
|
---|
898 | elif not uri[0]:
|
---|
899 | if is_text_request():
|
---|
900 | output += "Content-type:text/plain\r\n\r\n"
|
---|
901 | output += '\n'.join(get_hostlist())
|
---|
902 | else:
|
---|
903 | output += "Content-type:text/html\r\n\r\n"
|
---|
904 | output += generate_title(get_hostlist())
|
---|
905 | elif len(uri) == 1:
|
---|
906 | if is_text_request():
|
---|
907 | output += "Content-type:text/plain\r\n\r\n"
|
---|
908 | output += generate_node(uri[0])
|
---|
909 | else:
|
---|
910 | output += "Content-type:text/html\r\n\r\n"
|
---|
911 | output += generate_node_overview(uri[0])
|
---|
912 | elif len(uri) == 2:
|
---|
913 | output += "Content-type:text/plain\r\n\r\n"
|
---|
914 | output += generate_config(uri[0], uri[1])
|
---|
915 | else:
|
---|
916 | assert False, "Invalid option"
|
---|
917 | print output
|
---|
918 |
|
---|
919 | def get_realname(datadump):
|
---|
920 | # Proxy naming convention is special, as the proxy name is also included in
|
---|
921 | # the nodename, when it comes to the numbered proxies.
|
---|
922 | if datadump['nodetype'] == 'Proxy':
|
---|
923 | realname = datadump['nodetype'] + datadump['nodename'].replace('proxy','')
|
---|
924 | else:
|
---|
925 | # By default the full name is listed and also a shortname CNAME for easy use.
|
---|
926 | realname = datadump['nodetype'] + datadump['nodename']
|
---|
927 | return(realname)
|
---|
928 |
|
---|
929 |
|
---|
930 |
|
---|
931 | def make_dns(output_dir = 'dns', external = False):
|
---|
932 | items = dict()
|
---|
933 |
|
---|
934 | # hostname is key, IP is value
|
---|
935 | wleiden_zone = defaultdict(list)
|
---|
936 | wleiden_cname = dict()
|
---|
937 |
|
---|
938 | pool = dict()
|
---|
939 | for node in get_hostlist():
|
---|
940 | datadump = get_yaml(node)
|
---|
941 |
|
---|
942 | # Proxy naming convention is special
|
---|
943 | fqdn = datadump['autogen_realname']
|
---|
944 | if datadump['nodetype'] in ['CNode', 'Hybrid']:
|
---|
945 | wleiden_cname[datadump['nodename']] = fqdn
|
---|
946 |
|
---|
947 | wleiden_zone[fqdn].append(datadump['masterip'])
|
---|
948 |
|
---|
949 | # Hacking to get proper DHCP IPs and hostnames
|
---|
950 | for iface_key in get_interface_keys(datadump):
|
---|
951 | iface_name = datadump[iface_key]['interface'].replace(':',"-alias-")
|
---|
952 | (ip, cidr) = datadump[iface_key]['ip'].split('/')
|
---|
953 | try:
|
---|
954 | (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
|
---|
955 | datadump[iface_key]['netmask'] = cidr2netmask(cidr)
|
---|
956 | dhcp_part = ".".join(ip.split('.')[0:3])
|
---|
957 | if ip != datadump['masterip']:
|
---|
958 | wleiden_zone["dhcp-gateway-%s.%s" % (iface_name, fqdn)].append(ip)
|
---|
959 | for i in range(int(dhcp_start), int(dhcp_stop) + 1):
|
---|
960 | wleiden_zone["dhcp-%s-%s.%s" % (i, iface_name, fqdn)].append("%s.%s" % (dhcp_part, i))
|
---|
961 | except (AttributeError, ValueError):
|
---|
962 | # First push it into a pool, to indentify the counter-part later on
|
---|
963 | addr = parseaddr(ip)
|
---|
964 | cidr = int(cidr)
|
---|
965 | addr = addr & ~((1 << (32 - cidr)) - 1)
|
---|
966 | if pool.has_key(addr):
|
---|
967 | pool[addr] += [(iface_name, fqdn, ip)]
|
---|
968 | else:
|
---|
969 | pool[addr] = [(iface_name, fqdn, ip)]
|
---|
970 | continue
|
---|
971 |
|
---|
972 |
|
---|
973 | def pool_to_name(node, pool_members):
|
---|
974 | """Convert the joined name to a usable pool name"""
|
---|
975 |
|
---|
976 | # Get rid of the own entry
|
---|
977 | pool_members = list(set(pool_members) - set([fqdn]))
|
---|
978 |
|
---|
979 | target = oldname = ''
|
---|
980 | for node in sorted(pool_members):
|
---|
981 | (name, number) = re.match('^([A-Za-z]+)([0-9]*)$',node).group(1,2)
|
---|
982 | target += "-" + number if name == oldname else "-" + node if target else node
|
---|
983 | oldname = name
|
---|
984 |
|
---|
985 | return target
|
---|
986 |
|
---|
987 |
|
---|
988 | # WL uses an /29 to configure an interface. IP's are ordered like this:
|
---|
989 | # MasterA (.1) -- DeviceA (.2) <<>> DeviceB (.3) --- SlaveB (.4)
|
---|
990 |
|
---|
991 | sn = lambda x: re.sub(r'(?i)^cnode','',x)
|
---|
992 |
|
---|
993 | # Automatic naming convention of interlinks namely 2 + remote.lower()
|
---|
994 | for (key,value) in pool.iteritems():
|
---|
995 | # Make sure they are sorted from low-ip to high-ip
|
---|
996 | value = sorted(value, key=lambda x: parseaddr(x[2]))
|
---|
997 |
|
---|
998 | if len(value) == 1:
|
---|
999 | (iface_name, fqdn, ip) = value[0]
|
---|
1000 | wleiden_zone["2unused-%s.%s" % (iface_name, fqdn)].append(ip)
|
---|
1001 |
|
---|
1002 | # Device DNS names
|
---|
1003 | if 'cnode' in fqdn.lower():
|
---|
1004 | wleiden_zone["d-at-%s.%s" % (iface_name, fqdn)].append(showaddr(parseaddr(ip) + 1))
|
---|
1005 | wleiden_cname["d-at-%s.%s" % (iface_name,sn(fqdn))] = "d-at-%s.%s" % (iface_name, fqdn)
|
---|
1006 |
|
---|
1007 | elif len(value) == 2:
|
---|
1008 | (a_iface_name, a_fqdn, a_ip) = value[0]
|
---|
1009 | (b_iface_name, b_fqdn, b_ip) = value[1]
|
---|
1010 | wleiden_zone["2%s.%s" % (b_fqdn,a_fqdn)].append(a_ip)
|
---|
1011 | wleiden_zone["2%s.%s" % (a_fqdn,b_fqdn)].append(b_ip)
|
---|
1012 |
|
---|
1013 | # Device DNS names
|
---|
1014 | if 'cnode' in a_fqdn.lower() and 'cnode' in b_fqdn.lower():
|
---|
1015 | wleiden_zone["d-at-%s.%s" % (a_iface_name, a_fqdn)].append(showaddr(parseaddr(a_ip) + 1))
|
---|
1016 | wleiden_zone["d-at-%s.%s" % (b_iface_name, b_fqdn)].append(showaddr(parseaddr(b_ip) - 1))
|
---|
1017 | wleiden_cname["d-at-%s.%s" % (a_iface_name,sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
|
---|
1018 | wleiden_cname["d-at-%s.%s" % (b_iface_name,sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
|
---|
1019 | wleiden_cname["d2%s.%s" % (sn(b_fqdn),sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
|
---|
1020 | wleiden_cname["d2%s.%s" % (sn(a_fqdn),sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
|
---|
1021 |
|
---|
1022 | else:
|
---|
1023 | pool_members = [k[1] for k in value]
|
---|
1024 | for item in value:
|
---|
1025 | (iface_name, fqdn, ip) = item
|
---|
1026 | pool_name = "2pool-" + showaddr(key).replace('.','-') + "-" + pool_to_name(fqdn,pool_members)
|
---|
1027 | wleiden_zone["%s.%s" % (pool_name, fqdn)].append(ip)
|
---|
1028 |
|
---|
1029 | # Include static DNS entries
|
---|
1030 | # XXX: Should they override the autogenerated results?
|
---|
1031 | # XXX: Convert input to yaml more useable.
|
---|
1032 | # Format:
|
---|
1033 | ##; this is a comment
|
---|
1034 | ## roomburgh=CNodeRoomburgh1
|
---|
1035 | ## apkerk1.CNodeVosko=172.17.176.8 ;this as well
|
---|
1036 | dns_list = yaml.load(open(os.path.join(NODE_DIR,'../dns/staticDNS.yaml'),'r'))
|
---|
1037 |
|
---|
1038 | # Hack to allow special entries, for development
|
---|
1039 | wleiden_raw = {}
|
---|
1040 |
|
---|
1041 | for line in dns_list:
|
---|
1042 | k, items = line.items()[0]
|
---|
1043 | items = [items] if type(items) == str else items
|
---|
1044 | for item in items:
|
---|
1045 | if item.startswith('IN '):
|
---|
1046 | wleiden_raw[k] = item
|
---|
1047 | elif valid_addr(item):
|
---|
1048 | wleiden_zone[k].append(item)
|
---|
1049 | else:
|
---|
1050 | wleiden_cname[k] = item
|
---|
1051 |
|
---|
1052 | details = dict()
|
---|
1053 | # 24 updates a day allowed
|
---|
1054 | details['serial'] = time.strftime('%Y%m%d%H')
|
---|
1055 |
|
---|
1056 | if external:
|
---|
1057 | dns_masters = ['siteview.wirelessleiden.nl', 'ns1.vanderzwet.net']
|
---|
1058 | else:
|
---|
1059 | dns_masters = ['sunny.wleiden.net']
|
---|
1060 |
|
---|
1061 | details['master'] = dns_masters[0]
|
---|
1062 | details['ns_servers'] = '\n'.join(['\tNS\t%s.' % x for x in dns_masters])
|
---|
1063 |
|
---|
1064 | dns_header = '''
|
---|
1065 | $TTL 3h
|
---|
1066 | %(zone)s. SOA %(master)s. beheer.lijst.wirelessleiden.nl. ( %(serial)s 1d 12h 1w 3h )
|
---|
1067 | ; Serial, Refresh, Retry, Expire, Neg. cache TTL
|
---|
1068 |
|
---|
1069 | %(ns_servers)s
|
---|
1070 | \n'''
|
---|
1071 |
|
---|
1072 |
|
---|
1073 | if not os.path.isdir(output_dir):
|
---|
1074 | os.makedirs(output_dir)
|
---|
1075 | details['zone'] = 'wleiden.net'
|
---|
1076 | f = open(os.path.join(output_dir,"db." + details['zone']), "w")
|
---|
1077 | f.write(dns_header % details)
|
---|
1078 |
|
---|
1079 | for host,ips in wleiden_zone.iteritems():
|
---|
1080 | for ip in ips:
|
---|
1081 | if valid_addr(ip):
|
---|
1082 | f.write("%s.wleiden.net. IN A %s \n" % (host.lower(), ip))
|
---|
1083 | for source,dest in wleiden_cname.iteritems():
|
---|
1084 | f.write("%s.wleiden.net. IN CNAME %s.wleiden.net.\n" % (source.lower(), dest.lower()))
|
---|
1085 | for source, dest in wleiden_raw.iteritems():
|
---|
1086 | f.write("%s.wleiden.net. %s\n" % (source, dest))
|
---|
1087 | f.close()
|
---|
1088 |
|
---|
1089 | # Create whole bunch of specific sub arpa zones. To keep it compliant
|
---|
1090 | for s in range(16,32):
|
---|
1091 | details['zone'] = '%i.172.in-addr.arpa' % s
|
---|
1092 | f = open(os.path.join(output_dir,"db." + details['zone']), "w")
|
---|
1093 | f.write(dns_header % details)
|
---|
1094 |
|
---|
1095 | #XXX: Not effient, fix to proper data structure and do checks at other
|
---|
1096 | # stages
|
---|
1097 | for host,ips in wleiden_zone.iteritems():
|
---|
1098 | for ip in ips:
|
---|
1099 | if valid_addr(ip):
|
---|
1100 | if int(ip.split('.')[1]) == s:
|
---|
1101 | rev_ip = '.'.join(reversed(ip.split('.')))
|
---|
1102 | f.write("%s.in-addr.arpa. IN PTR %s.wleiden.net.\n" % (rev_ip.lower(), host.lower()))
|
---|
1103 | f.close()
|
---|
1104 |
|
---|
1105 |
|
---|
1106 | def usage():
|
---|
1107 | print """Usage: %(prog)s <argument>
|
---|
1108 | Argument:
|
---|
1109 | \tstandalone [port] = Run configurator webserver [8000]
|
---|
1110 | \tdns [outputdir] = Generate BIND compliant zone files in dns [./dns]
|
---|
1111 | \tfull-export = Generate yaml export script for heatmap.
|
---|
1112 | \tstatic [outputdir] = Generate all config files and store on disk
|
---|
1113 | \t with format ./<outputdir>/%%NODE%%/%%FILE%% [./static]
|
---|
1114 | \ttest <node> <file> = Receive output of CGI script.
|
---|
1115 | \tlist <status> <items> = List systems which have certain status
|
---|
1116 |
|
---|
1117 | Arguments:
|
---|
1118 | \t<node> = NodeName (example: HybridRick)
|
---|
1119 | \t<file> = %(files)s
|
---|
1120 | \t<status> = all|up|down|planned
|
---|
1121 | \t<items> = systems|nodes|proxies
|
---|
1122 |
|
---|
1123 | NOTE FOR DEVELOPERS; you can test your changes like this:
|
---|
1124 | BEFORE any changes in this code:
|
---|
1125 | $ ./gformat.py static /tmp/pre
|
---|
1126 | AFTER the changes:
|
---|
1127 | $ ./gformat.py static /tmp/post
|
---|
1128 | VIEW differences and VERIFY all are OK:
|
---|
1129 | $ diff -urI 'Generated' -r /tmp/pre /tmp/post
|
---|
1130 | """ % { 'prog' : sys.argv[0], 'files' : '|'.join(files) }
|
---|
1131 | exit(0)
|
---|
1132 |
|
---|
1133 |
|
---|
1134 | def is_text_request():
|
---|
1135 | """ Find out whether we are calling from the CLI or any text based CLI utility """
|
---|
1136 | try:
|
---|
1137 | return os.environ['HTTP_USER_AGENT'].split()[0] in ['curl', 'fetch', 'wget']
|
---|
1138 | except KeyError:
|
---|
1139 | return True
|
---|
1140 |
|
---|
1141 | def switchFormat(setting):
|
---|
1142 | if setting:
|
---|
1143 | return "YES"
|
---|
1144 | else:
|
---|
1145 | return "NO"
|
---|
1146 |
|
---|
1147 | def main():
|
---|
1148 | """Hard working sub"""
|
---|
1149 | # Allow easy hacking using the CLI
|
---|
1150 | if not os.environ.has_key('PATH_INFO'):
|
---|
1151 | if len(sys.argv) < 2:
|
---|
1152 | usage()
|
---|
1153 |
|
---|
1154 | if sys.argv[1] == "standalone":
|
---|
1155 | import SocketServer
|
---|
1156 | import CGIHTTPServer
|
---|
1157 | # Hop to the right working directory.
|
---|
1158 | os.chdir(os.path.dirname(__file__))
|
---|
1159 | try:
|
---|
1160 | PORT = int(sys.argv[2])
|
---|
1161 | except (IndexError,ValueError):
|
---|
1162 | PORT = 8000
|
---|
1163 |
|
---|
1164 | class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
|
---|
1165 | """ Serve this CGI from the root of the webserver """
|
---|
1166 | def is_cgi(self):
|
---|
1167 | if "favicon" in self.path:
|
---|
1168 | return False
|
---|
1169 |
|
---|
1170 | self.cgi_info = (os.path.basename(__file__), self.path)
|
---|
1171 | self.path = ''
|
---|
1172 | return True
|
---|
1173 | handler = MyCGIHTTPRequestHandler
|
---|
1174 | SocketServer.TCPServer.allow_reuse_address = True
|
---|
1175 | httpd = SocketServer.TCPServer(("", PORT), handler)
|
---|
1176 | httpd.server_name = 'localhost'
|
---|
1177 | httpd.server_port = PORT
|
---|
1178 |
|
---|
1179 | logger.info("serving at port %s", PORT)
|
---|
1180 | try:
|
---|
1181 | httpd.serve_forever()
|
---|
1182 | except KeyboardInterrupt:
|
---|
1183 | httpd.shutdown()
|
---|
1184 | logger.info("All done goodbye")
|
---|
1185 | elif sys.argv[1] == "test":
|
---|
1186 | os.environ['PATH_INFO'] = "/".join(sys.argv[2:])
|
---|
1187 | os.environ['SCRIPT_NAME'] = __file__
|
---|
1188 | process_cgi_request()
|
---|
1189 | elif sys.argv[1] == "static":
|
---|
1190 | items = dict()
|
---|
1191 | items['output_dir'] = sys.argv[2] if len(sys.argv) > 2 else "./static"
|
---|
1192 | for node in get_hostlist():
|
---|
1193 | items['node'] = node
|
---|
1194 | items['wdir'] = "%(output_dir)s/%(node)s" % items
|
---|
1195 | if not os.path.isdir(items['wdir']):
|
---|
1196 | os.makedirs(items['wdir'])
|
---|
1197 | datadump = get_yaml(node)
|
---|
1198 | for config in files:
|
---|
1199 | items['config'] = config
|
---|
1200 | logger.info("## Generating %(node)s %(config)s" % items)
|
---|
1201 | f = open("%(wdir)s/%(config)s" % items, "w")
|
---|
1202 | f.write(generate_config(node, config, datadump))
|
---|
1203 | f.close()
|
---|
1204 | elif sys.argv[1] == "wind-export":
|
---|
1205 | items = dict()
|
---|
1206 | for node in get_hostlist():
|
---|
1207 | datadump = get_yaml(node)
|
---|
1208 | sql = """INSERT IGNORE INTO nodes (name, name_ns, longitude, latitude)
|
---|
1209 | VALUES ('%(nodename)s', '%(nodename)s', %(latitude)s, %(longitude)s);""" % datadump;
|
---|
1210 | sql = """INSERT IGNORE INTO users_nodes (user_id, node_id, owner)
|
---|
1211 | VALUES (
|
---|
1212 | (SELECT id FROM users WHERE username = 'rvdzwet'),
|
---|
1213 | (SELECT id FROM nodes WHERE name = '%(nodename)s'),
|
---|
1214 | 'Y');""" % datadump
|
---|
1215 | #for config in files:
|
---|
1216 | # items['config'] = config
|
---|
1217 | # print "## Generating %(node)s %(config)s" % items
|
---|
1218 | # f = open("%(wdir)s/%(config)s" % items, "w")
|
---|
1219 | # f.write(generate_config(node, config, datadump))
|
---|
1220 | # f.close()
|
---|
1221 | for node in get_hostlist():
|
---|
1222 | datadump = get_yaml(node)
|
---|
1223 | for iface_key in sorted([elem for elem in datadump.keys() if elem.startswith('iface_')]):
|
---|
1224 | ifacedump = datadump[iface_key]
|
---|
1225 | if ifacedump.has_key('mode') and ifacedump['mode'] == 'ap-wds':
|
---|
1226 | ifacedump['nodename'] = datadump['nodename']
|
---|
1227 | if not ifacedump.has_key('channel') or not ifacedump['channel']:
|
---|
1228 | ifacedump['channel'] = 0
|
---|
1229 | sql = """INSERT INTO links (node_id, type, ssid, protocol, channel, status)
|
---|
1230 | VALUES ((SELECT id FROM nodes WHERE name = '%(nodename)s'), 'ap',
|
---|
1231 | '%(ssid)s', 'IEEE 802.11b', %(channel)s, 'active');""" % ifacedump
|
---|
1232 | elif sys.argv[1] == "full-export":
|
---|
1233 | hosts = {}
|
---|
1234 | for node in get_hostlist():
|
---|
1235 | datadump = get_yaml(node)
|
---|
1236 | hosts[datadump['nodename']] = datadump
|
---|
1237 | print yaml.dump(hosts)
|
---|
1238 |
|
---|
1239 | elif sys.argv[1] == "dns":
|
---|
1240 | make_dns(sys.argv[2] if len(sys.argv) > 2 else 'dns', 'external' in sys.argv)
|
---|
1241 | elif sys.argv[1] == "cleanup":
|
---|
1242 | # First generate all datadumps
|
---|
1243 | datadumps = dict()
|
---|
1244 | for host in get_hostlist():
|
---|
1245 | logger.info("# Processing: %s", host)
|
---|
1246 | # Set some boring default values
|
---|
1247 | datadump = { 'board' : 'UNKNOWN' }
|
---|
1248 | datadump.update(get_yaml(host))
|
---|
1249 | datadumps[datadump['autogen_realname']] = datadump
|
---|
1250 |
|
---|
1251 |
|
---|
1252 | for host,datadump in datadumps.iteritems():
|
---|
1253 | # Convert all yes and no to boolean values
|
---|
1254 | def fix_boolean(dump):
|
---|
1255 | for key in dump.keys():
|
---|
1256 | if type(dump[key]) == dict:
|
---|
1257 | dump[key] = fix_boolean(dump[key])
|
---|
1258 | elif str(dump[key]).lower() in ["yes", "true"]:
|
---|
1259 | dump[key] = True
|
---|
1260 | elif str(dump[key]).lower() in ["no", "false"]:
|
---|
1261 | # Compass richting no (Noord Oost) is valid input
|
---|
1262 | if key != "compass": dump[key] = False
|
---|
1263 | return dump
|
---|
1264 | datadump = fix_boolean(datadump)
|
---|
1265 |
|
---|
1266 | if datadump['rdnap_x'] and datadump['rdnap_y']:
|
---|
1267 | datadump['latitude'], datadump['longitude'] = rdnap.rd2etrs(datadump['rdnap_x'], datadump['rdnap_y'])
|
---|
1268 | elif datadump['latitude'] and datadump['longitude']:
|
---|
1269 | datadump['rdnap_x'], datadump['rdnap_y'] = rdnap.etrs2rd(datadump['latitude'], datadump['longitude'])
|
---|
1270 |
|
---|
1271 | if datadump['nodename'].startswith('Proxy'):
|
---|
1272 | datadump['nodename'] = datadump['nodename'].lower()
|
---|
1273 |
|
---|
1274 | for iface_key in datadump['autogen_iface_keys']:
|
---|
1275 | # Wireless Leiden SSID have an consistent lowercase/uppercase
|
---|
1276 | if datadump[iface_key].has_key('ssid'):
|
---|
1277 | ssid = datadump[iface_key]['ssid']
|
---|
1278 | prefix = 'ap-WirelessLeiden-'
|
---|
1279 | if ssid.lower().startswith(prefix.lower()):
|
---|
1280 | datadump[iface_key]['ssid'] = prefix + ssid[len(prefix)].upper() + ssid[len(prefix) + 1:]
|
---|
1281 | if datadump[iface_key].has_key('ns_ip') and not datadump[iface_key].has_key('mode'):
|
---|
1282 | datadump[iface_key]['mode'] = 'autogen-FIXME'
|
---|
1283 | if not datadump[iface_key].has_key('desc'):
|
---|
1284 | datadump[iface_key]['desc'] = 'autogen-FIXME'
|
---|
1285 | store_yaml(datadump)
|
---|
1286 | elif sys.argv[1] == "list":
|
---|
1287 | use_fqdn = False
|
---|
1288 | if len(sys.argv) < 4 or not sys.argv[2] in ["up", "down", "planned", "all"]:
|
---|
1289 | usage()
|
---|
1290 | if sys.argv[3] == "nodes":
|
---|
1291 | systems = get_nodelist()
|
---|
1292 | elif sys.argv[3] == "proxies":
|
---|
1293 | systems = get_proxylist()
|
---|
1294 | elif sys.argv[3] == "systems":
|
---|
1295 | systems = get_hostlist()
|
---|
1296 | else:
|
---|
1297 | usage()
|
---|
1298 | if len(sys.argv) > 4:
|
---|
1299 | if sys.argv[4] == "fqdn":
|
---|
1300 | use_fqdn = True
|
---|
1301 | else:
|
---|
1302 | usage()
|
---|
1303 |
|
---|
1304 | for system in systems:
|
---|
1305 | datadump = get_yaml(system)
|
---|
1306 |
|
---|
1307 | output = datadump['autogen_fqdn'] if use_fqdn else system
|
---|
1308 | if sys.argv[2] == "all":
|
---|
1309 | print output
|
---|
1310 | elif datadump['status'] == sys.argv[2]:
|
---|
1311 | print output
|
---|
1312 | elif sys.argv[1] == "create":
|
---|
1313 | if sys.argv[2] == "network.kml":
|
---|
1314 | print make_network_kml.make_graph()
|
---|
1315 | else:
|
---|
1316 | usage()
|
---|
1317 | usage()
|
---|
1318 | else:
|
---|
1319 | # Do not enable debugging for config requests as it highly clutters the output
|
---|
1320 | if not is_text_request():
|
---|
1321 | cgitb.enable()
|
---|
1322 | process_cgi_request()
|
---|
1323 |
|
---|
1324 |
|
---|
1325 | if __name__ == "__main__":
|
---|
1326 | main()
|
---|