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