1 | #!/usr/bin/env python
|
---|
2 | #
|
---|
3 | # vim:ts=2:et:sw=2:ai
|
---|
4 | # Wireless Leiden configuration generator, based on yaml files'
|
---|
5 | # Rick van der Zwet <info@rickvanderzwet.nl>
|
---|
6 | import cgi
|
---|
7 | import cgitb
|
---|
8 | import copy
|
---|
9 | import glob
|
---|
10 | import os
|
---|
11 | import socket
|
---|
12 | import string
|
---|
13 | import subprocess
|
---|
14 | import sys
|
---|
15 | import time
|
---|
16 | import yaml
|
---|
17 |
|
---|
18 | NODE_DIR = os.path.dirname(os.path.realpath(__file__))
|
---|
19 | __version__ = '$Id: gformat.py 8267 2010-08-08 15:21:43Z rick $'
|
---|
20 |
|
---|
21 |
|
---|
22 | files = [
|
---|
23 | 'authorized_keys',
|
---|
24 | 'dnsmasq.conf',
|
---|
25 | 'rc.conf.local',
|
---|
26 | 'resolv.conf',
|
---|
27 | 'wleiden.yaml'
|
---|
28 | ]
|
---|
29 |
|
---|
30 |
|
---|
31 |
|
---|
32 | def get_proxylist():
|
---|
33 | """Get all available proxies proxyX sorting based on X number"""
|
---|
34 | os.chdir(NODE_DIR)
|
---|
35 | proxylist = sorted(glob.glob("proxy*"),
|
---|
36 | key=lambda name: int(''.join([c for c in name if c in string.digits])),
|
---|
37 | cmp=lambda x,y: x - y)
|
---|
38 | return proxylist
|
---|
39 |
|
---|
40 |
|
---|
41 |
|
---|
42 | def get_nodelist():
|
---|
43 | """ Get all available nodes - sorted """
|
---|
44 | os.chdir(NODE_DIR)
|
---|
45 | nodelist = sorted(glob.glob("CNode*"))
|
---|
46 | return nodelist
|
---|
47 |
|
---|
48 |
|
---|
49 |
|
---|
50 | def generate_title(nodelist):
|
---|
51 | """ Main overview page """
|
---|
52 | items = {'root' : "." }
|
---|
53 | output = """
|
---|
54 | <html>
|
---|
55 | <head>
|
---|
56 | <title>Wireless leiden Configurator - GFormat</title>
|
---|
57 | <style type="text/css">
|
---|
58 | th {background-color: #999999}
|
---|
59 | tr:nth-child(odd) {background-color: #cccccc}
|
---|
60 | tr:nth-child(even) {background-color: #ffffff}
|
---|
61 | th, td {padding: 0.1em 1em}
|
---|
62 | </style>
|
---|
63 | </head>
|
---|
64 | <body>
|
---|
65 | <center>
|
---|
66 | <form type="GET" action="%(root)s">
|
---|
67 | <input type="hidden" name="action" value="update">
|
---|
68 | <input type="submit" value="Update Configuration Database (SVN)">
|
---|
69 | </form>
|
---|
70 | <table>
|
---|
71 | <caption><h3>Wireless Leiden Configurator</h3></caption>
|
---|
72 | """ % items
|
---|
73 |
|
---|
74 | for node in sorted(nodelist):
|
---|
75 | items['node'] = node
|
---|
76 | output += '<tr><td><a href="%(root)s/%(node)s">%(node)s</a></td>' % items
|
---|
77 | for config in files:
|
---|
78 | items['config'] = config
|
---|
79 | output += '<td><a href="%(root)s/%(node)s/%(config)s">%(config)s</a></td>' % items
|
---|
80 | output += "</tr>"
|
---|
81 | output += """
|
---|
82 | </table>
|
---|
83 | <hr />
|
---|
84 | <em>%s</em>
|
---|
85 | </center>
|
---|
86 | </body>
|
---|
87 | </html>
|
---|
88 | """ % __version__
|
---|
89 |
|
---|
90 | return output
|
---|
91 |
|
---|
92 |
|
---|
93 |
|
---|
94 | def generate_node(node):
|
---|
95 | """ Print overview of all files available for node """
|
---|
96 | return "\n".join(files)
|
---|
97 |
|
---|
98 |
|
---|
99 |
|
---|
100 | def generate_header(ctag="#"):
|
---|
101 | return """\
|
---|
102 | %(ctag)s
|
---|
103 | %(ctag)s DO NOT EDIT - Automatically generated by 'gformat'
|
---|
104 | %(ctag)s Generated at %(date)s by %(host)s
|
---|
105 | %(ctag)s
|
---|
106 | """ % { 'ctag' : ctag, 'date' : time.ctime(), 'host' : socket.gethostname() }
|
---|
107 |
|
---|
108 |
|
---|
109 |
|
---|
110 | def parseaddr(s):
|
---|
111 | """ Process IPv4 CIDR notation addr to a (binary) number """
|
---|
112 | f = s.split('.')
|
---|
113 | return (long(f[0]) << 24L) + \
|
---|
114 | (long(f[1]) << 16L) + \
|
---|
115 | (long(f[2]) << 8L) + \
|
---|
116 | long(f[3])
|
---|
117 |
|
---|
118 |
|
---|
119 |
|
---|
120 | def showaddr(a):
|
---|
121 | """ Display IPv4 addr in (dotted) CIDR notation """
|
---|
122 | return "%d.%d.%d.%d" % ((a >> 24) & 0xff, (a >> 16) & 0xff, (a >> 8) & 0xff, a & 0xff)
|
---|
123 |
|
---|
124 |
|
---|
125 |
|
---|
126 | def netmask2subnet(netmask):
|
---|
127 | """ Given a 'netmask' return corresponding CIDR """
|
---|
128 | return showaddr(0xffffffff & (0xffffffff << (32 - int(netmask))))
|
---|
129 |
|
---|
130 |
|
---|
131 |
|
---|
132 | def generate_dnsmasq_conf(datadump):
|
---|
133 | """ Generate configuration file '/usr/local/etc/dnsmasq.conf' """
|
---|
134 | output = generate_header()
|
---|
135 | output += """\
|
---|
136 | # DHCP server options
|
---|
137 | dhcp-authoritative
|
---|
138 | dhcp-fqdn
|
---|
139 | domain=dhcp.%(nodename_lower)s.%(domain)s
|
---|
140 | domain-needed
|
---|
141 | expand-hosts
|
---|
142 |
|
---|
143 | # Low memory footprint
|
---|
144 | cache-size=10000
|
---|
145 | \n""" % datadump
|
---|
146 |
|
---|
147 | for iface_key in datadump['iface_keys']:
|
---|
148 | if not datadump[iface_key].has_key('comment'):
|
---|
149 | datadump[iface_key]['comment'] = None
|
---|
150 | output += "## %(interface)s - %(desc)s - %(comment)s\n" % datadump[iface_key]
|
---|
151 |
|
---|
152 | try:
|
---|
153 | (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
|
---|
154 | (ip, netmask) = datadump[iface_key]['ip'].split('/')
|
---|
155 | datadump[iface_key]['subnet'] = netmask2subnet(netmask)
|
---|
156 | except (AttributeError, ValueError):
|
---|
157 | output += "# not autoritive\n\n"
|
---|
158 | continue
|
---|
159 |
|
---|
160 | dhcp_part = ".".join(ip.split('.')[0:3])
|
---|
161 | datadump[iface_key]['dhcp_start'] = dhcp_part + "." + dhcp_start
|
---|
162 | datadump[iface_key]['dhcp_stop'] = dhcp_part + "." + dhcp_stop
|
---|
163 | output += "dhcp-range=%(interface)s,%(dhcp_start)s,%(dhcp_stop)s,%(subnet)s,24h\n\n" % datadump[iface_key]
|
---|
164 |
|
---|
165 | return output
|
---|
166 |
|
---|
167 |
|
---|
168 |
|
---|
169 | def generate_rc_conf_local(datadump):
|
---|
170 | """ Generate configuration file '/etc/rc.conf.local' """
|
---|
171 | output = generate_header("#");
|
---|
172 | output += """\
|
---|
173 | hostname='%(nodetype)s%(nodename)s.%(domain)s'
|
---|
174 | location='%(location)s'
|
---|
175 | """ % datadump
|
---|
176 |
|
---|
177 | # TProxy configuration
|
---|
178 | output += "\n"
|
---|
179 | try:
|
---|
180 | if datadump['tproxy']:
|
---|
181 | output += """\
|
---|
182 | tproxy_enable='YES'
|
---|
183 | tproxy_range='%(tproxy)s'
|
---|
184 | """ % datadump
|
---|
185 | except KeyError:
|
---|
186 | output += "tproxy_enable='NO'\n"
|
---|
187 |
|
---|
188 | output += '\n'
|
---|
189 | # lo0 configuration:
|
---|
190 | # - 172.32.255.1/32 is the proxy.wleiden.net deflector
|
---|
191 | # - masterip is special as it needs to be assigned to at
|
---|
192 | # least one interface, so if not used assign to lo0
|
---|
193 | addrs_list = { 'lo0' : ["127.0.0.1/8", "172.31.255.1/32"] }
|
---|
194 | iface_map = {'lo0' : 'lo0'}
|
---|
195 | if not any([datadump[iface_key]['ip'].startswith(datadump['masterip']) \
|
---|
196 | for iface_key in datadump['iface_keys']]):
|
---|
197 | lo0_addrs.append(datadump['masterip'] + "/32")
|
---|
198 |
|
---|
199 | wlan_count = 0
|
---|
200 | for iface_key in datadump['iface_keys']:
|
---|
201 | ifacedump = datadump[iface_key]
|
---|
202 | interface = ifacedump['interface']
|
---|
203 | # By default no special interface mapping
|
---|
204 | iface_map[interface] = interface
|
---|
205 |
|
---|
206 | # Add interface IP to list
|
---|
207 | if addrs_list.has_key(interface):
|
---|
208 | addrs_list[interface].append(ifacedump['ip'])
|
---|
209 | else:
|
---|
210 | addrs_list[interface] = [ifacedump['ip']]
|
---|
211 |
|
---|
212 | # Alias only needs IP assignment for now, this might change if we
|
---|
213 | # are going to use virtual accesspoints
|
---|
214 | if "alias" in iface_key:
|
---|
215 | continue
|
---|
216 |
|
---|
217 | # XXX: Might want to deduct type directly from interface name
|
---|
218 | if ifacedump['type'] in ['11a', '11b', '11g', 'wireless']:
|
---|
219 | # Create wlanX interface
|
---|
220 | ifacedump['wlanif'] ="wlan%i" % wlan_count
|
---|
221 | iface_map[interface] = ifacedump['wlanif']
|
---|
222 | wlan_count += 1
|
---|
223 |
|
---|
224 | # Default to station (client) mode
|
---|
225 | ifacedump['wlanmode'] = "sta"
|
---|
226 | if ifacedump['mode'] in ['master']:
|
---|
227 | ifacedump['wlanmode'] = "ap"
|
---|
228 | # Default to 802.11b mode
|
---|
229 | ifacedump['mode'] = '11b'
|
---|
230 | if ifacedump['type'] in ['11a', '11b' '11g']:
|
---|
231 | ifacedump['mode'] = ifacedump['type']
|
---|
232 |
|
---|
233 | if not ifacedump.has_key('channel'):
|
---|
234 | if ifacedump['type'] == '11a':
|
---|
235 | ifacedump['channel'] = 36
|
---|
236 | else:
|
---|
237 | ifacedump['channel'] = 1
|
---|
238 |
|
---|
239 | # Allow special hacks at the back like wds and stuff
|
---|
240 | if not ifacedump.has_key('extra'):
|
---|
241 | ifacedump['extra'] = 'regdomain ETSI country NL'
|
---|
242 |
|
---|
243 | output += "wlans_%(interface)s='%(wlanif)s'\n" % ifacedump
|
---|
244 | output += ("create_args_%(wlanif)s='wlanmode %(wlanmode)s mode " +\
|
---|
245 | "%(mode)s ssid %(ssid)s channel %(channel)s %(extra)s'\n") % ifacedump
|
---|
246 |
|
---|
247 | elif ifacedump['type'] in ['ethernet', 'eth']:
|
---|
248 | # No special config needed besides IP
|
---|
249 | pass
|
---|
250 | else:
|
---|
251 | assert False, "Unknown type " + ifacedump['type']
|
---|
252 |
|
---|
253 | # Print IP address which needs to be assigned over here
|
---|
254 | output += "\n"
|
---|
255 | for iface,addrs in sorted(addrs_list.iteritems()):
|
---|
256 | output += "ipv4_addrs_%s='%s'\n" % (iface_map[iface], " ".join(addrs))
|
---|
257 |
|
---|
258 | return output
|
---|
259 |
|
---|
260 |
|
---|
261 |
|
---|
262 | def get_yaml(item):
|
---|
263 | """ Get configuration yaml for 'item'"""
|
---|
264 | gfile = NODE_DIR + '/%s/wleiden.yaml' % item
|
---|
265 |
|
---|
266 | f = open(gfile, 'r')
|
---|
267 | datadump = yaml.load(f)
|
---|
268 | f.close()
|
---|
269 |
|
---|
270 | return datadump
|
---|
271 |
|
---|
272 |
|
---|
273 |
|
---|
274 | def write_yaml(item, datadump):
|
---|
275 | """ Write configuration yaml for 'item'"""
|
---|
276 | gfile = NODE_DIR + '/%s/wleiden.yaml' % item
|
---|
277 |
|
---|
278 | f = open(gfile, 'w')
|
---|
279 | f.write(format_wleiden_yaml(datadump))
|
---|
280 | f.close()
|
---|
281 |
|
---|
282 |
|
---|
283 |
|
---|
284 | def generate_resolv_conf(datadump):
|
---|
285 | """ Generate configuration file '/etc/resolv.conf' """
|
---|
286 | output = generate_header("#");
|
---|
287 | output += """\
|
---|
288 | search wleiden.net
|
---|
289 | # Try local (cache) first
|
---|
290 | nameserver 127.0.0.1
|
---|
291 |
|
---|
292 | # Proxies are recursive nameservers
|
---|
293 | # needs to be in resolv.conf for dnsmasq as well
|
---|
294 | """ % datadump
|
---|
295 |
|
---|
296 | for proxy in get_proxylist():
|
---|
297 | proxy_ip = get_yaml(proxy)['masterip']
|
---|
298 | output += "nameserver %-15s # %s\n" % (proxy_ip, proxy)
|
---|
299 | return output
|
---|
300 |
|
---|
301 |
|
---|
302 |
|
---|
303 | def format_yaml_value(value):
|
---|
304 | """ Get yaml value in right syntax for outputting """
|
---|
305 | if isinstance(value,str):
|
---|
306 | output = "'%s'" % value
|
---|
307 | else:
|
---|
308 | output = value
|
---|
309 | return output
|
---|
310 |
|
---|
311 |
|
---|
312 |
|
---|
313 | def format_wleiden_yaml(datadump):
|
---|
314 | """ Special formatting to ensure it is editable"""
|
---|
315 | output = "# Genesis config yaml style\n"
|
---|
316 | output += "# vim:ts=2:et:sw=2:ai\n"
|
---|
317 | output += "#\n"
|
---|
318 | iface_keys = [elem for elem in datadump.keys() if elem.startswith('iface_')]
|
---|
319 | for key in sorted(set(datadump.keys()) - set(iface_keys)):
|
---|
320 | output += "%-10s: %s\n" % (key, format_yaml_value(datadump[key]))
|
---|
321 |
|
---|
322 | output += "\n\n"
|
---|
323 |
|
---|
324 | for iface_key in sorted(iface_keys):
|
---|
325 | output += "%s:\n" % iface_key
|
---|
326 | for key in sorted(datadump[iface_key]):
|
---|
327 | output += " %-11s: %s\n" % (key, format_yaml_value(datadump[iface_key][key]))
|
---|
328 | output += "\n\n"
|
---|
329 |
|
---|
330 | return output
|
---|
331 |
|
---|
332 |
|
---|
333 |
|
---|
334 | def generate_wleiden_yaml(datadump):
|
---|
335 | """ Generate (petty) version of wleiden.yaml"""
|
---|
336 | output = generate_header("#")
|
---|
337 | output += format_wleiden_yaml(datadump)
|
---|
338 | return output
|
---|
339 |
|
---|
340 |
|
---|
341 |
|
---|
342 | def generate_config(node, config):
|
---|
343 | """ Print configuration file 'config' of 'node' """
|
---|
344 | output = ""
|
---|
345 | try:
|
---|
346 | # Load config file
|
---|
347 | datadump = get_yaml(node)
|
---|
348 |
|
---|
349 | # Preformat certain needed variables for formatting and push those into special object
|
---|
350 | datadump_extra = copy.deepcopy(datadump)
|
---|
351 | if not datadump_extra.has_key('domain'):
|
---|
352 | datadump_extra['domain'] = 'wleiden.net'
|
---|
353 | datadump_extra['nodename_lower'] = datadump_extra['nodename'].lower()
|
---|
354 | datadump_extra['iface_keys'] = sorted([elem for elem in datadump.keys() if elem.startswith('iface_')])
|
---|
355 |
|
---|
356 | if config == 'wleiden.yaml':
|
---|
357 | output += generate_wleiden_yaml(datadump)
|
---|
358 | elif config == 'authorized_keys':
|
---|
359 | f = open("global_keys", 'r')
|
---|
360 | output += f.read()
|
---|
361 | f.close()
|
---|
362 | elif config == 'dnsmasq.conf':
|
---|
363 | output += generate_dnsmasq_conf(datadump_extra)
|
---|
364 | elif config == 'rc.conf.local':
|
---|
365 | output += generate_rc_conf_local(datadump_extra)
|
---|
366 | elif config == 'resolv.conf':
|
---|
367 | output += generate_resolv_conf(datadump_extra)
|
---|
368 | else:
|
---|
369 | assert False, "Config not found!"
|
---|
370 | except IOError, e:
|
---|
371 | output += "[ERROR] Config file not found"
|
---|
372 | return output
|
---|
373 |
|
---|
374 |
|
---|
375 |
|
---|
376 | def process_cgi_request():
|
---|
377 | """ When calling from CGI """
|
---|
378 | # Update repository if requested
|
---|
379 | form = cgi.FieldStorage()
|
---|
380 | if form.getvalue("action") == "update":
|
---|
381 | print "Refresh: 5; url=."
|
---|
382 | print "Content-type:text/plain\r\n\r\n",
|
---|
383 | print "[INFO] Updating subverion, please wait..."
|
---|
384 | print subprocess.Popen(['svn', 'up', NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0],
|
---|
385 | print "[INFO] All done, redirecting in 5 seconds"
|
---|
386 | sys.exit(0)
|
---|
387 |
|
---|
388 |
|
---|
389 | uri = os.environ['PATH_INFO'].strip('/').split('/')
|
---|
390 | output = ""
|
---|
391 | if not uri[0]:
|
---|
392 | output += "Content-type:text/html\r\n\r\n"
|
---|
393 | output += generate_title(get_nodelist())
|
---|
394 | elif len(uri) == 1:
|
---|
395 | output += "Content-type:text/plain\r\n\r\n"
|
---|
396 | output += generate_node(uri[0])
|
---|
397 | elif len(uri) == 2:
|
---|
398 | output += "Content-type:text/plain\r\n\r\n"
|
---|
399 | output += generate_config(uri[0], uri[1])
|
---|
400 | else:
|
---|
401 | assert False, "Invalid option"
|
---|
402 | print output
|
---|
403 |
|
---|
404 |
|
---|
405 | def usage():
|
---|
406 | print """Usage: %s <standalone [port] |test [test arguments]>
|
---|
407 | Examples:
|
---|
408 | \tstandalone = Run configurator webserver [default port=8000]
|
---|
409 | \ttest CNodeRick dnsmasq.conf = Receive output of CGI script
|
---|
410 | \t for arguments CNodeRick/dnsmasq.conf
|
---|
411 | """
|
---|
412 | exit(0)
|
---|
413 |
|
---|
414 |
|
---|
415 |
|
---|
416 | def main():
|
---|
417 | """Hard working sub"""
|
---|
418 | # Allow easy hacking using the CLI
|
---|
419 | if not os.environ.has_key('PATH_INFO'):
|
---|
420 | if len(sys.argv) < 2:
|
---|
421 | usage()
|
---|
422 |
|
---|
423 | if sys.argv[1] == "standalone":
|
---|
424 | import SocketServer
|
---|
425 | import CGIHTTPServer
|
---|
426 | try:
|
---|
427 | PORT = int(sys.argv[2])
|
---|
428 | except (IndexError,ValueError):
|
---|
429 | PORT = 8000
|
---|
430 |
|
---|
431 | class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
|
---|
432 | """ Serve this CGI from the root of the webserver """
|
---|
433 | def is_cgi(self):
|
---|
434 | if "favicon" in self.path:
|
---|
435 | return False
|
---|
436 |
|
---|
437 | self.cgi_info = (__file__, self.path)
|
---|
438 | self.path = ''
|
---|
439 | return True
|
---|
440 | handler = MyCGIHTTPRequestHandler
|
---|
441 | httpd = SocketServer.TCPServer(("", PORT), handler)
|
---|
442 | httpd.server_name = 'localhost'
|
---|
443 | httpd.server_port = PORT
|
---|
444 |
|
---|
445 | print "serving at port", PORT
|
---|
446 | httpd.serve_forever()
|
---|
447 | elif sys.argv[1] == "test":
|
---|
448 | os.environ['PATH_INFO'] = "/".join(sys.argv[2:])
|
---|
449 | os.environ['SCRIPT_NAME'] = __file__
|
---|
450 | process_cgi_request()
|
---|
451 | else:
|
---|
452 | usage()
|
---|
453 | else:
|
---|
454 | cgitb.enable()
|
---|
455 | process_cgi_request()
|
---|
456 |
|
---|
457 |
|
---|
458 | if __name__ == "__main__":
|
---|
459 | main()
|
---|