Ejemplo n.º 1
0
    def save(self, parentConf,        # pylint: disable-msg=W0613
             deviceid, olddeviceid):
        "Save the Configuration to parentConf"
        log.log(6, "Dialup.save")
        conf = parentConf
        for selfkey in self.intkeydict.keys():
            confkey = self.intkeydict[selfkey]
            if hasattr(self, selfkey) and getattr(self, selfkey):
                conf[confkey] = str(getattr(self, selfkey))
            else: del conf[confkey]

        if self.Login != None:
            papconf = getPAPConf()
            chapconf = getCHAPConf()
            # set *
            papconf[self.Login] = str(self.Password)
            chapconf[self.Login] = str(self.Password)
            # set specific auth also
            papconf[[self.Login, 
                     deviceid]] = str(self.Password)
            chapconf[[self.Login, 
                      deviceid]] = str(self.Password)
        if self.DialMode == DM_AUTO:
            parentConf['DEMAND'] = 'yes'
        else:
            parentConf['DEMAND'] = 'no'
        log.log(6, "Dialup.end")
    def register(self, theclass, hwtype=None, subtype=None):
        if not issubclass(theclass, Hardware):
            raise ValueError, "First argument has to be a subclass of Hardware!"

        if not hwtype:
            if hasattr(theclass, "Type"):
                hwtype = theclass.Type
            else:
                return

        if not subtype and hasattr(theclass, "SubType"):
            subtype = theclass.SubType

        if not subtype:
            if self.has_key(hwtype):
                #raise KeyError, "%s is already registered" % hwtype
                log.log(1, "KeyError, %s is already registered" % hwtype)
                return
            else:
                self[hwtype] = {0: theclass}
        else:
            if self.has_key(hwtype) and self[hwtype].has_key(subtype):
                #raise KeyError, "%s.%s is already registered"
                #                % (hwtype, subtype)
                log.log(
                    1,
                    "KeyError %s.%s is already registered" % (hwtype, subtype))
                return
            else:
                if not self.has_key(hwtype):
                    self[hwtype] = {}
                self[hwtype][subtype] = theclass
Ejemplo n.º 3
0
 def __contains__(self, obj):
     obj = os.path.abspath(obj)
     ret = list.__contains__(self, os.path.abspath(obj))
     log.log(
         5,
         "MyFileList.__contains__(self, %s) == %s" % (str(obj), str(ret)))
     return ret
Ejemplo n.º 4
0
    def save(self, parentConf):
        log.log(6, "in Callback.save")
        conf = parentConf

        for selfkey in self.keydict.keys():
            confkey = self.keydict[selfkey]
            if hasattr(self, selfkey):
                conf[confkey] = getattr(self, selfkey)
            else:
                conf[confkey] = ""

        for selfkey in self.intkeydict.keys():
            confkey = self.intkeydict[selfkey]
            if hasattr(self, selfkey):
                conf[confkey] = getattr(self, selfkey)
            else:
                conf[confkey] = ""

        for selfkey in self.boolkeydict.keys():
            confkey = self.boolkeydict[selfkey]
            if hasattr(self, selfkey) and getattr(self, selfkey):
                conf[confkey] = 'on'
            else:
                conf[confkey] = 'off'
        log.log(6, "in Callback.save end")
 def getHardwareClass(self, hwtype, subtype=None):
     if not self.has_key(hwtype):
         log.log(1, "Error: %s not in HardwareFactory!" % hwtype)
         return Hardware
     if subtype and self[type].has_key(subtype):
         return self[hwtype][subtype]
     else:
         return self[hwtype][0]
    def getDeviceClass(self, devtype, subtype=None):
        if not self.has_key(devtype):
            log.log(1, "Error: %s not in DeviceFactory!" % devtype)
            return Device

        if subtype and self[devtype].has_key(subtype):
            return self[devtype][subtype]
        else:
            return self[devtype][0]
Ejemplo n.º 7
0
    def load(self, parentConf, parent):
        "Load the Configuration from the parentConf"
        #print >> sys.stderr, "LOAD Dialup"

        conf = parentConf
        devidstr = parent.DeviceId
        for selfkey in self.intkeydict.keys():
            confkey = self.intkeydict[selfkey]
            if conf.has_key(confkey) and len(conf[confkey]):
                setattr(self, selfkey, int(conf[confkey]))


        if parentConf.has_key('DEMAND'):
            if parentConf['DEMAND'] == 'yes':
                self.DialMode = DM_AUTO
            else:
                self.DialMode = DM_MANUAL

        if self.Login:
            if not hasattr(self, "Password") or self.Password == None:
                self.Password = ""
            log.log(6, "Looking for %s" % self.Login)
            papconf = getPAPConf()
            chapconf = getCHAPConf()
            for conf in [chapconf, papconf]:
                if conf.has_key(self.Login):
                    log.log(6, "Found %s" % conf[self.Login])
                    if conf[self.Login].has_key("*"):
                        self.Password = conf[self.Login]["*"]
                    if conf[self.Login].has_key(devidstr):
                        self.Password = conf[self.Login][devidstr]
                        log.log(6, "Found %s" % self.Password)
                        break
        else:
            log.log(6, "No self.login!!!")
Ejemplo n.º 8
0
    def fromstr(self, vals, value):
        if len(vals) <= 1:
            return
        if vals[0] == "DeviceList":
            del vals[0]
        else:
            return
        for dev in self:
            if dev.DeviceId == vals[1]:
                if dev.Type != vals[0]:
                    self.pop(dev)
                    log.log(1, "Deleting device %s" % vals[1])
                    break
                dev.fromstr(vals[2:], value)  # pylint: disable-msg=W0212
                return

        dev = self.addDeviceType(vals[0])
        dev.DeviceId = vals[1]
        dev.fromstr(vals[2:], value)
 def fromstr(self, vals, value):
     if len(vals) <= 1:
         return
     if vals[0] == "HardwareList":
         del vals[0]
     else:
         return
     for dev in self:
         if dev.Name == vals[1]:
             if dev.Type != vals[0]:
                 self.remove(dev) 
                 log.log(1, "Deleting device %s" % vals[1] )
                 break
             dev.fromstr(vals[2:], value) # pylint: disable-msg=W0212
             return
     log.log(4, "Type = %s, Name = %s" % (vals[0], vals[1]))
     i = self.addHardware(vals[0])
     dev = self[i]
     dev.Name = vals[1]
     dev.fromstr(vals[2:], value)  # pylint: disable-msg=W0212
    def register(self, theclass, devtype=None, subtype=None):

        if devtype == None and hasattr(theclass, "Type"):
            devtype = theclass.Type
        if subtype == None and hasattr(theclass, "SubType"):
            subtype = theclass.SubType

        log.log(5, "Register %s %s" % (str(theclass), str(devtype)))

        if not issubclass(theclass, Device):
            raise ValueError, "first argument has to be a subclass of Device"

        if not subtype:
            if self.has_key(devtype):
                #raise KeyError, "%s is already registered" % devtype
                log.log(1, "KeyError, %s is already registered" % devtype)
                return
            else:
                self[devtype] = {0: theclass}
        else:
            if self.has_key(devtype) and self[devtype].has_key(subtype):
                log.log(
                    1, "KeyError, %s.%s is already registered" %
                    (devtype, subtype))
                return
            else:
                if not self.has_key(devtype):
                    self[devtype] = {}
                self[devtype][subtype] = theclass
Ejemplo n.º 11
0
    def updateFromHal(self, hdellist):
        from netconfpkg import NCBackendHal
        hal = NCBackendHal.NCBackendHal()
        cards = hal.probeCards()
        for hw in cards:
            # if it is already in our HW list do not delete it.
            for h in hdellist:
                if (h.Name == hw.Name 
                    and h.Card.ModuleName == hw.Card.ModuleName):
                    log.log(5, 
                    "Found %s:%s, which is already in our list!" 
                    % (hw.Name, hw.Card.ModuleName))
                    hdellist.remove(h)
                    break
                else:
                    log.log(5, "%s != %s and %s != %s" 
                            % (h.Name, hw.Name, 
                               h.Card.ModuleName, 
                               hw.Card.ModuleName))
            else: 
                for h in self:
                    if(h.Name == hw.Name 
                       and h.Card.ModuleName == hw.Card.ModuleName):
                        break
                    else:
                        log.log(5, "%s != %s and %s != %s" 
                                % (h.Name, hw.Name, 
                                   h.Card.ModuleName, 
                                   hw.Card.ModuleName))
                else:
                    hw.Status = HW_SYSTEM
                    self.append(hw) 
                    hw.setunmodified()        

        return hdellist
Ejemplo n.º 12
0
    def load(self):
        # pylint: disable-msg=W0201

        self.curr_prof = 'default'
        nwconf = ConfShellVar.ConfShellVar(getRoot() + SYSCONFNETWORK)
        if nwconf.has_key('CURRENT_PROFILE'):
            self.curr_prof = nwconf['CURRENT_PROFILE']

        if nwconf.has_key('HOSTNAME'):
            self.use_hostname = nwconf['HOSTNAME']
        else:
            self.use_hostname = 'localhost'

        if self.curr_prof == None or self.curr_prof == '':
            self.curr_prof = 'default'

        updateNetworkScripts()
        self.__delslice__(0, len(self))

        proflist = []
        if os.path.isdir(getRoot() + SYSCONFPROFILEDIR):
            proflist = os.listdir(getRoot() + SYSCONFPROFILEDIR)
            if proflist:
                for pr in proflist:
                    # 60016
                    profdir = getRoot() + SYSCONFPROFILEDIR + '/' + pr
                    if not os.path.isdir(profdir):
                        continue
                    self.loadprof(pr, profdir)
            else:
                self.loadprof('default', None)
        else:
            self.loadprof('default', None)

        prof = self.getActiveProfile()
        log.log(5, "ActiveProfile: %s" % str(prof))
        prof.DNS.Hostname = self.use_hostname
        self.commit()
        self.setunmodified()
Ejemplo n.º 13
0
    def load(self, f=None):

        if not f:
            f = getRoot() + ISDNCARDCONF
        if not os.path.exists(f):
            return -1

        mconf = ConfShellVar.ConfShellVar(filename=f)
        for selfkey in self.keydict.keys():
            confkey = self.keydict[selfkey]
            if mconf.has_key(confkey):
                setattr(self, selfkey, mconf[confkey])

        log.log(5, "RESOURCES=%s" % self.Resources)

        rlist = self.Resources.split(" ")
        for i in rlist:
            log.log(5, "%s" % i)
            if i.find("type=") == 0:
                self.Type = self.get_value(i)
            elif i.find("protocol=") == 0:
                self.ChannelProtocol = self.get_value(i)
            elif i.find("irq=") == 0:
                self.IRQ = self.get_value(i)
            elif i.find("id=") == 0:
                self.DriverId = self.get_value(i)
            elif i.find("io=") == 0 or i.find("io0=") == 0:
                self.IoPort = self.get_value(i)
            elif i.find("io1=") == 0:
                self.IoPort1 = self.get_value(i)
            elif i.find("io2=") == 0:
                self.IoPort2 = self.get_value(i)
            elif i.find("mem=") == 0:
                self.Mem = self.get_value(i)

        if len(rlist) and not self.Type:
            self.Type = '0'

        return 1
Ejemplo n.º 14
0
    def load(self):
        from netconfpkg.NCIPsec import ConfIPsec

        self.__delslice__(0, len(self))

        devices = ConfDevices()
        for ipsec_name in devices:
            conf = ConfIPsec(ipsec_name)
            mtype = None
            # take a peek in the config file
            if conf.has_key("TYPE"):
                mtype = conf["TYPE"]

            if mtype != "IPSEC":
                continue

            log.log(5, "Loading ipsec config %s" % ipsec_name)
            ipsec = IPsec()
            ipsec.load(ipsec_name)
            self.append(ipsec)

        self.commit()
        self.setunmodified()
Ejemplo n.º 15
0
 def append(self, obj):
     obj = os.path.abspath(obj)
     log.log(5, "MyFileList.append(self, %s)" % str(obj))
     return list.append(self, os.path.abspath(obj))
Ejemplo n.º 16
0
    def updateFromSys(self, hdellist):
        modules = getMyConfModules()
        modinfo = getModInfo()            
        #
        # Read in actual system state
        #
        for syspath in glob.glob(getRoot() + '/sys/class/net/*'):
            device = os.path.basename(syspath)
            mod = None
            try:                
                mpath = '%s/device/driver' % syspath
                log.log(5, "Checking %s" % mpath)
                mod = os.path.basename(os.readlink(mpath))
            except:                
                pass

            try:
                fp = open("%s/type" % syspath)
                line = fp.readlines()
                fp.close()
                line = " ".join(line)
                line.strip()
                log.log(5, "type %s = %s" % (device, line))
                mtype = int(line)
                if mtype >= 256:
                    continue
            except:
                pass

            log.log(5, "%s = %s" % (device, mod))
            
            h = None
            for h in self:
                if h.Name == device:
                    break
            # pylint: disable-msg=W0631
            if h and h.Name == device and h.Status != HW_SYSTEM:
                continue

#            if device[:3] != "eth":
#                continue

            # No Alias devices
            if device.find(':') != -1:
                continue

            if mod != None and mod != "":
                # if it is already in our HW list do not delete it.
                for h in hdellist:
                    if h.Name == device and h.Card.ModuleName == mod:
                        log.log(5, "Found %s:%s, which is already in our list!"
                                % (device, mod))
                        hdellist.remove(h)
                        break
                    else:
                        log.log(5, "%s != %s and %s != %s" 
                                % (h.Name, device, 
                                   h.Card.ModuleName, mod))
                else:
                    for h in self:
                        if h.Name == device and h.Card.ModuleName == mod:
                            break
                    else:
                        hwtype = getDeviceType(device, module = mod)
                        i = self.addHardware(hwtype)
                        hw = self[i]
                        hw.Name = device
                        hw.Description = mod
                        hw.Status = HW_SYSTEM
                        hw.Type = hwtype
                        hw.Card = Card()
                        hw.Card.ModuleName = mod
                        if modinfo:
                            for info in modinfo.keys():
                                if info == mod:
                                    if modinfo[info].has_key('description'):
                                        hw.Description = \
                                            modinfo[info]['description']

                        for selfkey, confkey in self.keydict.items():
                            if (modules[hw.Card.ModuleName] and
                                    modules[hw.Card.ModuleName]
                                    ['options'].has_key(confkey)):
                                setattr(hw.Card, selfkey, 
                                        modules[hw.Card.ModuleName]
                                        ['options'][confkey])
                        hw.setunmodified()

        return hdellist
Ejemplo n.º 17
0
                    _("Error removing file %(file)s: %(errormsg)") % {
                        "file": mfile,
                        "errormsg": str(e)
                    })

        # Remove all profile directories except default
        proflist = os.listdir(getRoot() + SYSCONFPROFILEDIR)
        for prof in proflist:
            # Remove all files in the profile directory
            filelist = os.listdir(getRoot() + SYSCONFPROFILEDIR + prof)
            for mfile in filelist:
                filename = getRoot() + SYSCONFPROFILEDIR + prof + '/' + \
                           mfile
                if filename in files_used:
                    # Do not remove used files
                    log.log(6, "%s not removed" % filename)
                    continue
                unlink(filename)

            filename = getRoot() + SYSCONFPROFILEDIR + prof
            if not (filename in files_used):
                rmdir(filename)

        # commit the changes
        self.commit()
        self.setunmodified()

    def activateDevice(self, deviceid, profile, state=None):
        profilelist = getProfileList()

        for prof in profilelist:
Ejemplo n.º 18
0
def main(mcmdline):
    from netconfpkg.NCDeviceList import getDeviceList
    from netconfpkg.NCHardwareList import getHardwareList               
    from netconfpkg.NCIPsecList import getIPsecList
    from netconfpkg.NCProfileList import getProfileList
    from netconfpkg.NC_functions import log

    signal.signal (signal.SIGINT, signal.SIG_DFL)
    class BadUsage(Exception):
        pass

    #progname = os.path.basename(sys.argv[0])
    NC_functions.setVerboseLevel(2)
    NC_functions.setDebugLevel(0)

    do_activate = 0
    switch_profile = 0
    profile = None
    test = 0
    EXPORT = 1
    IMPORT = 2
    SWITCH = 3
    mode = EXPORT
    filename = None
    clear = 0
    chroot = None
    debug = None
    devlists = []

    try:
        opts = getopt.getopt(mcmdline, "asp:?r:dhvtief:co",
                                   [
                                    "activate",
                                    "profile=",
                                    "help",
                                    "devicelist",
                                    "verbose",
                                    "test",
                                    "import",
                                    "export",
                                    "clear",
                                    "root=",
                                    "file=",
                                    "debug",
                                    "hardwarelist",
                                    "ipseclist",
                                    "profilelist"])[0]
        for opt, val in opts:
            if opt == '-r' or opt == '--root':                
                chroot = val
                NC_functions.prepareRoot(chroot)
                NC_functions.updateNetworkScripts()
                continue
    except (getopt.error, BadUsage):
        pass

    try:
        opts = getopt.getopt(mcmdline, "asp:?r:dhvtief:co",
                                   [
                                    "activate",
                                    "profile=",
                                    "help",
                                    "devicelist",
                                    "verbose",
                                    "test",
                                    "import",
                                    "export",
                                    "clear",
                                    "root=",
                                    "file=",
                                    "debug",
                                    "hardwarelist",
                                    "ipseclist",
                                    "profilelist"])[0]
        for opt, val in opts:
            if opt == '-d' or opt == '--devicelist':
                devlists.append(getDeviceList())
                continue

            if opt == '-h' or opt == '--hardwarelist':
                devlists.append(getHardwareList())
                continue

            if opt == '-s' or opt == '--ipseclist':
                devlists.append(getIPsecList())
                continue

            if opt == '-o' or opt == '--profilelist':
                devlists.append(getProfileList())
                continue

            if opt == '-p' or opt == '--profile':
                mode = SWITCH
                switch_profile = 1
                profile = val
                continue

            if opt == '-f' or opt == '--file':
                filename = val
                continue

            if opt == '-r' or opt == '--root':
                # already parsed
                continue

            if opt == '-c' or opt == '--clear':
                clear = 1
                continue

            if opt == '-t' or opt == '--test':
                test = 1
                continue

            if opt == '-a' or opt == '--activate':
                mode = SWITCH
                do_activate = 1
                continue

            if opt == '-i' or opt == '--import':
                mode = IMPORT
                continue

            if opt == '-e' or opt == '--export':
                mode = EXPORT
                continue

            if opt == '-?' or opt == '--help':
                Usage()
                return(0)

            if opt == '-v' or opt == '--verbose':
                NC_functions.setVerboseLevel(NC_functions.getVerboseLevel()+1)
                continue

            if opt == '--debug':
                NC_functions.setDebugLevel(NC_functions.getDebugLevel()+1)
                debug = 1
                continue

            sys.stderr.write(_("Unknown option %s\n" % opt))
            raise BadUsage

    except (getopt.error, BadUsage):
        Usage()
        return(1)

    try:

        if not NC_functions.getDebugLevel():
            log.handler = log.syslog_handler
            log.open()
        else:
            log.handler = log.file_handler
            log.open(sys.stderr)

        if not len(devlists):
            devlists = [getDeviceList(), getHardwareList(),
                        getIPsecList(),
                        getProfileList()]

        if clear:
            for devlist in devlists:
                del devlist[0:len(devlist)]

        if mode == EXPORT:
            for devlist in devlists:
                devstr =  str(devlist)
                if len(devstr):
                    # remove the last \n
                    print devstr[:-1]
            return(0)

        elif mode == IMPORT:
            devlistsdict = {
                "HardwareList" : getHardwareList(),
                "DeviceList" : getDeviceList(),
                "IPsecList" : getIPsecList(),
                "ProfileList" : getProfileList() }

            if filename:
                mfile = open(filename, "r")
            else:
                mfile = sys.stdin

            lines = mfile.readlines()

            for line in lines:
                try:
                    line = line[:-1]
                    log.log(3, "Parsing '%s'\n" % line)
                    vals = line.split("=")
                    if len(vals) <= 1:
                        continue
                    key = vals[0]
                    value = "=".join(vals[1:])

                    vals = key.split(".")
                    if devlistsdict.has_key(vals[0]):
                        # pylint: disable-msg=W0212
                        devlistsdict[vals[0]].fromstr(vals, value)
                    else:
                        sys.stderr.write(_("Unknown List %s\n", vals[0]))
                        raise ParseError

                except Exception, e:
                    pe = ParseError(_("Error parsing line: %s") % line)
                    pe.args += e.args
                    raise pe


            for devlist in devlists:
                log.log(1, "%s" % devlist)
                devlist.save()

            return(0)

        elif test:
            return(0)
Ejemplo n.º 19
0
    def updateFromSystem(self):
        log.log(5, "updateFromSystem")
        
        hdellist = []

        for h in self:
            if h.Status == HW_SYSTEM:
                hdellist.append(h)

        log.log(5, "updateFromHal")
        try:
            hdellist = self.updateFromHal(hdellist)
        except:
            pass
        log.log(5, str(self))

        log.log(5, "updateFromSys")
        try:
            hdellist = self.updateFromSys(hdellist)
        except:
            pass
        log.log(5, str(self))

        for h in hdellist:
            log.log(5, "Removing %s from HWList" % h.Name)
            self.remove(h) 

        del hdellist

        log.log(5, str(self))
Ejemplo n.º 20
0
class DeviceList(Gdtlist):
    gdtlist_properties(Device)

    def load(self):
        from netconfpkg.NCDevice import ConfDevice
        updateNetworkScripts()

        self.__delslice__(0, len(self))

        df = getDeviceFactory()
        devdir = getRoot() + SYSCONFDEVICEDIR
        devices = []

        log.log(5, "Checking %s" % devdir)
        if os.path.isdir(devdir):
            devices = ConfDevices()

        if not devices:
            log.log(5, "Checking %s" % devdir)
            devdir = getRoot() + OLDSYSCONFDEVICEDIR
            devices = ConfDevices(devdir)

        for dev in devices:
            log.log(5, "Checking %s" % dev)
            if dev == 'lo':
                continue
            conf = ConfDevice(dev, devdir)
            mtype = None
            device = None
            # take a peek in the config file
            if conf.has_key("TYPE"):
                mtype = conf["TYPE"]
            if conf.has_key("DEVICE"):
                device = conf["DEVICE"]
            if conf.has_key("NETTYPE"):
                if conf["NETTYPE"] == "qeth":
                    mtype = QETH
                if conf["NETTYPE"] == "lcs":
                    mtype = LCS

            del conf

            if mtype == "IPSEC":
                continue

            if not mtype or mtype == "" or mtype == _("Unknown"):
                from netconfpkg import NCHardwareList
                hwlist = NCHardwareList.getHardwareList()
                for hw in hwlist:
                    if hw.Name == device:
                        mtype = hw.Type
                        break
                else:
                    mtype = getDeviceType(device)

            devclass = df.getDeviceClass(mtype)
            if devclass:
                newdev = devclass()
                newdev.load(dev)
                self.append(newdev)

#                try:
#                    newdev.load(dev)
#                except BaseException, e:
#                    # FIXME: better exception handling
#                    generic_error_dialog (_("Error loading file %s\n%s")
#                                           % (devdir +
#                                               "/ifcfg-" + dev, str(e)),
#                                          dialog_type="error")
#                else:
#                    self.append(newdev)

            else:
                log.log(1, "NO DEVICE CLASS FOUND FOR %s" % dev)
                d = Device()
                self.append(d)
                d.load(dev)

        self.commit()
        self.setunmodified()

        chdev = {}
        # the initscripts do not like '-'
        for dev in self:
            newDeviceId = re.sub('-', '_', dev.DeviceId)
            if newDeviceId != dev.DeviceId:
                chdev[dev.DeviceId] = newDeviceId
                #log.log(4, "%s != %s" % (newDeviceId, dev.DeviceId))
                # Fixed change device names in active list of all profiles
                import netconfpkg.NCProfileList
                profilelist = netconfpkg.NCProfileList.getProfileList()

                for prof in profilelist:
                    #log.log(4, str(prof.ActiveDevices))
                    if dev.DeviceId in prof.ActiveDevices:
                        pos = prof.ActiveDevices.index(dev.DeviceId)
                        prof.ActiveDevices[pos] = newDeviceId
                        #log.log(4, "changed %s" % (prof.ActiveDevices[pos]))
                        #log.log(4, str(prof.ActiveDevices))
                        prof.commit()

                dev.DeviceId = newDeviceId
                dev.commit()
                dev.setunmodified()

        if len(chdev.keys()):
            s = _("Changed the following Nicknames due to the initscripts:\n")
            for n, d in chdev.items():
                s += "%s -> %s\n" % (n, d)
            generic_longinfo_dialog(_("Nicknames changed"), s)

    def addDeviceType(self, mtype):
        df = getDeviceFactory()
        devclass = df.getDeviceClass(mtype)
        if devclass:
            newdev = devclass()
            self.append(newdev)


#        else: # FIXME: !!
#            generic_error_dialog()
        return newdev

    def test(self):
        pass

    def __repr__(self):
        return repr(self.__dict__)

    def tostr(self, prefix_string=None):
        "returns a string in gdt representation"
        #print "tostr %s " % prefix_string
        if prefix_string == None:
            prefix_string = self.__class__.__name__
        mstr = ""
        for value in self:
            if isinstance(value, Device):
                mstr += value.tostr(
                    "%s.%s.%s" % (prefix_string, value.Type, value.DeviceId))
        return mstr

    def fromstr(self, vals, value):
        if len(vals) <= 1:
            return
        if vals[0] == "DeviceList":
            del vals[0]
        else:
            return
        for dev in self:
            if dev.DeviceId == vals[1]:
                if dev.Type != vals[0]:
                    self.pop(dev)
                    log.log(1, "Deleting device %s" % vals[1])
                    break
                dev.fromstr(vals[2:], value)  # pylint: disable-msg=W0212
                return

        dev = self.addDeviceType(vals[0])
        dev.DeviceId = vals[1]
        dev.fromstr(vals[2:], value)

    def save(self):
        # FIXME: [163040] "Exception Occurred" when saving
        # fail gracefully, with informing, which file, and why

        from netconfpkg.NCDevice import ConfDevice
        from types import DictType

        self.commit()

        nwconf = ConfShellVar.ConfShellVar(getRoot() + SYSCONFNETWORK)
        if len(self) > 0:
            nwconf["NETWORKING"] = "yes"
        nwconf.write()

        #
        # clear all Dialer sections in wvdial.conf
        # before the new Dialer sections written
        #
        wvdialconf = ConfSMB.ConfSMB(filename=getRoot() + WVDIALCONF)
        for wvdialkey in wvdialconf.vars.keys():
            if wvdialkey[:6] == 'Dialer':
                del wvdialconf[wvdialkey]
        wvdialconf.write()

        #
        # Clear all pap and chap-secrets generated by netconf
        #
        papconf = getPAPConf()
        chapconf = getCHAPConf()
        for key in papconf.keys():
            if isinstance(papconf[key], DictType):
                for server in papconf[key].keys():
                    papconf.delallitem([key, server])
            del papconf[key]
        for key in chapconf.keys():
            if isinstance(chapconf[key], DictType):
                for server in chapconf[key].keys():
                    chapconf.delallitem([key, server])
            del chapconf[key]

        #
        # traverse all devices in the list
        #
        for dev in self:
            #
            # really save the device
            #
            #if dev.changed:
            dev.save()

        papconf.write()
        chapconf.write()

        dirname = getRoot() + SYSCONFDEVICEDIR
        #
        # Remove old config files
        #
        try:
            mdir = os.listdir(dirname)
        except OSError, msg:
            raise IOError, 'Cannot save in ' \
                  + dirname + ': ' + str(msg)

        for entry in mdir:
            if not testFilename(dirname + entry):
                log.log(5, "not testFilename(%s)" % (dirname + entry))
                continue

            if (len(entry) <= 6) or \
                   entry[:6] != 'ifcfg-':
                log.log(5, "not ifcfg %s" % (entry))
                continue

            devid = entry[6:]
            for dev in self:
                if dev.DeviceId == devid:
                    break
            else:
                # check for IPSEC
                conf = ConfDevice(devid, mdir=dirname)
                mtype = IPSEC
                if conf.has_key("TYPE"):
                    mtype = conf["TYPE"]

                if mtype == IPSEC:
                    log.log(5, "IPSEC %s" % (entry))
                    continue

                # now remove the file
                unlink(dirname + entry)
                unlink(getRoot() + OLDSYSCONFDEVICEDIR + \
                       '/ifcfg-' + devid)

        # remove old route files
        for entry in mdir:
            if not testFilename(dirname + entry):
                continue

            if (len(entry) <= 6) or \
                   entry[:6] != '.route':
                continue

            devid = entry[6:]

            for dev in self:
                if dev.DeviceId == devid:
                    break
            else:
                # remove route file, if no routes defined
                unlink(dirname + entry)
                unlink(getRoot() + OLDSYSCONFDEVICEDIR + \
                       devid + '.route')

        # bug #78043
        # we should have device specific gateways
        # fixed this way, until we have a way to mark the
        # default GATEWAY/GATEWAYDEV
        cfg = ConfShellVar.ConfShellVar(getRoot() + SYSCONFNETWORK)
        if cfg.has_key('GATEWAY'):
            del cfg['GATEWAY']
        # bug #602688: don't remove GATEWAYDEV
        #if cfg.has_key('GATEWAYDEV'):
        #    del cfg['GATEWAYDEV']
        cfg.write()

        self.commit()
        self.setunmodified()
Ejemplo n.º 21
0
    def save(self):
        # FIXME: [163040] "Exception Occurred" when saving
        # fail gracefully, with informing, which file, and why
        import socket
        # Just to be safe...
        os.umask(0022)

        # commit the changes
        self.commit()

        nwconf = ConfShellVar.ConfShellVar(getRoot() + SYSCONFNETWORK)
        # FIXME: [183338] use SEARCH not resolv.conf
        dnsconf = ConfEResolv.ConfEResolv()

        act_prof = self.getActiveProfile()

        if (not getTestEnv()
                and socket.gethostname() != act_prof.DNS.Hostname):
            if os.getuid() == 0:
                # FIXME: [169733] Renaming machine prevents
                # applications from opening, if the hostname changed,
                # set it system wide (#55746)
                retval = generic_yesno_dialog(
                    _("""You changed the hostname.

Should the hostname be set to the system now?
This may have the effect, that some X applications do not function properly.

You may have to relogin."""))
                if retval == RESPONSE_YES:
                    os.system("hostname %s" % act_prof.DNS.Hostname)
                    log.log(2, "change hostname to %s" % act_prof.DNS.Hostname)

            newip = '127.0.0.1'
            try:
                newip = socket.gethostbyname(act_prof.DNS.Hostname)
            except socket.error:
                for host in act_prof.HostsList:
                    if host.IP == '127.0.0.1' or host.IP == "::1":
                        host.Hostname = 'localhost.localdomain'
                        if 'localhost' not in host.AliasList:
                            host.AliasList.append('localhost')
                        # append the hostname to 127.0.0.1,
                        # if it does not contain a domain
                        if act_prof.DNS.Hostname.find(".") != -1:
                            host.AliasList.append(
                                act_prof.DNS.Hostname.split(".")[0])
                        else:
                            host.AliasList.append(act_prof.DNS.Hostname)
            else:
                if newip != "127.0.0.1" and newip != "::1":
                    # We found an IP for the hostname
                    for host in act_prof.HostsList:
                        if host.IP == '127.0.0.1' or host.IP == "::1":
                            # reset localhost
                            host.Hostname = 'localhost.localdomain'
                            if 'localhost' not in host.AliasList:
                                host.AliasList.append('localhost')
                        if host.IP == newip:
                            # found entry in /etc/hosts with our IP
                            # change the entry
                            host.createAliasList()
                            try:
                                hname = socket.gethostbyaddr(newip)
                                host.Hostname = hname[0]
                                host.AliasList.extend(hname[1])
                            except socket.error:
                                host.Hostname = act_prof.DNS.Hostname

                            if host.Hostname != act_prof.DNS.Hostname:
                                host.AliasList.append(act_prof.DNS.Hostname)
                            if act_prof.DNS.Hostname.find(".") != -1:
                                hname = act_prof.DNS.Hostname.split(".")[0]
                                if not hname in host.AliasList:
                                    host.AliasList.append(hname)

            #act_prof.HostsList.commit(changed=False)

        nwconf['HOSTNAME'] = act_prof.DNS.Hostname

        if act_prof.ProfileName != 'default':
            nwconf['CURRENT_PROFILE'] = act_prof.ProfileName
        else:
            del nwconf['CURRENT_PROFILE']

        nwconf.write()

        if not os.path.isdir(getRoot() + SYSCONFPROFILEDIR):
            mkdir(getRoot() + SYSCONFPROFILEDIR)

        files_used = MyFileList()

        for prof in self:
            if not os.path.isdir(getRoot() + SYSCONFPROFILEDIR + '/' +
                                 prof.ProfileName):
                mkdir(getRoot() + SYSCONFPROFILEDIR + '/' + prof.ProfileName)
            files_used.append(getRoot() + SYSCONFPROFILEDIR + '/' +
                              prof.ProfileName)

            nwconf = ConfShellVar.ConfShellVar(getRoot() + SYSCONFPROFILEDIR +
                                               '/' + prof.ProfileName +
                                               '/network')
            #            print >> sys.stderr, "Writing Hostname ",
            #                    prof.ProfileName, prof.DNS.Hostname
            nwconf['HOSTNAME'] = prof.DNS.Hostname
            nwconf.write()
            files_used.append(nwconf.filename)

            # FIXME: [183338] use SEARCH not resolv.conf
            dnsconf.filename = getRoot() + SYSCONFPROFILEDIR + '/' + \
                               prof.ProfileName + '/resolv.conf'

            files_used.append(dnsconf.filename)

            dnsconf['domain'] = ''
            if prof.DNS.Domainname:
                dnsconf['domain'] = [prof.DNS.Domainname]
            else:
                del dnsconf['domain']

            dnsconf['search'] = []
            if prof.DNS.SearchList != []:
                dnsconf['search'] = prof.DNS.SearchList
            else:
                del dnsconf['search']

            dnsconf['nameservers'] = []
            nameservers = []
            if prof.DNS.PrimaryDNS:
                nameservers.append(prof.DNS.PrimaryDNS)
            if prof.DNS.SecondaryDNS:
                nameservers.append(prof.DNS.SecondaryDNS)
            if prof.DNS.TertiaryDNS:
                nameservers.append(prof.DNS.TertiaryDNS)

            dnsconf['nameservers'] = nameservers
            # CHECK: [198898] new backend for /etc/hosts
            filename = getRoot() + \
                SYSCONFPROFILEDIR + '/' + \
                prof.ProfileName + \
                '/hosts'
            prof.HostsList.save(filename=filename)
            files_used.append(filename)

            dnsconf.write()

            for devId in prof.ActiveDevices:
                for prefix in ['ifcfg-', 'route-', 'keys-']:
                    devfilename = getRoot() + SYSCONFDEVICEDIR + \
                                  prefix + devId
                    profilename = getRoot() + SYSCONFPROFILEDIR + '/' + \
                                  prof.ProfileName + '/' + prefix + devId

                    if os.path.isfile(devfilename):
                        if not issamefile(devfilename, profilename):
                            unlink(profilename)
                            link(devfilename, profilename)

                        files_used.append(devfilename)
                        files_used.append(profilename)

                # unlink old .route files
                profilename = getRoot() + SYSCONFPROFILEDIR + '/' + \
                              prof.ProfileName + '/' + devId + '.route'
                unlink(profilename)

                if prof.Active == False and prof.ProfileName != 'default':
                    continue

                # Active Profile or default profile
                for prefix in ['ifcfg-', 'route-', 'keys-']:
                    devfilename = getRoot() + SYSCONFDEVICEDIR + \
                                      '/' + prefix + devId
                    profilename = getRoot() + OLDSYSCONFDEVICEDIR + \
                                  '/' + prefix + devId

                    if os.path.isfile(devfilename):
                        if not issamefile(devfilename, profilename):
                            unlink(profilename)
                            link(devfilename, profilename)
                        files_used.append(profilename)

                # unlink old .route files
                unlink(getRoot() + OLDSYSCONFDEVICEDIR + \
                       '/' + devId + '.route')

            for devId in prof.ActiveIPsecs:
                for prefix in ['ifcfg-', 'keys-']:
                    devfilename = getRoot() + SYSCONFDEVICEDIR + \
                                  prefix + devId
                    profilename = getRoot() + SYSCONFPROFILEDIR + '/' + \
                                  prof.ProfileName + '/' + prefix + devId

                    if os.path.isfile(devfilename):
                        if not issamefile(devfilename, profilename):
                            unlink(profilename)
                            link(devfilename, profilename)

                        files_used.append(devfilename)
                        files_used.append(profilename)

                if prof.Active == False and prof.ProfileName != 'default':
                    continue

                # Active Profile or default profile
                for prefix in ['ifcfg-', 'keys-']:
                    devfilename = getRoot() + SYSCONFDEVICEDIR + \
                                      '/' + prefix + devId
                    profilename = getRoot() + OLDSYSCONFDEVICEDIR + \
                                  '/' + prefix + devId

                    if os.path.isfile(devfilename):
                        if not issamefile(devfilename, profilename):
                            unlink(profilename)
                            link(devfilename, profilename)

                        files_used.append(profilename)

            if prof.Active == False:
                continue

            # Special actions for the active profile

            for (mfile, cfile) in {
                    RESOLVCONF: '/resolv.conf',
                    HOSTSCONF: '/hosts'
            }.items():
                hostfile = getRoot() + mfile
                conffile = getRoot() + SYSCONFPROFILEDIR + '/' + \
                           prof.ProfileName + cfile
                if (os.path.isfile(conffile)
                        and (not os.path.isfile(hostfile)
                             or not issamefile(hostfile, conffile))):
                    rename(hostfile, hostfile + '.bak')
                    unlink(hostfile)
                    link(conffile, hostfile)

                os.chmod(hostfile, 0644)

        # Remove all unused files that are linked in the device directory
        devlist = os.listdir(getRoot() + OLDSYSCONFDEVICEDIR)
        for dev in devlist:
            if dev.split('-')[0] not in [ 'ifcfg', 'route',
                                                  'keys' ] or \
                                                  (len(dev) > 6 and \
                                                   dev[-6:] == '.route') \
                                                  or dev == 'ifcfg-lo':
                continue
            mfile = getRoot() + OLDSYSCONFDEVICEDIR + '/' + dev
            if mfile in files_used:
                # Do not remove used files
                continue
            try:
                stat = os.stat(mfile)
                if stat[3] > 1:
                    # Check, if it is a device of neat
                    # in every profile directory
                    dirlist = os.listdir(getRoot() + SYSCONFPROFILEDIR)
                    for mdir in dirlist:
                        dirname = getRoot() + SYSCONFPROFILEDIR + '/' + mdir
                        if not os.path.isdir(dirname):
                            continue
                        filelist = os.listdir(dirname)
                        for file2 in filelist:
                            stat2 = os.stat(dirname + '/' + file2)
                            if os.path.samestat(stat, stat2):
                                unlink(mfile)
            except OSError, e:
                generic_error_dialog(
                    _("Error removing file %(file)s: %(errormsg)") % {
                        "file": mfile,
                        "errormsg": str(e)
                    })
Ejemplo n.º 22
0
    def load(self):
        from netconfpkg.NCDevice import ConfDevice
        updateNetworkScripts()

        self.__delslice__(0, len(self))

        df = getDeviceFactory()
        devdir = getRoot() + SYSCONFDEVICEDIR
        devices = []

        log.log(5, "Checking %s" % devdir)
        if os.path.isdir(devdir):
            devices = ConfDevices()

        if not devices:
            log.log(5, "Checking %s" % devdir)
            devdir = getRoot() + OLDSYSCONFDEVICEDIR
            devices = ConfDevices(devdir)

        for dev in devices:
            log.log(5, "Checking %s" % dev)
            if dev == 'lo':
                continue
            conf = ConfDevice(dev, devdir)
            mtype = None
            device = None
            # take a peek in the config file
            if conf.has_key("TYPE"):
                mtype = conf["TYPE"]
            if conf.has_key("DEVICE"):
                device = conf["DEVICE"]
            if conf.has_key("NETTYPE"):
                if conf["NETTYPE"] == "qeth":
                    mtype = QETH
                if conf["NETTYPE"] == "lcs":
                    mtype = LCS

            del conf

            if mtype == "IPSEC":
                continue

            if not mtype or mtype == "" or mtype == _("Unknown"):
                from netconfpkg import NCHardwareList
                hwlist = NCHardwareList.getHardwareList()
                for hw in hwlist:
                    if hw.Name == device:
                        mtype = hw.Type
                        break
                else:
                    mtype = getDeviceType(device)

            devclass = df.getDeviceClass(mtype)
            if devclass:
                newdev = devclass()
                newdev.load(dev)
                self.append(newdev)

#                try:
#                    newdev.load(dev)
#                except BaseException, e:
#                    # FIXME: better exception handling
#                    generic_error_dialog (_("Error loading file %s\n%s")
#                                           % (devdir +
#                                               "/ifcfg-" + dev, str(e)),
#                                          dialog_type="error")
#                else:
#                    self.append(newdev)

            else:
                log.log(1, "NO DEVICE CLASS FOUND FOR %s" % dev)
                d = Device()
                self.append(d)
                d.load(dev)

        self.commit()
        self.setunmodified()

        chdev = {}
        # the initscripts do not like '-'
        for dev in self:
            newDeviceId = re.sub('-', '_', dev.DeviceId)
            if newDeviceId != dev.DeviceId:
                chdev[dev.DeviceId] = newDeviceId
                #log.log(4, "%s != %s" % (newDeviceId, dev.DeviceId))
                # Fixed change device names in active list of all profiles
                import netconfpkg.NCProfileList
                profilelist = netconfpkg.NCProfileList.getProfileList()

                for prof in profilelist:
                    #log.log(4, str(prof.ActiveDevices))
                    if dev.DeviceId in prof.ActiveDevices:
                        pos = prof.ActiveDevices.index(dev.DeviceId)
                        prof.ActiveDevices[pos] = newDeviceId
                        #log.log(4, "changed %s" % (prof.ActiveDevices[pos]))
                        #log.log(4, str(prof.ActiveDevices))
                        prof.commit()

                dev.DeviceId = newDeviceId
                dev.commit()
                dev.setunmodified()

        if len(chdev.keys()):
            s = _("Changed the following Nicknames due to the initscripts:\n")
            for n, d in chdev.items():
                s += "%s -> %s\n" % (n, d)
            generic_longinfo_dialog(_("Nicknames changed"), s)
Ejemplo n.º 23
0
 def __setitem__(self, key, value):
     value = os.path.abspath(value)
     log.log(
         5, "MyFileList.__setitem__(self, %s, %s)" % (str(key), str(value)))
     return list.__setitem__(self, key, value)
Ejemplo n.º 24
0
                devlist.save()

            return(0)

        elif test:
            return(0)

        elif mode == SWITCH:
            ret = None
            profilelist = getProfileList()
            actdev = Control.NetworkDevice()
            actdev.load()
            aprof = profilelist.getActiveProfile()

            if switch_profile and aprof.ProfileName != profile:
                log.log(1, "Switching to profile %s" % profile)
                if do_activate:
                    for p in profilelist:
                        if p.ProfileName == profile:
                            aprof = p
                            break
                    for device in getDeviceList():
                        if device.DeviceId not in aprof.ActiveDevices:
                            if actdev.find(device.Device):
                                (ret, msg) = device.deactivate()
                                if ret:
                                    print msg
                profilelist.switchToProfile(profile)
                profilelist.save()

            actdev.load()
Ejemplo n.º 25
0
    def save(self, parentConf, devidstr, olddeviceid):
        "Save the Configuration to parentConf"
        log.log(6, "IsdnDialup.save")
        Dialup.save(self, parentConf, devidstr, olddeviceid)
        conf = parentConf
        
        for selfkey in self.keydict.keys():
            confkey = self.keydict[selfkey]
            if hasattr(self, selfkey) and getattr(self, selfkey) != None:
                conf[confkey] = getattr(self, selfkey)
            else: conf[confkey] = ""

        for selfkey in self.intkeydict.keys():
            confkey = self.intkeydict[selfkey]
            if hasattr(self, selfkey) and getattr(self, selfkey) != None:
                conf[confkey] = str(getattr(self, selfkey))
            else: conf[confkey] = ""

        for selfkey in self.boolkeydict.keys():
            confkey = self.boolkeydict[selfkey]
            if hasattr(self, selfkey) and getattr(self, selfkey) == True:
                conf[confkey] = 'on'
            else:
                conf[confkey] = 'off'

        if self.DefRoute:
            conf['DEFROUTE'] = 'yes'
        else:
            conf['DEFROUTE'] = 'no'

        if conf.has_key('PEERDNS') and conf['PEERDNS'] == "yes":
            if conf['DNS1']: 
                del conf['DNS1']
            if conf['DNS2']: 
                del conf['DNS2']

        if self.PPPOptions:
            opt = ""
            for val in self.PPPOptions:
                if opt != "": 
                    opt = opt + ' '
                opt = opt + val
            conf['PPPOPTIONS'] = opt
        else:
            del conf['PPPOPTIONS']

        #parent = self.getParent()

        if conf.has_key('LOCAL_IP'):
            del conf['LOCAL_IP']
        if conf.has_key('REMOTE_IP'):
            del conf['REMOTE_IP']
        if conf.has_key('BOOT'):
            del conf['BOOT']

        if conf.has_key('PASSWORD'):
            del conf['PASSWORD']

        if self.Compression:
            self.Compression.save(conf)

        log.log(6, "Callback.save")

        if self.Callback: 
            conf['CALLBACK'] = self.Callback.Type
            self.Callback.save(conf)
        else:
            conf['CALLBACK'] = 'off'
            
        if conf['CALLBACK'] == 'off':
            for key in ['CBHUP', 'CBDELAY', 'CBCP', 'CBCP_MSN']:
                if conf.has_key(key):
                    del conf[key]

        for i in conf.keys():
            if not conf[i]: 
                del conf[i]

        if not conf.has_key('PEERDNS'):
            conf['PEERDNS'] = "no"

        conf.write()
        log.log(6, "IsdnDialup.save end")