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