Esempio n. 1
0
    def connect_to_dynamips(self, local_port, dynamips, remote_slot, remote_int, remote_port):
        #figure out the destionation port according to interface descritors
        if remote_slot.adapter in ['ETHSW', 'ATMSW', 'ATMBR', 'FRSW', 'Bridge']:
            # This is a virtual switch that doesn't provide interface descriptors
            dst_port = remote_port
        else:
            # Look at the interfaces dict to find out what the real port is as
            # as far as dynamips is concerned
            try:
                dst_port = remote_slot.interfaces[remote_int][remote_port]
            except KeyError:
                raise DynamipsError, 'invalid interface'

        #validate the connection
        if not validate_connect('e', remote_int, self.p, self, local_port, dynamips, remote_slot, remote_port):
            return

        (src_udp, dst_udp) = self.__allocate_udp_port(dynamips)

        if self.p.host == dynamips.host:
            # source and dest adapters are on the same dynamips server, perform loopback binding optimization
            src_ip = '127.0.0.1'
            dst_ip = '127.0.0.1'
        else:
            # source and dest are on different dynamips servers
            src_ip = self.p.name
            dst_ip = dynamips.host

            #check whether the user did not make a mistake in multi-server .net file
            if src_ip == 'localhost' or src_ip =='127.0.0.1' or dst_ip =='localhost' or dst_ip == '127.0.0.1':
                dowarning('Connecting %s port %s to %s slot %s port %s:\nin case of multi-server operation make sure you do not use "localhost" string in definition of dynamips hypervisor.\n'% (self.name, local_port, remote_slot.router.name, remote_slot.adapter, remote_port))

        #create the emulated device side of UDP connection
        send(self.p, 'qemu create_udp %s %i %i %s %i' % (self.name, local_port, src_udp, dst_ip, dst_udp))
        self.nios[local_port] = UDPConnection(src_udp, dst_ip, dst_udp, self, local_port)

        #create the dynamips side of UDP connection - the NIO and connect it to the router
        remote_nio = NIO_udp(dynamips, dst_udp, src_ip, src_udp, None, remote_slot, dst_port)

        if isinstance(remote_slot, Bridge):
            # Bridges don't use ports
            remote_slot.nio(nio=remote_nio)
        else:
            remote_slot.nio(port=dst_port, nio=remote_nio)

        #set reverse nios
        remote_nio.reverse_nio = self.nios[local_port]
        self.nios[local_port].reverse_nio = remote_nio
Esempio n. 2
0
    def connect_to_dynamips(self, local_port, dynamips, remote_slot, remote_int, remote_port):
        #figure out the destionation port according to interface descritors
        if remote_slot.adapter in ['ETHSW', 'ATMSW', 'FRSW', 'Bridge']:
            # This is a virtual switch that doesn't provide interface descriptors
            dst_port = remote_port
        else:
            # Look at the interfaces dict to find out what the real port is as
            # as far as dynamips is concerned
            try:
                dst_port = remote_slot.interfaces[remote_int][remote_port]
            except KeyError:
                raise DynamipsError, 'invalid interface'

        #validate the connection
        if not validate_connect('e', remote_int, self.p, self, local_port, dynamips, remote_slot, remote_port):
            return

        (src_udp, dst_udp) = self.__allocate_udp_port(dynamips)

        if self.p.host == dynamips.host:
            # source and dest adapters are on the same dynamips server, perform loopback binding optimization
            src_ip = '127.0.0.1'
            dst_ip = '127.0.0.1'
        else:
            # source and dest are on different dynamips servers
            src_ip = self.p.name
            dst_ip = dynamips.host
            
            #check whether the user did not make a mistake in multi-server .net file
            if src_ip == 'localhost' or src_ip =='127.0.0.1' or dst_ip =='localhost' or dst_ip == '127.0.0.1':
                dowarning('Connecting %s port %s to %s slot %s port %s:\nin case of multi-server operation make sure you do not use "localhost" string in definition of dynamips hypervisor.\n'% (self.name, local_port, remote_slot.router.name, remote_slot.adapter, remote_port))

        #create the fw side of UDP connection
        send(self.p, 'pemu create_udp %s %i %i %s %i' % (self.name, local_port, src_udp, dst_ip, dst_udp))
        self.nios[local_port] = UDPConnection(src_udp, dst_ip, dst_udp, self, local_port)

        #create the dynamips side of UDP connection - the NIO and connect it to the router
        remote_nio = NIO_udp(dynamips, dst_udp, src_ip, src_udp, None, remote_slot, dst_port)
        
        if isinstance(remote_slot, Bridge):
            # Bridges don't use ports
            remote_slot.nio(nio=remote_nio)
        else:
            remote_slot.nio(port=dst_port, nio=remote_nio)
        
        #set reverse nios
        remote_nio.reverse_nio = self.nios[local_port]
        self.nios[local_port].reverse_nio = remote_nio
Esempio n. 3
0
    def connect_to_dynamips(self, local_port, dynamips, remote_slot,
                            remote_int, remote_port):

        if self.nios.has_key(local_port) and self.nios[local_port] != None:
            debug("%s: port %i has already a UDP connection" %
                  (self.name, local_port))
            return

        #figure out the destionation port according to interface descritors
        debugmsg(
            2,
            "AnyVBoxEmuDevice::connect_to_dynamips(%s, dynamips, dynamips, %s, %s)"
            % (str(local_port), str(remote_int), str(remote_port)))
        #debugmsg(2, "AnyVBoxEmuDevice::connect_to_dynamips()")
        debugmsg(3, "remote_slot.adapter = %s" % str(remote_slot.adapter))
        if remote_slot.adapter in [
                'ETHSW', 'ATMSW', 'ATMBR', 'FRSW', 'Bridge', 'Hub'
        ]:
            # This is a virtual switch that doesn't provide interface descriptors
            dst_port = remote_port
        else:
            # Look at the interfaces dict to find out what the real port is as
            # as far as dynamips is concerned
            try:
                dst_port = remote_slot.interfaces[remote_int][remote_port]
            except KeyError:
                raise DynamipsError, 'invalid interface'

        debugmsg(
            3, "AnyVBoxEmuDevice::connect_to_dynamips()    validate_connect")
        #validate the connection
        if not validate_connect('e', remote_int, self.p, self, local_port,
                                dynamips, remote_slot, remote_port):
            return

        (src_udp, dst_udp) = self.__allocate_udp_port(dynamips)

        debugmsg(3, "self.p.host = %s" % self.p.host)
        debugmsg(3, "dynamips.host = %s" % dynamips.host)
        """ # WARNING: This code crashes on multi-host setups: (when connecting to Dynamips switch)
        if self.p.host == dynamips.host:
            # source and dest adapters are on the same dynamips server, perform loopback binding optimization
            src_ip = '127.0.0.1'
            dst_ip = '127.0.0.1'
        elif (self.p.host == 'localhost' or self.p.host == '127.0.0.1' or self.p.host == '::1') and (dynamips.host == 'localhost' or dynamips.host == '127.0.0.1' or dynamips.host == '::1'):
            # 'localhost', IP: '127.0.0.1' and IPv6 '::1' are equal.
            src_ip = '127.0.0.1'
            dst_ip = '127.0.0.1'
        else:
            # source and dest are on different dynamips servers
            src_ip = self.p.name
            dst_ip = dynamips.host

            #check whether the user did not make a mistake in multi-server .net file
            #if src_ip == 'localhost' or src_ip =='127.0.0.1' or dst_ip =='localhost' or dst_ip == '127.0.0.1':
            #    dowarning('Connecting %s port %s to %s slot %s port %s:\nin case of multi-server operation make sure you do not use "localhost" string in definition of dynamips hypervisor.\n'% (self.name, local_port, remote_slot.router.name, remote_slot.adapter, remote_port))
        """
        src_ip = self.p.name
        dst_ip = dynamips.host
        debugmsg(2, "dynagen_vbox_lib.py: src_ip = %s" % str(src_ip))
        debugmsg(2, "dynagen_vbox_lib.py: dst_ip = %s" % str(dst_ip))
        if src_ip != dst_ip:
            if (self.isLocalhost(src_ip)) or (self.isLocalhost(dst_ip)):
                if (self.isLocalhost(src_ip) is
                        False) or (self.isLocalhost(dst_ip) is False):
                    dowarning(
                        'In case of multi-server operation, make sure you do not use "localhost" or "127.0.0.1" string in definition of dynamips hypervisor. Use actual IP addresses instead.'
                    )
        debugmsg(
            3,
            "dynagen_vbox_lib.py: 'vbox create_udp self.name=%s local_port=%i src_udp=%i dst_ip=%s dst_udp=%i'"
            % (self.name, local_port, src_udp, dst_ip, dst_udp))
        #create the virtualized device side of UDP connection
        send(
            self.p, 'vbox create_udp %s %i %i %s %i' %
            (self.name, local_port, src_udp, dst_ip, dst_udp))
        self.nios[local_port] = UDPConnection(src_udp, dst_ip, dst_udp, self,
                                              local_port)

        #create the dynamips side of UDP connection - the NIO and connect it to the router
        remote_nio = NIO_udp(dynamips, dst_udp, src_ip, src_udp, None,
                             remote_slot, dst_port)

        if isinstance(remote_slot, Bridge):
            # Bridges don't use ports
            remote_slot.nio(nio=remote_nio)
        else:
            remote_slot.nio(port=dst_port, nio=remote_nio)

        #set reverse nios
        remote_nio.reverse_nio = self.nios[local_port]
        self.nios[local_port].reverse_nio = remote_nio
Esempio n. 4
0
def import_config(FILENAME):
    """ Read in the config file and set up the network
    """
    global globalconfig, globaludp, handled, debuglevel
    connectionlist = []  # A list of router connections
    maplist = []  # A list of Frame Relay and ATM switch mappings
    ethswintlist = []  # A list of Ethernet Switch vlan mappings

    # look for configspec in CONFIGSPECPATH and the same directory as dynagen
    realpath = os.path.realpath(sys.argv[0])
    debug('realpath ' + realpath)
    pathname = os.path.dirname(realpath)
    debug('pathname -> ' + pathname)
    CONFIGSPECPATH.append(pathname)
    for dir in CONFIGSPECPATH:
        configspec = dir + '/' + CONFIGSPEC
        debug('configspec -> ' + configspec)

        # Check to see if configuration file exists
        try:
            h = open(FILENAME)
            h.close()
            try:
                config = ConfigObj(FILENAME,
                                   configspec=configspec,
                                   raise_errors=True)
            except SyntaxError as e:
                print("\nError:")
                print(e)
                print(e.line, '\n')
                raw_input("Press ENTER to continue")
                handled = True
                sys.exit(1)

        except IOError:
            #doerror("Can't open configuration file")
            continue

    vtor = Validator()
    res = config.validate(vtor, preserve_errors=True)
    if res == True:
        debug('Passed validation')
    else:
        for entry in flatten_errors(config, res):
            # each entry is a tuple
            section_list, key, error = entry
            if key is not None:
                section_list.append(key)
            else:
                section_list.append('[missing section]')
            section_string = ', '.join(section_list)
            if error == False:
                error = 'Missing value or section.'
            print(section_string, ' = ', error)
        raw_input("Press ENTER to continue")
        handled = True
        sys.exit(1)

    debuglevel = config['debug']
    if debuglevel > 0: setdebug(True)

    globalconfig = config  # Store the config in a global for access by console.py

    if debuglevel >= 3:
        debug("Top-level items:")
        for item in config.scalars:
            debug(item + ' = ' + str(config[item]))

    debug("Dynamips Servers:")
    for section in config.sections:
        server = config[section]
        server.host = server.name
        controlPort = None
        if ':' in server.host:
            # unpack the server and port
            (server.host, controlPort) = server.host.split(':')
        if debuglevel >= 3:
            debug("Server = " + server.name)
            for item in server.scalars:
                debug('  ' + str(item) + ' = ' + str(server[item]))
        try:
            if server['port'] != None:
                controlPort = server['port']
            if controlPort == None:
                controlPort = 7200
            dynamips[server.name] = Dynamips(server.host, int(controlPort))
            # Reset each server
            dynamips[server.name].reset()
        except DynamipsError:
            doerror('Could not connect to server: %s' % server.name)

        if server['udp'] != None:
            udp = server['udp']
        else:
            udp = globaludp
        # Modify the default base UDP NIO port for this server
        try:
            dynamips[server.name].udp = udp
        except DynamipsError:
            doerror('Could not set base UDP NIO port to: "%s" on server: %s' %
                    (server['udp'], server.name))

        if server['workingdir'] == None:
            # If workingdir is not specified, set it to the same directory
            # as the network file

            realpath = os.path.realpath(FILENAME)
            workingdir = os.path.dirname(realpath)
        else:
            workingdir = server['workingdir']

        try:
            # Encase workingdir in quotes to protect spaces
            workingdir = '"' + workingdir + '"'
            dynamips[server.name].workingdir = workingdir
        except DynamipsError:
            doerror('Could not set working directory to: "%s" on server: %s' %
                    (server['workingdir'], server.name))

        # Has the base console port been overridden?
        if server['console'] != None:
            dynamips[server.name].baseconsole = server['console']

        # Devices on this Dynamips server
        devdefaults = {}
        devdefaults['7200'] = {
        }  # A dictionary of the default options and values for 7200 routers on this server
        devdefaults['3620'] = {}  # Defaults for 3620s
        devdefaults['3640'] = {}  # And guess what? Defaults for 3640s
        devdefaults['3660'] = {}  # Does it need to be said?
        devdefaults['2691'] = {}
        devdefaults['3725'] = {}
        devdefaults['3745'] = {}

        # Apply lab global defaults to device defaults
        for model in devdefaults:
            devdefaults[model]['ghostios'] = config['ghostios']
            devdefaults[model]['ghostsize'] = config['ghostsize']
            if config['idlemax'] != None:
                devdefaults[model]['idlemax'] = config['idlemax']
            if config['idlesleep'] != None:
                devdefaults[model]['idlesleep'] = config['idlesleep']

        for subsection in server.sections:
            device = server[subsection]
            # Create the device

            if device.name in DEVICETUPLE:
                debug('Router defaults:')
                # Populate the appropriate dictionary
                for scalar in device.scalars:
                    if device[scalar] != None:
                        devdefaults[device.name][scalar] = device[scalar]
                continue

            debug(device.name)
            # Create the device
            try:
                (devtype, name) = device.name.split(' ')
            except ValueError:
                doerror('Unable to interpret line: "[[' + device.name + ']]"')

            if devtype.lower() == 'router':
                # if model not specifically defined for this router, set it to the default defined in the top level config
                if device['model'] == None:
                    device['model'] = config['model']

                # Note to self: rewrite this blob to be a little smarter and use the Router superclass
                if device['model'] == '7200':
                    dev = C7200(dynamips[server.name], name=name)
                    # Apply the router defaults to this router
                    setdefaults(dev, devdefaults['7200'])
                elif device['model'] == '3620':
                    dev = C3600(dynamips[server.name],
                                chassis=device['model'],
                                name=name)
                    # Apply the router defaults to this router
                    setdefaults(dev, devdefaults['3620'])
                elif device['model'] == '3640':
                    dev = C3600(dynamips[server.name],
                                chassis=device['model'],
                                name=name)
                    # Apply the router defaults to this router
                    setdefaults(dev, devdefaults['3640'])
                elif device['model'] == '3660':
                    dev = C3600(dynamips[server.name],
                                chassis=device['model'],
                                name=name)
                    # Apply the router defaults to this router
                    setdefaults(dev, devdefaults['3660'])
                elif device['model'] == '2691':
                    dev = C2691(dynamips[server.name], name=name)
                    # Apply the router defaults to this router
                    setdefaults(dev, devdefaults['2691'])
                elif device['model'] == '3725':
                    dev = C3725(dynamips[server.name], name=name)
                    # Apply the router defaults to this router
                    setdefaults(dev, devdefaults['3725'])
                elif device['model'] == '3745':
                    dev = C3745(dynamips[server.name], name=name)
                    # Apply the router defaults to this router
                    setdefaults(dev, devdefaults['3745'])

                if device['autostart'] == None:
                    autostart[name] = config['autostart']
                else:
                    autostart[name] = device['autostart']
            elif devtype.lower() == 'frsw':
                dev = FRSW(dynamips[server.name], name=name)
            elif devtype.lower() == 'atmsw':
                dev = ATMSW(dynamips[server.name], name=name)
            elif devtype.lower() == 'ethsw':
                dev = ETHSW(dynamips[server.name], name=name)
            else:
                print('\n***Error: unknown device type:', devtype, '\n')
                raw_input("Press ENTER to continue")
                handled = True
                sys.exit(1)
            devices[name] = dev

            for subitem in device.scalars:
                if device[subitem] != None:
                    debug('  ' + subitem + ' = ' + str(device[subitem]))
                    if setproperty(dev, subitem, device[subitem]):
                        # This was a property that was set.
                        continue
                    else:
                        # Should be either an interface connection or a switch mapping
                        # is it an interface?
                        if interface_re.search(subitem):
                            # Add the tuple to the list of connections to deal with later
                            connectionlist.append(
                                (dev, subitem, device[subitem]))
                        # is it a frame relay or ATM vpi mapping?
                        elif mapint_re.search(subitem) or mapvci_re.search(
                                subitem):
                            # Add the tupple to the list of mappings to deal with later
                            maplist.append((dev, subitem, device[subitem]))
                        # is it an Ethernet switch port configuration?
                        elif ethswint_re.search(subitem):
                            ethswintlist.append(
                                (dev, subitem, device[subitem]))

                        else:
                            debug(
                                '***Warning: ignoring unknown config item: %s %s'
                                % (str(subitem), str(device[subitem])))

    # Establish the connections we collected earlier
    for connection in connectionlist:
        debug('connection: ' + str(connection))
        (router, source, dest) = connection
        try:
            result = connect(router, source, dest)
        except DynamipsError as e:
            err = e[0]
            doerror('Connecting %s %s to %s resulted in \n    %s' %
                    (router.name, source, dest, err))
        if result == False:
            doerror('Attempt to connect %s %s to unknown device: "%s"' %
                    (router.name, source, dest))

    # Apply the switch configuration we collected earlier
    for mapping in maplist:
        debug('mapping: ' + str(mapping))
        (switch, source, dest) = mapping
        switch_map(switch, source, dest)

    for ethswint in ethswintlist:
        debug('ethernet switchport configing: ' + str(ethswint))
        (switch, source, dest) = ethswint

        parameters = len(dest.split(' '))
        if parameters == 2:
            # should be a porttype and a vlan
            (porttype, vlan) = dest.split(' ')
            try:
                switch.set_port(int(source), porttype, int(vlan))
            except DynamipsError as e:
                doerror(e)
            except DynamipsWarning as e:
                dowarning(e)

        elif parameters == 3:
            # Should be a porttype, vlan, and an nio
            (porttype, vlan, nio) = dest.split(' ')
            try:
                (niotype, niostring) = nio.split(':', 1)
            except ValueError:
                doerror('Malformed NETIO in line: ' + str(source) + ' = ' +
                        str(dest))
                return False
            debug('A NETIO: ' + str(nio))
            try:
                #Process the netio
                if niotype.lower() == 'nio_linux_eth':
                    debug('NIO_linux_eth ' + str(dest))
                    switch.nio(int(source),
                               nio=NIO_linux_eth(switch.dynamips,
                                                 interface=niostring),
                               porttype=porttype,
                               vlan=vlan)

                elif niotype.lower() == 'nio_gen_eth':
                    debug('gen_eth ' + str(dest))
                    switch.nio(int(source),
                               nio=NIO_gen_eth(switch.dynamips,
                                               interface=niostring),
                               porttype=porttype,
                               vlan=vlan)

                elif niotype.lower() == 'nio_udp':
                    debug('udp ' + str(dest))
                    (udplocal, remotehost, udpremote) = niostring.split(':', 2)
                    switch.nio(int(source),
                               nio=NIO_udp(switch.dynamips, int(udplocal),
                                           str(remotehost), int(udpremote)),
                               porttype=porttype,
                               vlan=vlan)

                elif niotype.lower() == 'nio_null':
                    debug('nio null')
                    switch.nio(int(source),
                               nio=NIO_null(switch.dynamips),
                               porttype=porttype,
                               vlan=vlan)

                elif niotype.lower() == 'nio_tap':
                    debug('nio tap ' + str(dest))
                    switch.nio(int(source),
                               nio=NIO_tap(switch.dynamips, niostring),
                               porttype=porttype,
                               vlan=vlan)

                elif niotype.lower() == 'nio_unix':
                    debug('unix ' + str(dest))
                    (unixlocal, unixremote) = niostring.split(':', 1)
                    switch.nio(int(source),
                               nio=NIO_unix(switch.dynamips, unixlocal,
                                            unixremote),
                               porttype=porttype,
                               vlan=vlan)

                elif niotype.lower() == 'nio_vde':
                    debug('vde ' + str(dest))
                    (controlsock, localsock) = niostring.split(':', 1)
                    switch.nio(int(source),
                               nio=NIO_vde(switch.dynamips, controlsock,
                                           localsock),
                               porttype=porttype,
                               vlan=vlan)

                else:
                    # Bad NIO
                    doerror(
                        'Invalid NIO in Ethernet switchport config: %s = %s' %
                        (source, dest))

            except DynamipsError as e:
                doerror(e)

        else:
            doerror('Invalid Ethernet switchport config: %s = %s' %
                    (source, dest))
Esempio n. 5
0
def connect(router, source, dest):
    """ Connect a router to something
        router: a router object
        source: a string specifying the local interface
        dest: a string specifying a device and a remote interface, LAN, a raw NIO
    """

    match_obj = interface_re.search(source)
    if not match_obj:
        return False
    (pa1, slot1, port1) = match_obj.group(1, 2, 3)
    slot1 = int(slot1)
    port1 = int(port1)
    try:
        (devname, interface) = dest.split(' ')
    except ValueError:
        # Must be either a NIO or malformed
        if not dest[:4].lower() == 'nio_':
            debug('Malformed destination:' + str(dest))
            return False
        try:
            debug('A NETIO: ' + str(dest))
            (niotype, niostring) = dest.split(':', 1)
        except ValueError:
            debug('Malformed NETIO:' + str(dest))
            return False
        # Process the netio
        if niotype.lower() == 'nio_linux_eth':
            debug('NIO_linux_eth ' + str(dest))
            smartslot(router, pa1, slot1, port1)
            router.slot[slot1].nio(port1,
                                   nio=NIO_linux_eth(router.dynamips,
                                                     interface=niostring))

        elif niotype.lower() == 'nio_gen_eth':
            debug('gen_eth ' + str(dest))
            smartslot(router, pa1, slot1, port1)
            router.slot[slot1].nio(port1,
                                   nio=NIO_gen_eth(router.dynamips,
                                                   interface=niostring))

        elif niotype.lower() == 'nio_udp':
            debug('udp ' + str(dest))
            (udplocal, remotehost, udpremote) = niostring.split(':', 2)
            smartslot(router, pa1, slot1, port1)
            router.slot[slot1].nio(port1,
                                   nio=NIO_udp(router.dynamips, int(udplocal),
                                               str(remotehost),
                                               int(udpremote)))

        elif niotype.lower() == 'nio_null':
            debug('nio null')
            smartslot(router, pa1, slot1, port1)
            router.slot[slot1].nio(port1, nio=NIO_null(router.dynamips))

        elif niotype.lower() == 'nio_tap':
            debug('nio tap ' + str(dest))
            smartslot(router, pa1, slot1, port1)
            router.slot[slot1].nio(port1,
                                   nio=NIO_tap(router.dynamips, niostring))

        elif niotype.lower() == 'nio_unix':
            debug('unix ' + str(dest))
            (unixlocal, unixremote) = niostring.split(':', 1)
            smartslot(router, pa1, slot1, port1)
            router.slot[slot1].nio(port1,
                                   nio=NIO_unix(router.dynamips, unixlocal,
                                                unixremote))

        elif niotype.lower() == 'nio_vde':
            debug('vde ' + str(dest))
            (controlsock, localsock) = niostring.split(':', 1)
            smartslot(router, pa1, slot1, port1)
            router.slot[slot1].nio(port1,
                                   nio=NIO_vde(router.dynamips, controlsock,
                                               localsock))

        else:
            # Bad NIO
            return False
        return True

    match_obj = interface_re.search(interface)
    if match_obj:
        # Connecting to another interface
        (pa2, slot2, port2) = match_obj.group(1, 2, 3)
        slot2 = int(slot2)
        port2 = int(port2)

        # Does the device we are trying to connect to actually exist?
        if not devices.has_key(devname):
            line = router.name + ' ' + source + ' = ' + dest
            doerror('Nonexistant device "' + devname + '" in line: \n ' + line)

        # If interfaces don't exist, create them
        smartslot(router, pa1, slot1, port1)
        smartslot(devices[devname], pa2, slot2, port2)

        router.slot[slot1].connect(port1, devices[devname].dynamips,
                                   devices[devname].slot[slot2], port2)
        return True

    if devname.lower() == 'lan':
        debug('a LAN interface ' + str(dest))
        # If interface doesn't exist, create it
        smartslot(router, pa1, slot1, port1)
        if not bridges.has_key(interface):
            # If this LAN doesn't already exist, create it
            bridges[interface] = Bridge(router.dynamips, name=interface)
        router.slot[slot1].connect(port1, bridges[interface].dynamips,
                                   bridges[interface])
        return True

    match_obj = number_re.search(interface)
    if match_obj:
        port2 = int(interface)
        # Should be a swtich port
        if devname not in devices:
            debug('Unknown device ' + str(devname))
            return False

        debug('a switch port: ' + str(dest))
        # If interface doesn't exist, create it
        smartslot(router, pa1, slot1, port1)
        router.slot[slot1].connect(port1, devices[devname].dynamips,
                                   devices[devname], port2)
        return True

    else:
        # Malformed
        debug('Malformed destination interface: ' + str(dest))
        return False
Esempio n. 6
0
    def connect_to_dynamips(self, local_port, dynamips, remote_slot, remote_int, remote_port):
        #figure out the destionation port according to interface descritors
        debugmsg(2, "AnyEmuDevice::connect_to_dynamips()")
        if remote_slot.adapter in ['ETHSW', 'ATMSW', 'ATMBR', 'FRSW', 'Bridge']:
            # This is a virtual switch that doesn't provide interface descriptors
            dst_port = remote_port
        else:
            # Look at the interfaces dict to find out what the real port is as
            # as far as dynamips is concerned
            try:
                dst_port = remote_slot.interfaces[remote_int][remote_port]
            except KeyError:
                raise DynamipsError, 'invalid interface'

        #validate the connection
        if not validate_connect('e', remote_int, self.p, self, local_port, dynamips, remote_slot, remote_port):
            return

        (src_udp, dst_udp) = self.__allocate_udp_port(dynamips)

        debugmsg(3, "self.p.host = %s" % self.p.host)
        debugmsg(3, "dynamips.host = %s" % dynamips.host)

        """ # WARNING: This code crashes on multi-host setups:
        if self.p.host == dynamips.host:
            # source and dest adapters are on the same dynamips server, perform loopback binding optimization
            src_ip = '127.0.0.1'
            dst_ip = '127.0.0.1'        
        elif (self.p.host == 'localhost' or self.p.host == '127.0.0.1' or self.p.host == '::1') and (dynamips.host == 'localhost' or dynamips.host == '127.0.0.1' or dynamips.host == '::1'):
            # 'localhost', IP: '127.0.0.1' and IPv6 '::1' are equal.
            src_ip = '127.0.0.1'
            dst_ip = '127.0.0.1'
        else:
            # source and dest are on different dynamips servers
            src_ip = self.p.name
            dst_ip = dynamips.host

            #check whether the user did not make a mistake in multi-server .net file
            if src_ip == 'localhost' or src_ip =='127.0.0.1' or dst_ip =='localhost' or dst_ip == '127.0.0.1':
                dowarning('Connecting %s port %s to %s slot %s port %s:\nin case of multi-server operation make sure you do not use "localhost" string in definition of dynamips hypervisor.\n'% (self.name, local_port, remote_slot.router.name, remote_slot.adapter, remote_port))
        """
        src_ip = self.p.name
        dst_ip = dynamips.host
        debugmsg(2, "qemu_lib.py: src_ip = %s" % str(src_ip))
        debugmsg(2, "qemu_lib.py: dst_ip = %s" % str(dst_ip))
        if src_ip != dst_ip:
            if (self.isLocalhost(src_ip)) or (self.isLocalhost(dst_ip)):
                if (self.isLocalhost(src_ip) is False) or (self.isLocalhost(dst_ip) is False):
                    dowarning('In case of multi-server operation, make sure you do not use "localhost" or "127.0.0.1" string in definition of dynamips hypervisor. Use actual IP addresses instead.')
        debugmsg(3, "qemu_lib.py: 'qemu create_udp self.name=%s local_port=%i src_udp=%i dst_ip=%s dst_udp=%i'" % (self.name, local_port, src_udp, dst_ip, dst_udp))
        #create the emulated device side of UDP connection
        send(self.p, 'qemu create_udp %s %i %i %s %i' % (self.name, local_port, src_udp, dst_ip, dst_udp))
        self.nios[local_port] = UDPConnection(src_udp, dst_ip, dst_udp, self, local_port)

        #create the dynamips side of UDP connection - the NIO and connect it to the router
        remote_nio = NIO_udp(dynamips, dst_udp, src_ip, src_udp, None, remote_slot, dst_port)

        if isinstance(remote_slot, Bridge):
            # Bridges don't use ports
            remote_slot.nio(nio=remote_nio)
        else:
            remote_slot.nio(port=dst_port, nio=remote_nio)

        #set reverse nios
        remote_nio.reverse_nio = self.nios[local_port]
        self.nios[local_port].reverse_nio = remote_nio