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