示例#1
0
文件: Routing.py 项目: calston/tums
    def submitRoute(self, ctx, form, data):
        eth = self.sysconf.EthernetDevices
        target = None
        destination = data['dest'].encode("ascii", "replace").lower()
        if data['gate']:
            gateway = data['gate'].encode("ascii", "replace")
            if data['device']:
                target = data['device'].encode("ascii", "replace")
        else:
            gateway = data['device'].encode("ascii", "replace")

        if '0.0.0.0/0' in destination:
            destination = 'default'

        if destination == 'default':
            # Purge existing default routes, if any
            for dev, items in eth.items():
                oldRoutes = items.get('routes', [])
                newRoutes = []
                for dst, gw in oldRoutes:
                    if dst == "default":
                        continue
                    newRoutes.append((dst, gw))
                eth[dev]['routes'] = newRoutes

        if (not target) and data['gate']:
            # Dunno where to go... Look at gateway and make an intelligent choice
            for iface, net in Utils.getLanNetworks(self.sysconf).items():
                print data['gate']
                if Utils.matchIP(net, gateway):
                    # Gateway matches this interface local-link
                    target = iface
        if not target:
            # Still nothing, go for broke - these will be added to Quagga anyways
            target = Utils.getLans(self.sysconf)[0]

        routes = eth[target].get('routes', [])
        routes.append((destination, gateway))

        eth[target]['routes'] = routes
        self.sysconf.EthernetDevices = eth

        def next(_):
            return url.root.child('Routing')

        return applySettings().addCallback(next)
示例#2
0
文件: Routing.py 项目: calston/tums
    def submitRoute(self, ctx, form, data):
        eth = self.sysconf.EthernetDevices
        target = None
        destination = data['dest'].encode()
        if data['gate']:
            gateway = data['gate'].encode()
        else:
            gateway = data['device'].encode()

        if '0.0.0.0/0' in destination:
            destination = u'default'
            if 'eth' in self.sysconf.WANPrimary:
                target = self.sysconf.WANPrimary
            else:
                target = Utils.getLans(self.sysconf)[0]

        if (not target) and data['gate']:
            # Dunno where to go... Look at gateway and make an intelligent choice
            for iface, net in Utils.getLanNetworks(self.sysconf).items():
                print data['gate']
                if Utils.matchIP(net, gateway):
                    # Gateway matches this interface local-link
                    target = iface
        if not target:
            # Still nothing, go for broke
            target = Utils.getLans(self.sysconf)[0]

        routes = eth[target].get('routes', [])
        routes.append((destination, gateway))
        
        eth[target]['routes'] = routes
        self.sysconf.EthernetDevices = eth

        def next(_):
            return url.root.child('Routing')
        return applySettings().addCallback(next)
示例#3
0
    def renderHTTP(self, ctx):
        request = inevow.IRequest(ctx)
        
        def render(data):
            # Set our content dispositions and write the stream
            request.setHeader("content-type", "image/png")
            request.setHeader("content-length", str(len(data)))
            return data
        width = 700
        height = 64
        rHeight, lHeight = 0, 0

       
        # Internet side (left)
        locals = Utils.getLans(self.sysconf)

        wans = {}
        lans = {}
        leftSize = 0
        rightSize = 0

        balanceZones = {}

        for zone, ip, type in self.sysconf.ShorewallBalance:
            balance = 'balance' in type
            balanceZones[zone] = (balance, ip)
        self.balanced = []
        idefer = []
        for k,net in Utils.getNetworks(self.sysconf).items():
            routes = {}
            size = 1
            
            zone = Utils.getZone(self.sysconf, k)
            doneInet = False
            if zone in balanceZones:
                if balanceZones[zone][0]:
                    self.balanced.append(k)
                gate = balanceZones[zone][1]
                if gate:
                    # otherwise... wtf
                    routes[('router', gate)] = {('internet', 'Internet', k):None}
                    size = 3
                else:
                    # Get a new router icon for Link-route devices like PPPoE
                    routes[('router', 'LINK')]= {('internet', 'Internet', k):None}

            for dst,gate in self.sysconf.EthernetDevices[k].get('routes', []):
                if (dst == 'default') and (not doneInet):
                    if Utils.matchIP(net, gate):
                        # The default router sits on this segment
                        routes[('router', gate)] = {('internet', 'Internet', k): None}
                        if 3>size:
                            size = 3
                else:
                    # Another switch behind a router
                    routes[('router', gate)] = {('switch', dst): None}
                    size = 3

            if k in locals:
                node = ('switch', net+'-'+k)
                lans[node] = routes
                if size > rightSize:
                    rightSize = size
                rHeight += 64
            else:
                node = ('switch', net+'-'+k)
                if k in self.balanced:
                    idefer.append((node, routes))
                else:
                    wans[node] = routes

                if size > leftSize:
                    leftSize = size
                lHeight += 64

        for k,v in self.sysconf.WANDevices.items():
            routes = {}
            zone = Utils.getZone(self.sysconf, k)
            lHeight += 64
            if zone in balanceZones:
                if balanceZones[zone][0]:
                    self.balanced.append(k)
                gate = balanceZones[zone][1]
                # Get a new router icon for Link-route devices like PPPoE
                routes[('internet', 'Internet', k)] = None

            if 'defaultroute' in v.get('pppd', []):
                routes[('internet', 'Internet', k)] = None
            else:
                if k == self.sysconf.LocalRoute:
                    # Put a ZA flag here...
                    routes[('internet', 'Internet', k)] = None
            if not routes:
                routes[('switch', 'Cloud', k)] = None
                
            node = ('netlink', 'PPP '+k[-1])
            wans[node] = routes

        # Figure out our best dimensions
        mHeight = max([rHeight, lHeight])

        print "Total height", mHeight, rHeight, lHeight
        height = mHeight

        # Configure our context
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height+16)
        c = cairo.Context(surface)
        
        c.set_line_width(2)
 
        vloc = (width/2, height/2)  # Center of image (where vulani goes)

        wans = [i for i in wans.items()]
        wans.extend(idefer)
        #for node, routes in idefer:
        #    wans.append((node] = routes

        totalBreadth = leftSize + rightSize + 1
        print "Total width", totalBreadth, leftSize, rightSize
        xSteps = (width)/totalBreadth
        if leftSize:
            if leftSize == rightSize:
                vx = width/2
            else:
                vx = (xSteps * leftSize) + 56
        else:
            vx = 56

        vloc = (vx, height/2)

        self.drawLater = []
        posX = 64

        # Wans (left)
        self.iLoc = None
        self.parseTree(c, wans, height, 0, vloc[0]-xSteps, vloc, -xSteps)
        # Lans (right)
        self.parseTree(c, lans, height, 0, vloc[0]+xSteps, vloc, +xSteps)

        #self.text(c, "Hello", 10.5, 30,30)

        for i in self.drawLater:
            self.drawImage(c, i[0], (i[1], i[2]), True)
        self.drawImage(c, '/usr/local/tcs/tums/images/vulani-globe-64.png', vloc, True)
        
        out = StringIO.StringIO()
        surface.write_to_png(out)
        out.seek(0)
        return render(out.read())
示例#4
0
 def matchLans(self, ip):
     """ Match an IP to a LAN interface """
     for n in self.lanNetworks:
         if Utils.matchIP(n, ip):
             return True
     return False
示例#5
0
文件: DHCP.py 项目: calston/tums
    def writeConfig(self, *a):
        lans = Utils.getLanNetworks(config)
        extramain = config.DHCP.get('main','')
        
        ips = Utils.getLanIPs(config)
        myIp = ips[0]
        rev = '.'.join([i for i in reversed(myIp.split('.')[:3])])

        ifaces = []
        
        dhcpconf = """# DHCPD config generated by TUMS Configurator
ddns-update-style interim;
default-lease-time 21600;
max-lease-time 21600;
allow booting;
allow bootp;
authoritative;
log-facility local7;

zone %(domain)s. {
    primary 127.0.0.1;
}

zone %(rev)s.in-addr.arpa. {
    primary 127.0.0.1;
}

option local-pac-server code 252 = text;

%(extramain)s
"""     % {
            'extramain': extramain, 
            'domain': config.Domain,
            'rev': rev
        }
        
        n = 0 
        for k,v in lans.items():
            myNet = v
            myIp = config.EthernetDevices[k].get('ip', '/').split('/')[0]
            
            dhcpConf = config.DHCP.get(k, {})
            
            if not myIp:
                # No IP set for this interface (is DHCP itself)
                continue 
            if not config.EthernetDevices[k].get('dhcpserver'):
                # Not set to do DHCP
                continue
            
            ifaces.append(k)

            statics = ""
            
            for ip, hostmac in config.DHCP.get('leases',{}).items():
                if Utils.matchIP(myNet, ip):
                    # make sure the IP is in this network
                    host, mac = hostmac
                    statics += """    host %s {
            fixed-address %s;
            hardware ethernet %s;
        }\n""" % (host, ip, mac)
            
            myNetmask = Utils.cidr2netmask(myNet.split('/')[1])
            
            rangeStart  = dhcpConf.get('rangeStart', "100")
            rangeEnd    = dhcpConf.get('rangeEnd', "240")

            netmask     = dhcpConf.get('netmask', myNetmask)
            netbios     = dhcpConf.get('netbios', myIp)
            nameserver  = dhcpConf.get('nameserver', myIp)
            router      = dhcpConf.get('gateway', myIp)
            myNet       = dhcpConf.get('network', Utils.getNetwork(config.EthernetDevices[k]['ip']))
            domain      = dhcpConf.get('domain', config.Domain)
            if not '/' in myNet:
                # AAAAAAAAAAAARGH GOD DAMN DIE IN HELL PAUL VIXIE
                cdr = Utils.netmask2cidr(netmask)
                myNet = "%s/%s" % (myNet, cdr)
                bcast       = Utils.getBroadcast(myNet)
            else:
                bcast = Utils.getBroadcast(myNet)
            
            # allow custom configuration options
            custom = dhcpConf.get('custom', '')
            
            netL = '.'.join(myNet.split('.')[:3])

            if not ("." in rangeStart):
                rangeStart = "%s.%s" % (netL, rangeStart)
                rangeEnd = "%s.%s" % (netL, rangeEnd)

            defn = {
                'netname': 'DHCP%s' % k.upper(),
                'myIp': myIp,
                'pacIp': myIp.replace('.', '-'),
                'domain': domain,
                'network': netL,
                'networkF': myNet.split('/')[0],
                'static': statics,
                'custom': custom,
                'netmask': netmask,
                'rangeStart': rangeStart,
                'rangeEnd': rangeEnd,
                'myNetbios': netbios,
                'myDns': nameserver,
                'myRouter': router,
                'extramain': extramain,
                'bcast': bcast
            }
            
            dhcpnet = """
shared-network %(netname)s {
    use-host-decl-names           on;
    option domain-name            "%(domain)s";
    option domain-name-servers    %(myDns)s;
    
    option netbios-name-servers   %(myNetbios)s;
    option netbios-node-type      8;

    option local-pac-server "http://%(myIp)s/wpad-%(pacIp)s.pac"; 

    option ntp-servers            %(myIp)s;
    option time-servers           %(myIp)s;
    option log-servers            %(myIp)s;
    option font-servers           %(myIp)s;
    option pop-server             %(myIp)s;
    option smtp-server            %(myIp)s;
    option x-display-manager      %(myIp)s;
    
    subnet %(networkF)s netmask %(netmask)s {
        range dynamic-bootp           %(rangeStart)s %(rangeEnd)s;
        option subnet-mask            %(netmask)s;
        option broadcast-address      %(bcast)s;
        option routers                %(myRouter)s;
    }
%(static)s
%(custom)s
}\n"""      % defn
            
            dhcpconf += dhcpnet
        
        # Check for debianism (goes in /etc/dhcp3)
        f = open('/etc/dhcp3/dhcpd.conf', 'wt')
        f.write(dhcpconf)
        f.close()

        f = open('/etc/default/dhcp3-server', 'wt')
        f.write('# On what interfaces should the DHCP server (dhcpd) serve DHCP requests?\n')
        f.write('#       Separate multiple interfaces with spaces, e.g. "eth0 eth1".\n')
        f.write('INTERFACES="%s"\n' % ' '.join(ifaces))
        f.close()