def initvars(self): self.vars = {} if not os.access(getRoot() + HWCONF, os.R_OK): return fp = open(getRoot() + HWCONF, 'r') hwlist = fp.read() hwlist = hwlist.split("-\n") pos = 0 for hw in hwlist: if not len(hw): continue items = hw.split('\n') hwdict = {} for item in items: if not len(item): continue vals = item.split(":") if len(vals) <= 1: # skip over bad/malformed lines continue # Some of the first words are used as dict keys server side # so this just helps make that easier strippedstring = vals[1].strip() vals[1] = strippedstring hwdict[vals[0]] = " ".join(vals[1:]) self.vars[pos] = hwdict pos = pos + 1
def getDeviceList(refresh=None): # pylint: disable-msg=W0603 global __DVList global __DVList_root if __DVList == None or refresh or \ __DVList_root != getRoot(): __DVList = DeviceList() __DVList.load() __DVList_root = getRoot() return __DVList
def getMyConfModules(refresh = None): # pylint: disable-msg=W0603 global _MyConfModules global _MyConfModules_root if _MyConfModules == None or refresh or \ _MyConfModules_root != getRoot() : _MyConfModules = MyConfModules() _MyConfModules_root = getRoot() return _MyConfModules
def getHardwareList(refresh = None): # pylint: disable-msg=W0603 global __HWList global __HWList_root if __HWList == None or refresh or \ __HWList_root != getRoot(): __HWList = HardwareList() __HWList.load() __HWList_root = getRoot() return __HWList
def getMyWvDial(create_if_missing = None): # pylint: disable-msg=W0603 global _MyWvDial global _MyWvDial_root if _MyWvDial == None or _MyWvDial_root != getRoot(): _MyWvDial = ConfSMB(getRoot() + WVDIALCONF, create_if_missing = create_if_missing) _MyWvDial_root = getRoot() return _MyWvDial
def __init__(self, filename = None): # if we put getRoot() in the default parameter it will # have the value at parsing time if filename == None: filename = getRoot() + MODULESCONF # FIXME: [187640] Support aliases in /etc/modprobe.d/ ConfModules.__init__(self, filename)
def cleanup(self, f=None): if f == None: f = getRoot() + ISDNCARDCONF # we only support 1 ISDN card in this version if not self.Description: if os.path.exists(f): os.unlink(f) return
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()
def save(self, f=None): if f == None: f = getRoot() + ISDNCARDCONF # we only support 1 ISDN card in this version if not self.Description: if os.path.exists(f): os.unlink(f) return conf = ConfShellVar.ConfShellVar(filename=f) rs = "" if self.Type: rs = rs + "protocol=" + str(self.ChannelProtocol) if self.Type == '0': pass else: rs = rs + " type=" + str(self.Type) if self.IRQ: rs = rs + " irq=" + str(self.IRQ) if self.DriverId: rs = rs + " id=" + str(self.DriverId) if self.IoPort: if (self.Type == "4" or self.Type == "19" or self.Type == "24"): rs = rs + " io0=" + str(self.IoPort) else: rs = rs + " io=" + str(self.IoPort) if self.IoPort1: rs = rs + " io1=" + str(self.IoPort1) if self.IoPort2: rs = rs + " io2=" + str(self.IoPort2) if self.Mem: rs = rs + " mem=" + str(self.Mem) else: rs = rs + "NONE" self.Resources = rs for selfkey in self.keydict.keys(): confkey = self.keydict[selfkey] if hasattr(self, selfkey): conf[confkey] = getattr(self, selfkey) else: conf[confkey] = "" conf.write()
def save(self): from netconfpkg.NCIPsec import ConfIPsec for ipsec in self: ipsec.save() self.commit() dirname = getRoot() + SYSCONFDEVICEDIR # # Remove old config files # try: mdir = os.listdir(dirname) except OSError, msg: raise IOError, 'Cannot save in ' \ + dirname + ': ' + str(msg)
def write_wvdial(self, devname, sectname): "Write the wvdial section" conf = ConfSMB.ConfSMB(filename=getRoot() + WVDIALCONF) conf.chmod(0600) if not conf.has_key(sectname): conf[sectname] = ConfSMB.ConfSMBSubDict(conf, sectname) for selfkey in self.wvdict.keys(): confkey = self.wvdict[selfkey] if hasattr(self, selfkey) and getattr(self, selfkey) != None: conf[sectname][confkey] = str(getattr(self, selfkey)) elif conf[sectname].has_key(confkey): del conf[sectname][confkey] for selfkey in self.boolwvdict.keys(): confkey = self.boolwvdict[selfkey] if hasattr(self, selfkey) and getattr(self, selfkey): conf[sectname][confkey] = '1' # FIXME: [177931] Stupid Mode goes away in /etc/wvdial.conf # when a dialup connection is saved else: conf[sectname][confkey] = '0' # # Write Modem Init strings # if conf[sectname].has_key('Init'): del conf[sectname]['Init'] if not conf[sectname].has_key('Init1'): conf[sectname]['Init1'] = 'ATZ' # # Better not be smarter than the user # #if not conf[sectname].has_key('Init2'): # conf[sectname]['Init2'] = 'ATQ0 V1 E1 S0=0 &C1 &D2' if self.InitString: conf[sectname]['Init3'] = str(self.InitString) #else: del conf[sectname]['Init3'] conf[sectname]['Inherits'] = devname for i in conf.keys(): if not conf[i]: del conf[i] conf.write()
def loadprof(self, pr, profdir): devicelist = NCDeviceList.getDeviceList() ipseclist = NCIPsecList.getIPsecList() prof = Profile() self.append(prof) prof.ProfileName = pr if pr == self.curr_prof: prof.Active = True else: prof.Active = False devlist = [] if profdir: devlist = ConfDevices(profdir) if not devlist: devlist = ConfDevices(getRoot() + OLDSYSCONFDEVICEDIR) for dev in devlist: for d in devicelist: if d.DeviceId == dev: #print >> sys.stderr, "Appending ", d.DeviceId, dev prof.ActiveDevices.append(dev) break for ipsec in devlist: for d in ipseclist: if d.IPsecId == ipsec: prof.ActiveIPsecs.append(ipsec) break # CHECK: [198898] new backend for /etc/hosts if profdir: try: prof.HostsList.load(filename=profdir + '/hosts') except ValueError, e: self.error = str(e)
def __init__(self, name, mdir=None): if mdir == None: mdir = getRoot() + SYSCONFDEVICEDIR new = False self.filename = mdir + 'ifcfg-' + name if not os.access(self.filename, os.R_OK): new = True self.oldmode = 0644 else: status = os.stat(self.filename) self.oldmode = status[0] #print status ConfShellVar.ConfShellVar.__init__(self, self.filename) if new: self.rewind() self.insertline("# Please read /usr/share/doc/" "initscripts-*/sysconfig.txt") self.nextline() self.insertline("# for the documentation of these parameters.") self.rewind()
def write_peers(self, deviceid, olddeviceid, name): # Write /etc/ppp/peers/DeviceId # bug #77763 peerdir = getRoot() + PPPDIR + "/peers/" if not os.path.isdir(peerdir): mkdir(peerdir) if olddeviceid and (olddeviceid != deviceid): unlink(peerdir + olddeviceid) filename = peerdir + deviceid try: mfile = open(filename, "w") line = str('connect "/usr/bin/wvdial --remotename ' '%s --chat \'%s\'"' % (deviceid, name)) mfile.write(line + '\n') log.lch(2, filename, line) mfile.close() except KeyError: pass
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
def __init__(self): glade_file = 'neat-control.glade' if not os.path.isfile(glade_file): glade_file = GLADEPATH + glade_file if not os.path.isfile(glade_file): glade_file = NETCONFDIR + glade_file self.isRoot = False self.no_profileentry_update = False if os.access(getRoot() + "/", os.W_OK): self.isRoot = True self.xml = glade.XML(glade_file, None, domain=PROGNAME) xml_signal_autoconnect(self.xml, { 'on_closeButton_clicked' : self.on_closeButton_clicked, 'on_infoButton_clicked' : self.on_infoButton_clicked, 'on_activateButton_clicked' : self.on_activateButton_clicked, 'on_deactivateButton_clicked' : self.on_deactivateButton_clicked, 'on_configureButton_clicked' : self.on_configureButton_clicked, 'on_monitorButton_clicked' : self.on_monitorButton_clicked, 'on_profileActivateButton_clicked' : \ self.on_profileActivateButton_clicked, # 'on_autoSelectProfileButton_clicked' : \ # self.on_autoSelectProfileButton_clicked, 'on_interfaceClist_select_row' : (\ self.on_generic_clist_select_row, self.xml.get_widget('activateButton'), self.xml.get_widget('deactivateButton'), self.xml.get_widget('editButtonbutton'), self.xml.get_widget('monitorButton')), }) self.dialog = self.xml.get_widget('mainWindow') self.dialog.connect('delete-event', self.on_Dialog_delete_event) self.dialog.connect('hide', gtk.main_quit) self.on_xpm, self.on_mask = get_icon('on.xpm') self.off_xpm, self.off_mask = get_icon('off.xpm') if not os.access('/usr/bin/rp3', os.X_OK): self.xml.get_widget('monitorButton').hide() load_icon('neat-control.xpm', self.dialog) pix = self.xml.get_widget('pixmap') pix.set_from_pixbuf(get_pixbuf('neat-control-logo.png')) clist = self.xml.get_widget('interfaceClist') clist.column_titles_passive() self.devicelist = self.getProfDeviceList() self.activedevicelist = NetworkDevice().get() self.hydrate() self.oldprofile = None self.xml.get_widget('profileActivateButton').set_sensitive(False) self.hydrateProfiles() self.xml.get_widget('autoSelectProfileButton').hide() self.tag = gobject.timeout_add(4000, self.update_dialog) # Let this dialog be in the taskbar like a normal window self.dialog.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_NORMAL) self.dialog.show()
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 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
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()
try: prof.HostsList.load(filename=profdir + '/hosts') except ValueError, e: self.error = str(e) else: try: prof.HostsList.load(filename=HOSTSCONF) except ValueError, e: self.error = str(e) # FIXME: [183338] use SEARCH not resolv.conf dnsconf = ConfEResolv.ConfEResolv() if profdir: dnsconf.filename = profdir + '/resolv.conf' else: dnsconf.filename = getRoot() + RESOLVCONF dnsconf.read() prof.DNS.Hostname = self.use_hostname prof.DNS.Domainname = '' prof.DNS.PrimaryDNS = '' prof.DNS.SecondaryDNS = '' prof.DNS.TertiaryDNS = '' if profdir: nwconf = ConfShellVar.ConfShellVar(profdir + '/network') else: nwconf = ConfShellVar.ConfShellVar(getRoot() + SYSCONFNETWORK) if nwconf['HOSTNAME'] != '': prof.DNS.Hostname = nwconf['HOSTNAME'] if len(dnsconf['domain']) > 0:
def load(self, name): conf = ConfDevice(name) self.oldname = name if not conf.has_key("DEVICE"): aliaspos = name.find(':') if aliaspos != -1: from netconfpkg.NCDeviceList import getDeviceList # ok, we have to inherit all other data from our master for dev in getDeviceList(): if dev.Device == name[:aliaspos]: self.apply(dev) break self.Device = name self.DeviceId = name for selfkey in self.__keydict.keys(): confkey = self.__keydict[selfkey] if conf.has_key(confkey) and conf[confkey]: setattr(self, selfkey, conf[confkey]) else: # if confkey is for example IPADDR, we should try also IPADDR0, IPADDR1 etc. if confkey in self.__keydictn: for i in range(10): confkeyn = confkey + str(i) if conf.has_key(confkeyn) and len(conf[confkeyn]): setattr(self, selfkey, conf[confkeyn]) break for selfkey in self.__intkeydict.keys(): confkey = self.__intkeydict[selfkey] if conf.has_key(confkey) and len(conf[confkey]): setattr(self, selfkey, conf[confkey]) else: if confkey in self.__intkeydictn: for i in range(10): confkeyn = confkey + str(i) if conf.has_key(confkeyn) and len(conf[confkeyn]): setattr(self, selfkey, conf[confkeyn]) break for selfkey in self.__boolkeydict.keys(): confkey = self.__boolkeydict[selfkey] if conf.has_key(confkey): if conf[confkey] == 'yes': setattr(self, selfkey, True) #print >> sys.stderr, self.DeviceId, selfkey, "True" #setattr(self, selfkey, True) else: setattr(self, selfkey, False) #print >> sys.stderr, self.DeviceId, selfkey, "False" #setattr(self, selfkey, False) # we need to deal with options which have default value 'yes' like NM_CONTROLLED else: if confkey != "NM_CONTROLLED": setattr(self, selfkey, False) #setattr(self, selfkey, False) # if PREFIX exists it takes preference over NETMASK if hasattr(self, 'Prefix') and len(self.Prefix): prefix = int(self.Prefix) if prefix >= 0 and prefix <= 32: netmask_str = socket.inet_ntoa( struct.pack(">I", 0xFFFFFFFF & (0xFFFFFFFF << (32 - prefix)))) self.Netmask = netmask_str if not conf.has_key("PEERDNS"): del self.AutoDNS if not self.Slave: del self.Slave if not self.Gateway: try: cfg = ConfShellVar.ConfShellVar(getRoot() + SYSCONFNETWORK) if (cfg.has_key('GATEWAY') and ((not cfg.has_key('GATEWAYDEV')) or cfg['GATEWAYDEV'] == self.Device)): gw = cfg['GATEWAY'] if gw and self.Netmask: try: network = commands.getoutput('ipcalc --network ' + str(self.IP) + ' ' + str(self.Netmask) + ' 2>/dev/null') out = commands.getoutput('ipcalc --network ' + str(gw) + ' ' + str(self.Netmask) + ' 2>/dev/null') if out == network: self.Gateway = str(gw) except: pass except EnvironmentError, msg: NC_functions.generic_error_dialog(str(msg))
def load(self): #hwconf = ConfHWConf() # first clear the list self.__delslice__(0, len(self)) # FIXME: move HW detection to NCDev* dosysupdate = True if getTestEnv(): dosysupdate = False if dosysupdate: self.updateFromSystem() self.updateFromModules() for hw in self: if hw.Name == "ISDN Card 0": break else: # # XXX FIXME... this is not OO # isdncard = NCisdnhardware.ConfISDN() if isdncard.load() > 0: i = self.addHardware(ISDN) hw = self[i] hw.Name = "ISDN Card 0" hw.Description = isdncard.Description hw.Type = ISDN hw.Status = HW_CONF hw.Card = Card() hw.Card.ModuleName = isdncard.ModuleName hw.Card.Type = isdncard.Type hw.Card.IoPort = isdncard.IoPort hw.Card.IoPort1 = isdncard.IoPort1 hw.Card.IoPort2 = isdncard.IoPort2 hw.Card.Mem = isdncard.Mem hw.Card.IRQ = isdncard.IRQ hw.Card.ChannelProtocol = isdncard.ChannelProtocol hw.Card.Firmware = isdncard.Firmware hw.Card.DriverId = isdncard.DriverId hw.Card.VendorId = isdncard.VendorId hw.Card.DeviceId = isdncard.DeviceId # # FIXME: This is not OO! # try: wvdial = ConfSMB(getRoot() + WVDIALCONF) except FileMissing: pass else: for dev in wvdial.keys(): if dev[:5] != 'Modem': continue i = self.addHardware(MODEM) hw = self[i] hw.Name = dev hw.Description = 'Generic Modem' hw.Type = MODEM hw.Status = HW_CONF hw.createModem() if not wvdial[dev].has_key('Modem'): wvdial[dev]['Modem'] = '/dev/modem' hw.Modem.DeviceName = wvdial[dev]['Modem'] if not wvdial[dev].has_key('Baud'): wvdial[dev]['Baud'] = '38400' try: hw.Modem.BaudRate = int(wvdial[dev]['Baud']) except ValueError: hw.Modem.BaudRate = 38400 if not wvdial[dev].has_key('SetVolume'): wvdial[dev]['SetVolume'] = '0' hw.Modem.ModemVolume = int(wvdial[dev]['SetVolume']) if not wvdial[dev].has_key('Dial Command'): wvdial[dev]['Dial Command'] = 'ATDT' hw.Modem.DialCommand = wvdial[dev]['Dial Command'] if not wvdial[dev].has_key('Init1'): wvdial[dev]['Init1'] = 'ATZ' hw.Modem.InitString = wvdial[dev]['Init1'] if not wvdial[dev].has_key('FlowControl'): wvdial[dev]['FlowControl'] = CRTSCTS hw.Modem.FlowControl = wvdial[dev]['FlowControl'] self.commit() self.setunmodified()
class IPsecList(IPsecList_base): def __init__(self): super(IPsecList, self).__init__() self.oldname = None 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() def save(self): from netconfpkg.NCIPsec import ConfIPsec for ipsec in self: ipsec.save() self.commit() 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): continue if (len(entry) <= 6) or \ entry[:6] != 'ifcfg-': continue ipsecid = entry[6:] for ipsec in self: if ipsec.IPsecId == ipsecid: break else: # check for IPSEC conf = ConfIPsec(ipsecid) mtype = None if conf.has_key("TYPE"): mtype = conf["TYPE"] if mtype != IPSEC: continue unlink(dirname + entry) unlink(getRoot() + OLDSYSCONFDEVICEDIR + \ '/ifcfg-' + ipsecid) # # Remove old key files # try: mdir = os.listdir(dirname) except OSError, msg: raise IOError, 'Cannot save in ' \ + dirname + ': ' + str(msg)
for ipsec in self: if ipsec.IPsecId == ipsecid: break else: # check for IPSEC from netconfpkg.NCDevice import ConfDevice conf = ConfDevice(ipsecid) mtype = None if conf.has_key("TYPE"): mtype = conf["TYPE"] if mtype: continue unlink(dirname + entry) unlink(getRoot() + OLDSYSCONFDEVICEDIR + '/keys-' + ipsecid) self.commit() self.setunmodified() def __repr__(self): return repr(self.__dict__) def _objToStr(self, parentStr=None): # pylint: disable-msg=W0613 retstr = "" for ipsec in self: # pylint: disable-msg=W0212 retstr += ipsec._objToStr("IPsecList.%s" % (ipsec.IPsecId)) return retstr
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) })
def __init__(self, name): ConfShellVar.ConfShellVar.__init__( self, getRoot() + SYSCONFDEVICEDIR + 'route-' + name) self.chmod(0644)
class Device(Device_base): Type = ETHERNET SubType = None Priority = 0 keyid = "DeviceId" __keydict = { 'Device': 'DEVICE', 'IP': 'IPADDR', 'Netmask': 'NETMASK', 'Gateway': 'GATEWAY', 'Hostname': 'DHCP_HOSTNAME', 'PrimaryDNS': 'DNS1', 'SecondaryDNS': 'DNS2', 'Domain': 'DOMAIN', 'BootProto': 'BOOTPROTO', 'Type': 'TYPE', 'HardwareAddress': 'HWADDR', } # The following variables can be in form of for example IPADDRn where n is integer __keydictn = ["IPADDR", "NETMASK", "GATEWAY"] __intkeydict = { 'Mtu': 'MTU', 'Prefix': 'PREFIX', } __intkeydictn = ["PREFIX"] __boolkeydict = { 'OnBoot': 'ONBOOT', 'OnParent': 'ONPARENT', 'NMControlled': 'NM_CONTROLLED', 'AllowUser': '******', 'AutoDNS': 'PEERDNS', 'Slave': 'SLAVE', 'IPv6Init': 'IPV6INIT', } def __init__(self): super(Device, self).__init__() self.oldname = None def getDialog(self): return None def getWizard(self): return None def isType(self, device): raise False def testDeviceId(self, value): if re.search(r"^[a-z|A-Z|0-9\_:]+$", value): return True return False def getDeviceAlias(self): devname = self.Device if self.Alias != None and self.Alias != "": devname = devname + ':' + str(self.Alias) return devname def getRealMtu(self): out = commands.getoutput('/sbin/ip link show %s 2>/dev/null' % self.Device) next = False val = 0 try: for k in out.split(): if next: val = int(k) break if k == "mtu": next = True except ValueError: pass return val def load(self, name): conf = ConfDevice(name) self.oldname = name if not conf.has_key("DEVICE"): aliaspos = name.find(':') if aliaspos != -1: from netconfpkg.NCDeviceList import getDeviceList # ok, we have to inherit all other data from our master for dev in getDeviceList(): if dev.Device == name[:aliaspos]: self.apply(dev) break self.Device = name self.DeviceId = name for selfkey in self.__keydict.keys(): confkey = self.__keydict[selfkey] if conf.has_key(confkey) and conf[confkey]: setattr(self, selfkey, conf[confkey]) else: # if confkey is for example IPADDR, we should try also IPADDR0, IPADDR1 etc. if confkey in self.__keydictn: for i in range(10): confkeyn = confkey + str(i) if conf.has_key(confkeyn) and len(conf[confkeyn]): setattr(self, selfkey, conf[confkeyn]) break for selfkey in self.__intkeydict.keys(): confkey = self.__intkeydict[selfkey] if conf.has_key(confkey) and len(conf[confkey]): setattr(self, selfkey, conf[confkey]) else: if confkey in self.__intkeydictn: for i in range(10): confkeyn = confkey + str(i) if conf.has_key(confkeyn) and len(conf[confkeyn]): setattr(self, selfkey, conf[confkeyn]) break for selfkey in self.__boolkeydict.keys(): confkey = self.__boolkeydict[selfkey] if conf.has_key(confkey): if conf[confkey] == 'yes': setattr(self, selfkey, True) #print >> sys.stderr, self.DeviceId, selfkey, "True" #setattr(self, selfkey, True) else: setattr(self, selfkey, False) #print >> sys.stderr, self.DeviceId, selfkey, "False" #setattr(self, selfkey, False) # we need to deal with options which have default value 'yes' like NM_CONTROLLED else: if confkey != "NM_CONTROLLED": setattr(self, selfkey, False) #setattr(self, selfkey, False) # if PREFIX exists it takes preference over NETMASK if hasattr(self, 'Prefix') and len(self.Prefix): prefix = int(self.Prefix) if prefix >= 0 and prefix <= 32: netmask_str = socket.inet_ntoa( struct.pack(">I", 0xFFFFFFFF & (0xFFFFFFFF << (32 - prefix)))) self.Netmask = netmask_str if not conf.has_key("PEERDNS"): del self.AutoDNS if not self.Slave: del self.Slave if not self.Gateway: try: cfg = ConfShellVar.ConfShellVar(getRoot() + SYSCONFNETWORK) if (cfg.has_key('GATEWAY') and ((not cfg.has_key('GATEWAYDEV')) or cfg['GATEWAYDEV'] == self.Device)): gw = cfg['GATEWAY'] if gw and self.Netmask: try: network = commands.getoutput('ipcalc --network ' + str(self.IP) + ' ' + str(self.Netmask) + ' 2>/dev/null') out = commands.getoutput('ipcalc --network ' + str(gw) + ' ' + str(self.Netmask) + ' 2>/dev/null') if out == network: self.Gateway = str(gw) except: pass except EnvironmentError, msg: NC_functions.generic_error_dialog(str(msg)) try: aliaspos = self.Device.find(':') if aliaspos != -1: self.Alias = int(self.Device[aliaspos + 1:]) self.Device = self.Device[:aliaspos] except TypeError: NC_functions.generic_error_dialog( _("%s, " "Device not specified " "or alias not a number!") % self.DeviceId) #raise TypeError, _("Device not specified or alias not a number!") except ValueError: NC_functions.generic_error_dialog( _("%s, " "Device not specified " "or alias not a number!") % self.DeviceId) if not self.Alias: del self.OnParent if self.BootProto == None: if self.IP: self.BootProto = "none" else: self.BootProto = 'dhcp' if not self.Type or self.Type == "" or self.Type == _("Unknown"): from netconfpkg import NCHardwareList hwlist = NCHardwareList.getHardwareList() for hw in hwlist: if hw.Name == self.Device: self.Type = hw.Type break else: self.Type = NC_functions.getDeviceType(self.Device) if conf.has_key("RESOLV_MODS"): if conf["RESOLV_MODS"] != "no": self.AutoDNS = True else: self.AutoDNS = False # move old <id>.route files to route-<id> mfile = str(getRoot() + SYSCONFDEVICEDIR + self.DeviceId + '.route') if os.path.isfile(mfile): NC_functions.rename( mfile, getRoot() + SYSCONFDEVICEDIR + 'route-' + self.DeviceId) # load routes rconf = ConfRoute(name) for key in rconf.keys(): if key.startswith("ADDRESS"): try: p = int(key[7:]) except: continue route = Route() self.createStaticRoutes() self.StaticRoutes.append(route) route.Address = rconf['ADDRESS' + str(p)] if rconf.has_key("NETMASK" + str(p)): route.Netmask = rconf['NETMASK' + str(p)] if rconf.has_key("GATEWAY" + str(p)): route.Gateway = rconf['GATEWAY' + str(p)] self.commit() self.setunmodified()
# 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() __DVList = None __DVList_root = getRoot() def getDeviceList(refresh=None): # pylint: disable-msg=W0603 global __DVList global __DVList_root if __DVList == None or refresh or \ __DVList_root != getRoot(): __DVList = DeviceList() __DVList.load() __DVList_root = getRoot() return __DVList def getNextDev(base):
def save(self): # FIXME: [163040] "Exception Occurred" when saving # fail gracefully, with informing, which file, and why # Just to be safe... os.umask(0022) self.commit() if self.oldname and (self.oldname != self.DeviceId): for prefix in ['ifcfg-', 'route-', 'keys-']: NC_functions.rename( getRoot() + SYSCONFDEVICEDIR + prefix + self.oldname, getRoot() + SYSCONFDEVICEDIR + prefix + self.DeviceId) conf = ConfDevice(self.DeviceId) conf.fsf() if self.BootProto == None: if self.IP: self.BootProto = "none" else: self.BootProto = 'dhcp' if self.BootProto: self.BootProto = self.BootProto.lower() if self.BootProto == "static": self.BootProto = "none" # Do not set GATEWAY with dhcp if self.BootProto == 'dhcp': # [169526] lost Gateway when I change static IP by DHCP # #167593, #162902, #169113, #149780 self.Gateway = None self.IP = None self.Netmask = None for selfkey in self.__keydict.keys(): confkey = self.__keydict[selfkey] if hasattr(self, selfkey): if not conf.has_key(confkey) or not len(conf[confkey]): if confkey in self.__keydictn: # try also conf[confkey0], conf[confkey1] etc. for i in range(10): confkeyn = confkey + str(i) if conf.has_key(confkeyn) and len(conf[confkeyn]): confkey = confkeyn break 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: if not conf.has_key(confkey) or not len(conf[confkey]): if confkey in self.__intkeydictn: for i in range(10): confkeyn = confkey + str(i) if conf.has_key(confkeyn) and len(conf[confkeyn]): confkey = confkeyn break conf[confkey] = str(getattr(self, selfkey)) else: del conf[confkey] for selfkey in self.__boolkeydict.keys(): confkey = self.__boolkeydict[selfkey] if getattr(self, selfkey) == True: conf[confkey] = 'yes' elif getattr(self, selfkey) == False: conf[confkey] = 'no' else: del conf[confkey] # save also PREFIX according to NETMASK if hasattr(self, 'Netmask'): try: prefix = commands.getoutput('ipcalc --prefix ' + '0.0.0.0' + ' ' + str(self.Netmask) + ' 2>/dev/null') if prefix: conf['PREFIX'] = prefix[7:] except: pass # cleanup if self.Alias != None: # FIXME: [167991] Add consistency check for aliasing # check, if a parent device exists!!! conf['DEVICE'] = str(self.Device) + ':' + str(self.Alias) del conf['ONBOOT'] # Alias interfaces should not have a HWADDR (bug #188321, #197401) del conf['HWADDR'] else: del conf['ONPARENT'] # Recalculate BROADCAST and NETWORK values if IP and netmask are # present (#51462) # obsolete if self.IP and self.Netmask and conf.has_key('BROADCAST'): try: broadcast = commands.getoutput('ipcalc --broadcast ' + str(self.IP) + ' ' + str(self.Netmask) + ' 2>/dev/null') if broadcast: conf['BROADCAST'] = broadcast[10:] except: pass else: del conf['BROADCAST'] if self.IP and self.Netmask and conf.has_key('NETWORK'): try: network = commands.getoutput('ipcalc --network ' + str(self.IP) + ' ' + str(self.Netmask) + ' 2>/dev/null') if network: conf['NETWORK'] = network[8:] except: pass else: del conf['NETWORK'] # FIXME: RFE [174974] limitation of setting routing if self.StaticRoutes and len(self.StaticRoutes) > 0: rconf = ConfRoute(self.DeviceId) for key in rconf.keys(): del rconf[key] p = 0 for route in self.StaticRoutes: if route.Address: rconf['ADDRESS' + str(p)] = route.Address if route.Netmask: rconf['NETMASK' + str(p)] = route.Netmask if route.Gateway: rconf['GATEWAY' + str(p)] = route.Gateway p = p + 1 rconf.write() # remove empty gateway entries if not self.Gateway: del conf['GATEWAY'] for i in conf.keys(): if not conf[i] or conf[i] == "": del conf[i] # RESOLV_MODS should be PEERDNS if conf.has_key('RESOLV_MODS'): del conf['RESOLV_MODS'] # no need to write DEVICE (RHBZ#846081) if conf.has_key('DEVICE'): del conf['DEVICE'] conf.write() self.oldname = self.DeviceId
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)