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