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